text:
__author__ = 'Traphix'

import os
import time
import copy
import socket
import struct
from vpp_papi import VPP

from runtime_data import *
from hub import *
from ..config.cfg import *
from ..utils.utils import *
from ..models import *

class MSVPP():
    def __init__(self, app, msc, mysql, model=None):
        self.app                           = app
        self.msc                           = msc
        self.mysql                         = mysql
        self.model                         = model
        self.vpp                           = VPP()
        self.virtual_hosts                 = []
        self.rx_bytes                      = []
        self.rx_timer                      = time.time()
        self.tx_bytes                      = []
        self.tx_timer                      = time.time()
        self.pid                           = os.getpid()
        self.failure_recovery              = False
        self.flag_connect                  = False
        self.last_dhcp_attack_warning_time = 0

    def __call__(self, name, reply):
        if name == 'vnet_interface_combined_counters':
            self.refresh_vpp_interface_counter(reply)
        if name == 'sw_interface_set_flags':
            self.refresh_vpp_interface_status(reply)
        if name == 'dhcp_up_event':
            self.dhcp_up_event_handler(reply)
        if name == 'dhcp_warning_event':
            self.dhcp_warning_event_handler(reply)

    def serve(self):
        if app.config['MSC_ONLY_CONNECT_TO_VPP']:
            return True
        self.get_vpp_if_information()
        self.want_interfaces_events()
        self.build_env()
        self.want_interfaces_stats()
        # self.create_vhosts()
        self.want_dhcp_info()

    def rebuild(self):
        """ call this method when vpp restart but msc is still running """
        self.vpp = VPP()
        self.connect()
        self.serve()

    def connect(self):
        self.vpp.connect(name='msc')
        self.vpp.register_event_callback(self)
        self.app.logger.debug("vpp_papi connected")
        self.flag_connect = True

    def disconnect(self):
        try:
            self.vpp.disconnect()
        except Exception as _e:
            pass
        self.flag_connect = False
        self.app.logger.debug("vpp_papi disconnected")

    def check_vpp_intfs_up_down(self):
        self.connect()
        for intf in self.vpp.api.sw_interface_dump():
            if intf.admin_up_down == 0 and intf.interface_name.decode().split('\x00')[0] != 'local0':
                self.failure_recovery = False
                app.logger.debug("vpp interfaces check - vpp all interfaces are down")
                return False
        self.failure_recovery = True
        app.logger.debug("vpp interfaces check - vpp all interfaces are up")
        return True

    def get_vpp_if_information(self):
        """ get_vpp_if_information """
        if self.msc == None:
            return False
        interfaces = self.vpp.api.sw_interface_dump()
        for interface in interfaces:
            self.rx_bytes.append(0)
            self.tx_bytes.append(0)
            for (key, value) in self.msc.config["interfaces_names"].items():
                if_name = interface.interface_name.decode().split('\x00')[0]
                if key == if_name:
                    self.msc.config["interfaces_names"][key]["mac"] = \
                        mac2str(interface.l2_address, interface.l2_address_length)
                    self.msc.config["interfaces_names"][key]["sw_if_index"] = \
                        interface.sw_if_index

                    # register_interface
                    name = self.msc.config["interfaces_names"][key]["line_name"] + \
                           ("_in" if self.msc.config["interfaces_names"][key]["in_out"] == 1 else "_out")
                    mac = self.msc.config["interfaces_names"][key]["mac"]
                    sw_if_index = interface.sw_if_index
                    self.register_interface(name, mac, sw_if_index, key)

                    # init runtime_clients lines
                    # self.runtime_clients[self.msc.config["interfaces_names"][key]["line_name"]] = []

                    # init msc runtime interfaces
                    self.msc.runtime_vpp_interface_status[key] = {}
                    self.msc.runtime_vpp_interface_status[key]["line_name"]   = \
                        self.msc.config["interfaces_names"][key]["line_name"]
                    self.msc.runtime_vpp_interface_status[key]["port_num"]    = \
                        self.msc.config["interfaces_names"][key]["port_num"]
                    self.msc.runtime_vpp_interface_status[key]["custom_name"] = \
                        self.msc.config["interfaces_names"][key]["custom_name"] + u"进口" \
                        if self.msc.config["interfaces_names"][key]["in_out"] else \
                        self.msc.config["interfaces_names"][key]["custom_name"] + u"出口"
                    self.msc.runtime_vpp_interface_status[key]["state"] = INT_ISUP[interface.link_up_down]
                    self.msc.runtime_vpp_interface_status[key]["rx_packets"]  = 0
                    self.msc.runtime_vpp_interface_status[key]["tx_packets"]  = 0
                    self.msc.runtime_vpp_interface_status[key]["rx_bytes"]    = 0
                    self.msc.runtime_vpp_interface_status[key]["tx_bytes"]    = 0
                    self.msc.runtime_vpp_interface_status[key]["rx_speed"]    = 0
                    self.msc.runtime_vpp_interface_status[key]["tx_speed"]    = 0

        if self.app:
            self.app.logger.debug("initialized vpp_if_information")

    def want_interfaces_events(self):
        self.vpp.api.want_interface_events(enable_disable=1, pid=self.pid)
        self.app.logger.debug("start vpp interface events receiving")

    def want_interfaces_stats(self):
        self.vpp.api.want_stats(enable_disable=1, pid=self.pid)
        self.app.logger.debug("start vpp interface counter refreshing")

    def want_dhcp_info(self):
        client_inf = []
        server_inf = []
        names = sorted(self.msc.runtime_intfs.__dict__.keys())
        # print names

        if self.msc.config["global_config"]["DHCP"] == "0":
            server_mode = 0
            for name in names:
                if "_in" in name:
                    client_inf.append(self.msc.runtime_intfs.__dict__[name].sw_if_index)
                elif "_out" in name:
                    server_inf.append(self.msc.runtime_intfs.__dict__[name].sw_if_index)
        else:
            server_mode = 1
            for name in names:
                if "_in" in name:
                    client_inf.append(self.msc.runtime_intfs.__dict__[name].sw_if_index)
                if 'host-vpp-line' in name:
                    server_inf.append(self.msc.runtime_intfs.__dict__[name].sw_if_index)

        # server_inf = [7,7,7]
        self.app.logger.debug("dhcp interfaces relations - %s : %s", client_inf, server_inf)

        client_inf = ''.join([hex(i).split('x')[1] if i > 15 else ('0' + hex(i).split('x')[1]) for i in client_inf]).decode('hex')
        server_inf = ''.join([hex(i).split('x')[1] if i > 15 else ('0' + hex(i).split('x')[1]) for i in server_inf]).decode('hex')

        ip_pool_size = 0
        for pool in self.msc.config["nip_net_seg"]:
            ip_pool_size += (~ip2long(pool["mask"])) & 0xFFFFFFFF

        rv = self.dhcp_want_info(
            pid          = self.pid,
            server_mode  = server_mode,
            client_inf   = client_inf,
            server_inf   = server_inf,
            length       = len(client_inf),
            ip_pool_size = ip_pool_size
        )
        if rv.retval == 0:
            self.app.logger.debug("start dhcp info want")
            return True
        else:
            self.app.logger.error("failed to start dhcp info want")
            return False

    def build_env(self):
        if self.failure_recovery:
            return
        self.ms_vpp_global_init()

        self.create_vpp_dnat()

        for line in self.msc.runtime_lines_vlans:
            self.create_line(line=line)
            self.create_dhcp_line(line=line)
            for vlan in self.msc.runtime_lines_vlans[line]:
                if vlan == 0:
                    continue
                self.create_line(line=line, vlan=vlan)
                self.create_dhcp_line(line=line, vlan=vlan)

        if self.msc.config["global_config"]["DHCP"] == "1":
            if self.msc.config["global_config"]["fDNS"]:
                self.vpp.mc_add_del_session(is_add=1,
                                            table_index=TABLE_DNS_OUT2IN_IN2IN,
                                            match_dst_ip=self.msc.config["global_config"]["fDNS"],
                                            hit_next_index=DNS_NODE)
            if self.msc.config["global_config"]["sDNS"]:
                self.vpp.mc_add_del_session(is_add=1,
                                            table_index=TABLE_DNS_OUT2IN_IN2IN,
                                            match_dst_ip=self.msc.config["global_config"]["sDNS"],
                                            hit_next_index=DNS_NODE)

    def ms_vpp_global_init(self):
        responses = []
        # vppctl set interface ip table local0 10
        rv = self.sw_interface_set_table(sw_if_index=0, table_id=10)

        # vppctl ip route add 0.0.0.0/0 lookup in table 10
        rv = self.ip_add_del_route(is_add=1,
                                   dst_address='0.0.0.0',
                                   dst_address_length=0,
                                   next_hop_address='0.0.0.0',
                                   next_hop_table_id=10,
                                   create_vrf_if_needed=1)

        # vppctl ms classify del tables
        rv = self.mc_del_tables()
        # vppctl ms classify init tables nbuckets-t1 10 memsize-t1 1M nbuckets-t2 10 memsize-t2 1M
        rv = self.mc_initial_tables(nbuckets_t1=20000,
                                    memsize_t1=0x4000000,
                                    nbuckets_t2=1024,
                                    memsize_t2=0x200000)
        for rv in responses:
            if rv.retval:
                app.logger.error("failed to ms_vpp_global_init")
                return False
        else:
            app.logger.debug("initialized ms_vpp_global_config")
            return True

    def create_dhcp_line(self, line, vlan=0):
        if self.msc.config["global_config"]["DHCP"] == "0":
            return

        if self.failure_recovery:
            return

        responses = []

        line = 'vpp-' + line

        if vlan == 0:
            rv = self.af_packet_create(host_if_name=line)
            responses.append(rv)

            rv = self.sw_interface_set_flags(sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line).sw_if_index,
                                             link_up_down=1,
                                             admin_up_down=1)
            responses.append(rv)

            rv = self.feature_enable_disable(enable=0,
                                             sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line).sw_if_index,
                                             feature_name='ip4-drop',
                                             arc_name='ip4-unicast')
            responses.append(rv)

            rv = self.mc_set_interface(is_add=1,
                                       sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line).sw_if_index)
            responses.append(rv)
        else:
            rv = self.create_vlan_subif(sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line).sw_if_index,
                                        vlan=vlan)
            responses.append(rv)

            rv = self.sw_interface_set_flags(sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line + '_' + str(vlan)).sw_if_index,
                                             link_up_down=1,
                                             admin_up_down=1)
            responses.append(rv)

            rv = self.feature_enable_disable(enable=0,
                                             sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line + '_' + str(vlan)).sw_if_index,
                                             feature_name='ip4-drop',
                                             arc_name='ip4-unicast')
            responses.append(rv)

            rv = self.mc_set_interface(is_add=1,
                                       sw_if_index=getattr(self.msc.runtime_intfs, 'host-' + line + '_' + str(vlan)).sw_if_index)
            responses.append(rv)

        for rv in responses:
            if rv.retval:
                app.logger.error("failed to create_dhcp_line %s vlan %s", line, vlan)
                return False
        else:
            app.logger.debug("create_dhcp_line %s vlan %s", line, vlan)
            return True

    def create_vpp_dnat(self):
        if app.config['MSC_CREATE_VPP_DNAT'] == 0:
            return

        responses = []

        if self.failure_recovery:
            return True

        rv = self.af_packet_create(host_if_name='vpp-dnat')
        responses.append(rv)

        rv = self.sw_interface_set_flags(sw_if_index=getattr(self.msc.runtime_intfs, 'host-vpp-dnat').sw_if_index,
                                         link_up_down=1,
                                         admin_up_down=1)
        responses.append(rv)

        rv = self.mc_set_honeyd_interface(sw_if_index=getattr(self.msc.runtime_intfs, 'host-vpp-dnat').sw_if_index)

        responses.append(rv)

        rv = self.sw_interface_set_table(sw_if_index=getattr(self.msc.runtime_intfs, 'host-vpp-dnat').sw_if_index,
                                         table_id=100)
        responses.append(rv)

        rv = self.sw_interface_add_del_address(is_add=1,
                                               sw_if_index=getattr(self.msc.runtime_intfs, 'host-vpp-dnat').sw_if_index,
                                               addr='192.168.1.1',
                                               addr_len=30)
        responses.append(rv)

        rv = self.ip_add_del_route(is_add=1,
                                   table_id=100,
                                   dst_address='0.0.0.0',
                                   dst_address_length=0,
                                   next_hop_address='192.168.1.2',
                                   next_hop_sw_if_index=getattr(self.msc.runtime_intfs, 'host-vpp-dnat').sw_if_index)
        responses.append(rv)

        for rv in responses:
            if rv.retval:
                app.logger.error("failed to create vpp dnat")
                return False
        else:
            app.logger.debug("create vpp dnat")
            return True

    def create_line(self, line, vlan=0):
        line_in = (line + '_in_' + str(vlan)) if vlan else (line + '_in')
        line_out = (line + '_out_' + str(vlan)) if vlan else (line + '_out')

        if self.failure_recovery:
            return True

        responses = []

        if vlan:
            rv = self.create_vlan_subif(sw_if_index=getattr(self.msc.runtime_intfs, line + "_in").sw_if_index,
                                        vlan=vlan)
            responses.append(rv)

            rv = self.create_vlan_subif(sw_if_index=getattr(self.msc.runtime_intfs, line + "_out").sw_if_index,
                                        vlan=vlan)
            responses.append(rv)

        rv = self.feature_enable_disable(enable=0,
                                         sw_if_index=getattr(self.msc.runtime_intfs, line_in).sw_if_index,
                                         feature_name='ip4-drop',
                                         arc_name='ip4-unicast')
        responses.append(rv)

        rv = self.feature_enable_disable(enable=0,
                                         sw_if_index=getattr(self.msc.runtime_intfs, line_out).sw_if_index,
                                         feature_name='ip4-drop',
                                         arc_name='ip4-unicast')
        responses.append(rv)

        rv = self.sw_interface_set_flags(sw_if_index=getattr(self.msc.runtime_intfs, line_in).sw_if_index,
                                         link_up_down=1,
                                         admin_up_down=1)
        responses.append(rv)

        rv = self.sw_interface_set_flags(sw_if_index=getattr(self.msc.runtime_intfs, line_out).sw_if_index,
                                         link_up_down=1,
                                         admin_up_down=1)
        responses.append(rv)

        if vlan == 0:
            rv = self.sw_interface_set_promiscuous(flag=1,
                                                   sw_if_index=getattr(self.msc.runtime_intfs, line_in).sw_if_index)

            rv = self.sw_interface_set_promiscuous(flag=1,
                                                   sw_if_index=getattr(self.msc.runtime_intfs, line_out).sw_if_index)

        rv = self.mc_set_interface(is_add=1,
                                   sw_if_index=getattr(self.msc.runtime_intfs, line_in).sw_if_index)
        responses.append(rv)

        rv = self.mc_set_interface(is_add=1,
                                   sw_if_index=getattr(self.msc.runtime_intfs, line_out).sw_if_index)
        responses.append(rv)

        for rv in responses:
            if rv.retval:
                app.logger.error("failed to create in_out line %s vlan %s", line, vlan)
                return False
        else:
            app.logger.debug("create %s vlan %s", line, vlan)
            return True

    def register_interface(self, name, mac, sw_if_index, sw_if_name):
        if self.failure_recovery:
            return

        k = sw_if_name.split('.')[0]

        if '.' in sw_if_name:
            vlan = int(sw_if_name.split('.')[1])
        else:
            vlan = 0

        tmp             = Empty()
        tmp.mac         = mac
        tmp.sw_if_index = sw_if_index
        tmp.sw_if_name  = sw_if_name
        tmp.vlan        = vlan

        if 'host' in name:
            newobj = self.model(
                sw_if_name  = sw_if_name,
                sw_if_index = sw_if_index,
                mac         = mac,
                vlan        = vlan
            )
        else:
            tmp.line_name = self.msc.config["interfaces_names"][k]["line_name"]
            newobj = self.model(
                sw_if_name  = sw_if_name,
                sw_if_index = sw_if_index,
                line_name   = tmp.line_name,
                in_out      = self.msc.config["interfaces_names"][k]["in_out"],
                mac         = mac,
                vlan        = vlan,
                custom_name = self.msc.config["interfaces_names"][k]["custom_name"]
            )

        setattr(self.msc.runtime_intfs, name, tmp)
        self.mysql.save(newobj)

    def refresh_vpp_interface_status(self, reply):
        if self.flag_connect == False:
            return False
        for interface in self.msc.config["interfaces_names"]:
            if self.msc.config["interfaces_names"][interface]["sw_if_index"] == reply.sw_if_index:
                self.msc.runtime_vpp_interface_status[interface]["state"] = INT_ISUP[reply.link_up_down]

    def refresh_vpp_interface_counter(self, reply):
        if self.flag_connect == False:
            return False

        if reply.vnet_counter_type == 0:
            # RX
            index = range(reply.first_sw_if_index, reply.count)
            rx_packets = [reply.data[i].packets for i in index]
            rx_bytes = [reply.data[i].bytes for i in index]
            inc = time.time() - self.rx_timer
            self.rx_timer = time.time()
            rx_speed = list(map(lambda x: float(x[0] - x[1])/inc, zip(rx_bytes, self.rx_bytes)))
            self.rx_bytes = rx_bytes
            for interface in self.msc.runtime_vpp_interface_status:
                self.msc.runtime_vpp_interface_status[interface]["rx_packets"]  = \
                    rx_packets[self.msc.config["interfaces_names"][interface]["sw_if_index"]]
                self.msc.runtime_vpp_interface_status[interface]["rx_bytes"]    = \
                    rx_bytes[self.msc.config["interfaces_names"][interface]["sw_if_index"]]
                self.msc.runtime_vpp_interface_status[interface]["rx_speed"]    = \
                    rx_speed[self.msc.config["interfaces_names"][interface]["sw_if_index"]]
        else:
            # TX
            index = range(reply.first_sw_if_index, reply.count)
            tx_packets = [reply.data[i].packets for i in index]
            tx_bytes = [reply.data[i].bytes for i in index]
            inc = time.time() - self.tx_timer
            self.tx_timer = time.time()
            tx_speed = list(map(lambda x: float(x[0] - x[1])/inc, zip(tx_bytes, self.tx_bytes)))
            self.tx_bytes = tx_bytes
            for interface in self.msc.runtime_vpp_interface_status:
                self.msc.runtime_vpp_interface_status[interface]["tx_packets"]  = \
                    tx_packets[self.msc.config["interfaces_names"][interface]["sw_if_index"]]
                self.msc.runtime_vpp_interface_status[interface]["tx_bytes"]    = \
                    tx_bytes[self.msc.config["interfaces_names"][interface]["sw_if_index"]]
                self.msc.runtime_vpp_interface_status[interface]["tx_speed"]    = \
                    tx_speed[self.msc.config["interfaces_names"][interface]["sw_if_index"]]

    def dhcp_up_event_handler(self, reply):
        self.msc.dhcp_up_event_q.put_nowait(reply)
        # pass

    def dhcp_warning_event_handler(self, reply):
        """ mac_count, attack_type, rx_inf_index """
        # check two dhcp_attack_warning interval
        now = time.time()
        if now - self.last_dhcp_attack_warning_time < 10:
            new_obj = LogDoSAttack(
                attack_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
                attack_type = DHCP_ATTACK[reply.attack_type],
                line_name   = self.mysql.get_value(LogInterfaces, {"sw_if_index": reply.rx_inf_index}, "line_name")
            )
            self.mysql.save(new_obj)
        self.last_dhcp_attack_warning_time = now
        # # send trust_macs to vpp
        # trust_macs = []
        # for line in self.msc.runtime_clients:
        #     for client in self.msc.runtime_clients[line]:
        #         trust_macs.append({
        #             "client_inf" : client.intf_inner,
        #             "mac_addr"   : client.mac.replace(":", "").decode('hex')
        #         })
        # self.dhcp_down_mac(count=len(trust_macs), trust_macs=trust_macs)

    def apply_acl_rules(self, rules):
        """
        {'sip': u'2.2.2.2/24', 'protocol': u'6', 'ruleid': u'2', 'portconf': u'3', 'dport': u'4', 'sport': u'2,3', 'ipconf': u'1'}
        """
        e = MSCError()
        new_rules = []
        format_rules = []
        for rule in rules:
            tmp = []
            del rule['ipconf']
            del rule['ruleid']
            for key, value in rule.items():
                if 'ip' in key:
                    rule[key + "_length"] = int(rule[key].split('/')[1])
                    rule[key] = rule[key].split('/')[0]
                elif 'protocol' == key:
                    rule[key] = int(rule[key])
                    if rule[key] == 138:
                        rule[key] = 0
                elif 'port' in key and key != 'portconf':
                    rule[key] = strlist_to_intlist(rule[key])
            if rule.has_key('portconf'):
                if rule['portconf'] == '0':
                    tmp.append(rule)
                elif rule['portconf'] == '1':
                    for port in rule['sport']:
                        t = copy.deepcopy(rule)
                        del t['sport']
                        t['sport'] = port
                        tmp.append(t)
                elif rule['portconf'] == '2':
                    for port in rule['dport']:
                        t = copy.deepcopy(rule)
                        del t['dport']
                        t['dport'] = port
                        tmp.append(t)
                elif rule['portconf'] == '3':
                    for sport in rule['sport']:
                        for dport in rule['dport']:
                            t = copy.deepcopy(rule)
                            del t['sport']
                            del t['dport']
                            t['sport'] = sport
                            t['dport'] = dport
                            tmp.append(t)
                else:
                    for port in rule['ports']:
                        t = copy.deepcopy(rule)
                        t['sport'] = port
                        del t['ports']
                        tmp.append(t)
                        t = copy.deepcopy(rule)
                        del t['ports']
                        t['dport'] = port
                        tmp.append(t)
            else:
                tmp.append(rule)

            for i in tmp:
                if i.has_key('portconf'):
                    del i['portconf']
                if i.has_key('ports'):
                    del  i['ports']
            new_rules += tmp

        format_rules = [self.create_acl_rule(**kw) for kw in new_rules]

        # add default all pass rule
        format_rules.append(
            self.create_acl_rule(
                is_permit=1, sport=-1, dport=-1, protocol=0,
                sip_length=0, sip='0.0.0.0',
                dip_length=0, dip='0.0.0.0'
            )
        )
        # for i in format_rules:
        #     print i
        if self.acl_dump():
            rv = self.acl_add_replace(
                acl_index=self.msc.runtime_acl_index,
                r=format_rules,
                count=len(format_rules),
                tag='MS firewall rules'
            )
            if rv.retval:
                e.set_msg(u"配置防火墙规则失败")
                return e
        else:
            rv = self.acl_add_replace(
                r=format_rules,
                count=len(format_rules),
                tag='MS firewall rules'
            )
            if rv.retval:
                e.set_msg(u"配置防火墙规则失败")
                return e
            self.msc.runtime_acl_index = rv.acl_index
        for name, value in self.msc.runtime_intfs.__dict__.items():
            rv = self.acl_interface_add_del(
                is_add=1,
                is_input=1,
                sw_if_index=value.sw_if_index,
                acl_index=self.msc.runtime_acl_index
            )
            if rv.retval:
                e.set_msg(u"应用防火墙规则失败")
        return e

    def apply_macip_acl_rules(self, rules, is_permit):
        format_rules = []
        format_rules = [self.create_macip_acl_rule(is_permit=is_permit, src_mac=rule['mac']) \
                        for rule in rules]
        # print format_rules
        msg = u"配置白名单失败" if is_permit == 1 else u"配置黑名单失败"
        print format_rules
        rv = self.macip_acl_add(tag='MS macip rules', r=format_rules, count=len(format_rules))

        if rv.retval:
            e.set_msg(msg)
            return e
        self.msc.runtime_macip_acl_index = rv.acl_index
        for name, value in self.msc.runtime_intfs.__dict__.items():
            rv = self.macip_acl_interface_add_del(
                is_add=1,
                sw_if_index=value.sw_if_index,
                acl_index=self.msc.runtime_macip_acl_index
            )
            if rv.retval:
                e.set_msg(msg)
        return e

    def create_acl_rule(self, is_ip6=0, is_permit=0,
                    sport=-1, dport=-1, protocol=-1,
                    sip_length=0, sip='0.0.0.0',
                    dip_length=0, dip='0.0.0.0'):
        if protocol == -1:
            return

        sip = socket.inet_pton(socket.AF_INET, sip)
        dip = socket.inet_pton(socket.AF_INET, dip)

        if sport == -1:
            sport_from = 0
            sport_to   = 65535
        else:
            sport_from = sport
            sport_to   = sport

        if dport == -1:
            dport_from = 0
            dport_to   = 65535
        else:
            dport_from = dport
            dport_to   = dport

        rule = ({'is_permit': is_permit, 'is_ipv6': is_ip6, 'proto': protocol,
                 'srcport_or_icmptype_first': sport_from,
                 'srcport_or_icmptype_last': sport_to,
                 'src_ip_prefix_len': sip_length,
                 'src_ip_addr': sip,
                 'dstport_or_icmpcode_first': dport_from,
                 'dstport_or_icmpcode_last': dport_to,
                 'dst_ip_prefix_len': dip_length,
                 'dst_ip_addr': dip})
        return rule

    def create_macip_acl_rule(self,
                              is_permit,
                              src_mac,
                              src_mac_mask='FF:FF:FF:FF:FF:FF',
                              src_ip_addr='0.0.0.0',
                              src_ip_prefix_len=0,
                              is_ipv6=0):
        rule = ({'is_permit': is_permit, 'is_ipv6': is_ipv6,
                 'src_mac': src_mac.replace(":", "").decode('hex'),
                 'src_mac_mask': src_mac_mask.replace(":", "").decode('hex'),
                 'src_ip_addr': socket.inet_pton(socket.AF_INET, src_ip_addr),
                 'src_ip_prefix_len': src_ip_prefix_len})
        return rule

    @retval_check
    def mc_add_del_session(self, is_add, table_index, match_dst_ip, hit_next_index, lip="0.0.0.0"):
        return self.vpp.api.mc_add_del_session(
            is_add=is_add,
            table_index=table_index,
            match_dst_ip=socket.inet_pton(socket.AF_INET, match_dst_ip),
            lip=socket.inet_pton(socket.AF_INET, lip),
            hit_next_index=hit_next_index
        )

    @retval_check
    def mc_set_interface(self, is_add, sw_if_index):
        return self.vpp.api.mc_set_interface(
            is_add=is_add,
            sw_if_index=sw_if_index
        )

    @retval_check
    def mc_del_tables(self):
        return self.vpp.api.mc_del_tables()

    @retval_check
    def mc_initial_tables(self, nbuckets_t1, memsize_t1, nbuckets_t2, memsize_t2):
        return self.vpp.api.mc_initial_tables(
            nbuckets_t1  = nbuckets_t1,
            memsize_t1   = memsize_t1,
            nbuckets_t2  = nbuckets_t2,
            memsize_t2   = memsize_t2
        )

    @retval_check
    def snat_add_static_mapping(
            self,
            local_ip,
            external_ip=0,
            external_sw_if_index=0xFFFFFFFF,
            local_port=0,
            external_port=0,
            addr_only=1,
            vrf_id=0,
            protocol=0,
            is_add=1,
            is_ip4=1):

        return self.vpp.api(
            is_add=is_add,
            is_ip4=is_ip4,
            addr_only=addr_only,
            local_ip_address=socket.inet_pton(socket.AF_INET, local_ip),
            external_ip_address=socket.inet_pton(socket.AF_INET, external_ip),
            local_port=local_port,
            external_port=external_port,
            external_sw_if_index=external_sw_if_index,
            vrf_id=vrf_id,
            protocol=protocol
        )

    @retval_check
    def ms_in2in_add_address_mapping(self, is_add, link_ip_address, virtual_ip_address):
        return self.vpp.api.ms_in2in_add_address_mapping(
            is_add=1,
            link_ip_address=socket.inet_pton(socket.AF_INET, link_ip_address),
            virtual_ip_address=socket.inet_pton(socket.AF_INET, virtual_ip_address)
        )

    @retval_check
    def dns_proxy_add_del(self, is_add, dname, vip):
        return self.vpp.api.dns_proxy_add_del(
            is_add=is_add,
            dname=dname,
            vip=ip2long(vip)
        )

    @retval_check
    def dns_proxy_add_del_ptr(self, is_add, lip, dname):
        return self.vpp.api.dns_proxy_add_del_ptr(
            is_add=is_add,
            lip=ip2long(lip),
            dname=dname
        )

    @retval_check
    def ip_add_del_route(
            self,
            dst_address,
            dst_address_length,
            next_hop_address,
            next_hop_sw_if_index=0xFFFFFFFF,
            table_id=0,
            next_hop_table_id=0,
            next_hop_weight=1,
            next_hop_n_out_labels=0,
            next_hop_out_label_stack=[],
            next_hop_via_label=0xFFFFF+1,
            create_vrf_if_needed=0,
            is_resolve_host=0,
            is_resolve_attached=0,
            classify_table_index=0xFFFFFFFF,
            is_add=1,
            is_drop=0,
            is_unreach=0,
            is_prohibit=0,
            is_ipv6=0,
            is_local=0,
            is_classify=0,
            is_multipath=0,
            not_last=0):

        return self.vpp.api.ip_add_del_route(
            next_hop_sw_if_index=next_hop_sw_if_index,
            table_id=table_id,
            classify_table_index=classify_table_index,
            next_hop_table_id=next_hop_table_id,
            create_vrf_if_needed=create_vrf_if_needed,
            is_add=is_add,
            is_drop=is_drop,
            is_unreach=is_unreach,
            is_prohibit=is_prohibit,
            is_ipv6=is_ipv6,
            is_local=is_local,
            is_classify=is_classify,
            is_multipath=is_multipath,
            is_resolve_host=is_resolve_host,
            is_resolve_attached=is_resolve_attached,
            not_last=not_last,
            next_hop_weight=next_hop_weight,
            dst_address_length=dst_address_length,
            dst_address=socket.inet_pton(socket.AF_INET, dst_address),
            next_hop_address=socket.inet_pton(socket.AF_INET, next_hop_address),
            next_hop_n_out_labels=next_hop_n_out_labels,
            next_hop_via_label=next_hop_via_label,
            next_hop_out_label_stack=next_hop_out_label_stack)

    @retval_check
    def ms_arp_table_add_del(self, isadd, ip):
        return self.vpp.api.ms_arp_table_add_del(
            isadd=isadd,
            ip=ip2long(ip)
        )

    @retval_check
    def create_subif(self, sw_if_index, sub_id, outer_vlan_id, inner_vlan_id,
                     no_tags=0, one_tag=0, two_tags=0, dot1ad=0, exact_match=0,
                     default_sub=0, outer_vlan_id_any=0, inner_vlan_id_any=0):

        return self.vpp.api.create_subif(
            sw_if_index=sw_if_index,
            sub_id=sub_id,
            no_tags=no_tags,
            one_tag=one_tag,
            two_tags=two_tags,
            dot1ad=dot1ad,
            exact_match=exact_match,
            default_sub=default_sub,
            outer_vlan_id_any=outer_vlan_id_any,
            inner_vlan_id_any=inner_vlan_id_any,
            outer_vlan_id=outer_vlan_id,
            inner_vlan_id=inner_vlan_id
        )

    @retval_check
    def create_vlan_subif(self, sw_if_index, vlan):
        rv = self.vpp.api.create_vlan_subif(
            sw_if_index=sw_if_index,
            vlan_id=vlan
        )
        if rv.retval == 0:
            for name, value in self.msc.runtime_intfs.__dict__.items():
                if value.sw_if_index == sw_if_index:
                    phy_name = value.sw_if_name + "." + str(vlan)
                    self.register_interface(name + "_" + str(vlan), value.mac, rv.sw_if_index, phy_name)
        return rv

    @retval_check
    def feature_enable_disable(self, enable, sw_if_index, arc_name, feature_name):
        return self.vpp.api.feature_enable_disable(
            enable=enable,
            sw_if_index=sw_if_index,
            arc_name=arc_name,
            feature_name=feature_name
        )

    @retval_check
    def sw_interface_set_flags(self, sw_if_index, admin_up_down,
                               link_up_down=0, deleted=0):

        return self.vpp.api.sw_interface_set_flags(
            sw_if_index=sw_if_index,
            admin_up_down=admin_up_down,
            link_up_down=link_up_down,
            deleted=deleted
        )

    @retval_check
    def snat_add_static_mapping(
            self,
            local_ip_address,
            external_ip_address=0,
            external_sw_if_index=0xFFFFFFFF,
            local_port=0,
            external_port=0,
            addr_only=1,
            vrf_id=0,
            protocol=0,
            is_add=1,
            is_ip4=1):

        return self.vpp.api.snat_add_static_mapping(
            is_add=is_add,
            is_ip4=is_ip4,
            addr_only=addr_only,
            local_ip_address=socket.inet_pton(socket.AF_INET, local_ip_address),
            external_ip_address=socket.inet_pton(socket.AF_INET, external_ip_address),
            local_port=local_port,
            external_port=external_port,
            external_sw_if_index=external_sw_if_index,
            vrf_id=vrf_id,
            protocol=protocol
        )

    @retval_check
    def sw_interface_set_promiscuous(self, flag, sw_if_index):
        return self.vpp.api.sw_interface_set_promiscuous(
            flag=flag,
            sw_if_index=sw_if_index
        )

    @retval_check
    def ip_neighbor_add_del(self,
                            sw_if_index,
                            mac_address,
                            dst_address,
                            is_add=1,
                            is_ipv6=0,
                            is_static=0,
                            is_no_adj_fib=0,
                            ):

        return self.vpp.api.ip_neighbor_add_del(
            sw_if_index=sw_if_index,
            is_add=is_add,
            is_ipv6=is_ipv6,
            is_static=is_static,
            is_no_adj_fib=is_no_adj_fib,
            mac_address=mac_address.replace(":", "").decode('hex'),
            dst_address=socket.inet_pton(socket.AF_INET, dst_address)
        )

    @retval_check
    def acl_add_replace(self,
                        r,
                        count,
                        tag='',
                        acl_index=0xFFFFFFFF):

        return self.vpp.api.acl_add_replace(
            acl_index=acl_index,
            r=r,
            count=count,
            tag=tag
        )

    @retval_check
    def acl_interface_add_del(self, is_add, is_input, sw_if_index, acl_index):
        return self.vpp.api.acl_interface_add_del(
            is_add=is_add,
            is_input=is_input,
            sw_if_index=sw_if_index,
            acl_index=acl_index
        )

    @retval_check
    def acl_dump(self, acl_index=0xFFFFFFFF):
        return self.vpp.api.acl_dump(acl_index=acl_index)

    @retval_check
    def af_packet_create(self, host_if_name, hw_addr="00:00:00:00:00:00", use_random_hw_addr=1):
        rv = self.vpp.api.af_packet_create(
            host_if_name=host_if_name,
            hw_addr=hw_addr.replace(":", "").decode('hex'),
            use_random_hw_addr=use_random_hw_addr
        )
        if rv.retval == 0:
            for intf in self.vpp.api.sw_interface_dump():
                if intf.sw_if_index == rv.sw_if_index:
                    mac = mac2str(intf.l2_address, intf.l2_address_length)
                    sw_if_name = intf.interface_name.decode().split('\x00')[0]
            self.register_interface(sw_if_name, mac, rv.sw_if_index, sw_if_name)
        return rv

    @retval_check
    def sw_interface_set_table(self, sw_if_index, table_id, is_ipv6=0):
        return self.vpp.api.sw_interface_set_table(
            sw_if_index=sw_if_index,
            is_ipv6=is_ipv6,
            vrf_id=table_id
        )

    @retval_check
    def sw_interface_add_del_address(self, sw_if_index, addr, addr_len,
                                     is_ipv6=0, is_add=1, del_all=0):
        return self.vpp.api.sw_interface_add_del_address(
            sw_if_index=sw_if_index,
            is_add=is_add,
            is_ipv6=is_ipv6,
            del_all=del_all,
            address_length=addr_len,
            address=socket.inet_pton(socket.AF_INET, addr)
        )

    @retval_check
    def mc_set_honeyd_interface(self, sw_if_index):
        return self.vpp.api.mc_set_honeyd_interface(
            sw_if_index=sw_if_index
        )

    @retval_check
    def dhcp_down_offer(self, pid, broadcast, deny_flag, dhcp_type, rx_sw_if_index, tx_sw_if_index, client_mac,
                        net_ip, net_ip_mask, net_ip_gw, link_ip, link_ip_mask, link_ip_gw, server_ip, dns_server_ip,
                        lease, lease_renewal, lease_rebind, transaction_id, eth_header, vlan_flag, net_ip_broadcast,
                        link_ip_broadcast):
        return self.vpp.api.dhcp_down_offer(
            pid               = pid,
            broadcast         = broadcast,
            deny_flag         = deny_flag,
            dhcp_type         = dhcp_type,
            rx_sw_if_index    = rx_sw_if_index,
            tx_sw_if_index    = tx_sw_if_index,
            client_mac        = client_mac,
            net_ip            = net_ip,
            net_ip_mask       = net_ip_mask,
            net_ip_gw         = net_ip_gw,
            link_ip           = link_ip,
            link_ip_mask      = link_ip_mask,
            link_ip_gw        = link_ip_gw,
            server_ip         = server_ip,
            dns_server_ip     = dns_server_ip,
            lease             = lease,
            lease_renewal     = lease_renewal,
            lease_rebind      = lease_rebind,
            transaction_id    = transaction_id,
            eth_header        = eth_header,
            vlan_flag         = vlan_flag,
            net_ip_broadcast  = net_ip_broadcast,
            link_ip_broadcast = link_ip_broadcast
        )

    @retval_check
    def dhcp_want_info(self, pid, server_mode, client_inf, server_inf, length, ip_pool_size):
        return self.vpp.api.dhcp_want_info(
            pid          = pid,
            server_mode  = server_mode,
            client_inf   = client_inf,
            server_inf   = server_inf,
            length       = length,
            ip_pool_size = ip_pool_size
        )

    @retval_check
    def dhcp_down_timeout(self, pid, client_mac, link_ip, link_ip_mask, link_ip_gw, server_ip):
        return self.vpp.api.dhcp_down_timeout(
            pid          = pid,
            client_mac   = client_mac.replace(":", "").decode('hex'),
            link_ip      = ip2long(link_ip),
            link_ip_mask = ip2long(link_ip_mask),
            link_ip_gw   = ip2long(link_ip_gw),
            server_ip    = ip2long(server_ip)
        )

    @retval_check
    def dhcp_down_mac(self, count, trust_macs):
        return self.vpp.api.dhcp_down_mac(count=count, r=trust_macs)

    @retval_check
    def ms_arp_honeyd_table_add_del(self, isadd, startip, endip):
        return self.vpp.api.ms_arp_honeyd_table_add_del(
            isadd   = isadd,
            startip = startip,
            endip   = endip
        )

    @retval_check
    def ms_in2in_tcp_session_vips_dump(self):
        return self.vpp.api.ms_in2in_tcp_session_vips_dump()

    @retval_check
    def macip_acl_add(self, count, r, tag=''):
        return self.vpp.api.macip_acl_add(tag=tag, r=r, count=count)

    @retval_check
    def macip_acl_del(self, acl_index):
        return self.vpp.api.macip_acl_del(acl_index=acl_index)

    @retval_check
    def macip_acl_interface_add_del(self, is_add, sw_if_index, acl_index):
        return self.vpp.api.macip_acl_interface_add_del(is_add=is_add,
                                                        sw_if_index=sw_if_index,
                                                        acl_index=acl_index)

    @retval_check
    def macip_acl_dump(self, acl_index=0xFFFFFFFF):
        return self.vpp.api.macip_acl_dump(acl_index=acl_index)


text:
build:
	docker build -t ahmet2mir/jenkins .
run:
	docker run -d -p 8080:8080 -P -h jenkins --name jenkins ahmet2mir/jenkins
clean:
	docker rm -f jenkins
log:
	docker logs -f jenkins
port:
	docker port jenkins 8080
enter:
	docker exec -it jenkins /bin/bash

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Weapsy.Mvc.Context;
using Weapsy.Mvc.ViewEngine;

namespace Weapsy.Mvc.Middleware
{
    public class ThemeMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IContextService _contextService;

        public ThemeMiddleware(RequestDelegate next,
            IContextService contextService)
        {
            _next = next;
            _contextService = contextService;
        }

        public Task Invoke(HttpContext context)
        {
            var folder = _contextService.GetCurrentThemeInfo()?.Folder;
            context.Request.HttpContext.Items[ViewLocationExpander.ThemeKey] = folder ?? "Default";
            return _next(context);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNet.Identity.Shaolinq.DataModel.Interfaces;
using Microsoft.AspNet.Identity;
using Shaolinq;

namespace AspNet.Identity.Shaolinq
{
	public class ShaolinqIdentityUserStore<TIdentityUser, TDataModel, TPrimaryKey, TDbUser, TDbUserLogin, TDbUserClaim, TDbUserRole> :
		IUserPasswordStore<TIdentityUser, TPrimaryKey>,
		IUserLoginStore<TIdentityUser, TPrimaryKey>,
		IUserClaimStore<TIdentityUser, TPrimaryKey>,
		IUserSecurityStampStore<TIdentityUser, TPrimaryKey>,
		IUserRoleStore<TIdentityUser, TPrimaryKey>,
		IUserEmailStore<TIdentityUser, TPrimaryKey>,
		IUserLockoutStore<TIdentityUser, TPrimaryKey>

		//IQueryableUserStore<TIdentityUser, TPrimaryKey>,
		//IUserPhoneNumberStore<TIdentityUser, TPrimaryKey>,
		//IUserTwoFactorStore<TIdentityUser, TPrimaryKey>

		where TIdentityUser : ShaolinqIdentityUser<TPrimaryKey>, new()
		where TDataModel : DataAccessModel, IShaolinqIdentityDataAccessModel<TPrimaryKey, TDbUser, TDbUserLogin, TDbUserClaim, TDbUserRole>
		where TPrimaryKey : IEquatable<TPrimaryKey>
		where TDbUser : DataAccessObject, IShaolinqIdentityDbUser<TPrimaryKey>
		where TDbUserLogin : DataAccessObject, IShaolinqIdentityDbUserLogin<TPrimaryKey, TDbUser>
		where TDbUserClaim : DataAccessObject, IShaolinqIdentityDbUserClaim<TPrimaryKey, TDbUser>
		where TDbUserRole : DataAccessObject, IShaolinqIdentityDbUserRole<TPrimaryKey, TDbUser>
	{
		private readonly TDataModel dataModel;

		public ShaolinqIdentityUserStore(
			TDataModel dataModel
		)
		{
			this.dataModel = dataModel;
		}

		public virtual async Task CreateAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				var dbUser = dataModel.Users.Create();

				MapUser(user, dbUser);

				dbUser.ActivationDate = DateTime.UtcNow;

				await scope.FlushAsync();

				user.Id = dbUser.Id;

				await scope.CompleteAsync();
			}
		}

		public virtual async Task UpdateAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				var dbUser = await dataModel.Users.FirstOrDefaultAsync(x => x.Id.Equals(user.Id));

				if (dbUser == null)
				{
					throw new ApplicationException("User not found");
				}

				MapUser(user, dbUser);

				await scope.CompleteAsync();
			}
		}

		public virtual async Task DeleteAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				await dataModel.Users.DeleteAsync(x => x.Id.Equals(user.Id));

				await scope.CompleteAsync();
			}
		}

		public virtual async Task<TIdentityUser> FindByIdAsync(TPrimaryKey userId)
		{
			return await FindUserAsync(m => m.Users.SingleOrDefaultAsync(x => x.Id.Equals(userId)));
		}

		public virtual async Task<TIdentityUser> FindByNameAsync(string userName)
		{
			return await FindUserAsync(m => m.Users.FirstOrDefaultAsync(x => x.UserName == userName));
		}

		public virtual Task SetPasswordHashAsync(TIdentityUser user, string passwordHash)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.PasswordHash = passwordHash;

			return Task.FromResult<object>(null);
		}

		public virtual Task<string> GetPasswordHashAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.PasswordHash);
		}

		public virtual Task<bool> HasPasswordAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(!string.IsNullOrEmpty(user.PasswordHash));
		}

		public virtual async Task AddLoginAsync(TIdentityUser user, UserLoginInfo login)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			if (login == null)
			{
				throw new ArgumentNullException(nameof(login));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				var dbUserLogin = dataModel.UserLogins.Create();
				var dbUser = dataModel.Users.GetReference(user.Id);

				dbUserLogin.User = dbUser;
				dbUserLogin.LoginProvider = login.LoginProvider;
				dbUserLogin.ProviderKey = login.ProviderKey;

				await scope.FlushAsync();
				await scope.CompleteAsync();
			}
		}

		public virtual async Task RemoveLoginAsync(TIdentityUser user, UserLoginInfo login)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			if (login == null)
			{
				throw new ArgumentNullException(nameof(login));
			}

			using (var scope = DataAccessScope.CreateReadUncommited())
			{
				await dataModel.UserLogins.DeleteAsync(x => x.User.Id.Equals(user.Id) && x.LoginProvider == login.LoginProvider && x.ProviderKey == login.ProviderKey);

				await scope.CompleteAsync();
			}
		}

		public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			var dbUserLogins = dataModel.UserLogins.Where(x => x.User.Id.Equals(user.Id));
			var userLogins = await dbUserLogins.Select(x => new UserLoginInfo(x.LoginProvider, x.ProviderKey)).ToListAsync();

			return userLogins;
		}

		public virtual async Task<TIdentityUser> FindAsync(UserLoginInfo login)
		{
			if (login == null)
			{
				throw new ArgumentNullException(nameof(login));
			}

			return await FindUserAsync(async m =>
			{
				var userLogin = await dataModel.UserLogins.Include(x => x.User).SingleOrDefaultAsync(x => x.LoginProvider == login.LoginProvider && x.ProviderKey == login.ProviderKey);

				return userLogin?.User;
			});
		}

		public virtual async Task<IList<Claim>> GetClaimsAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			var dbClaims = dataModel.UserClaims.Where(x => x.User.Id.Equals(user.Id));
			var claims = await dbClaims.Select(x => new Claim(x.ClaimType, x.ClaimValue)).ToListAsync();

			return claims;
		}

		public virtual async Task AddClaimAsync(TIdentityUser user, Claim claim)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			if (claim == null)
			{
				throw new ArgumentNullException(nameof(claim));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				var dbUserClaim = dataModel.UserClaims.Create();
				var dbUser = dataModel.Users.GetReference(user.Id);

				dbUserClaim.User = dbUser;
				dbUserClaim.ClaimType = claim.Type;
				dbUserClaim.ClaimValue = claim.Value;

				await scope.FlushAsync();
				await scope.CompleteAsync();
			}
		}

		public virtual async Task RemoveClaimAsync(TIdentityUser user, Claim claim)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			if (claim == null)
			{
				throw new ArgumentNullException(nameof(claim));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				await dataModel.UserClaims.DeleteAsync(x => x.User.Id.Equals(user.Id) && x.ClaimType == claim.Type && x.ClaimValue == claim.Value);
				await scope.FlushAsync();
				await scope.CompleteAsync();
			}
		}

		public virtual Task SetSecurityStampAsync(TIdentityUser user, string stamp)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.SecurityStamp = stamp;

			return Task.FromResult<object>(null);
		}

		public virtual Task<string> GetSecurityStampAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.SecurityStamp);
		}

		public virtual async Task AddToRoleAsync(TIdentityUser user, string roleName)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			if (string.IsNullOrEmpty(roleName))
			{
				throw new ArgumentNullException(nameof(roleName));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				var dbUserRole = dataModel.UserRoles.Create();
				var dbUser = dataModel.Users.GetReference(user.Id);

				dbUserRole.User = dbUser;
				dbUserRole.Role = roleName;

				await scope.FlushAsync();
				await scope.CompleteAsync();
			}
		}

		public virtual async Task RemoveFromRoleAsync(TIdentityUser user, string roleName)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			if (string.IsNullOrEmpty(roleName))
			{
				throw new ArgumentNullException(nameof(roleName));
			}

			using (var scope = DataAccessScope.CreateReadCommitted())
			{
				await dataModel.UserRoles.DeleteAsync(x => x.User.Id.Equals(user.Id) && x.Role == roleName);

				await scope.CompleteAsync();
			}
		}

		public virtual async Task<IList<string>> GetRolesAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			var dbRoles = dataModel.UserRoles.Where(x => x.User.Id.Equals(user.Id));

			return await dbRoles.Select(x => x.Role).ToListAsync();
		}

		public virtual async Task<bool> IsInRoleAsync(TIdentityUser user, string roleName)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return (await dataModel.UserRoles.SingleOrDefaultAsync(x => x.User.Id.Equals(user.Id) && x.Role == roleName)) != null;
		}

		public virtual Task SetEmailAsync(TIdentityUser user, string email)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.Email = email;

			return Task.FromResult<object>(null);
		}

		public virtual Task<string> GetEmailAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.Email);
		}

		public virtual Task<bool> GetEmailConfirmedAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.EmailConfirmed);
		}

		public virtual Task SetEmailConfirmedAsync(TIdentityUser user, bool confirmed)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.EmailConfirmed = confirmed;

			return Task.FromResult<object>(null);
		}

		public virtual async Task<TIdentityUser> FindByEmailAsync(string email)
		{
			return await FindUserAsync(m => m.Users.FirstOrDefaultAsync(x => x.Email == email));
		}

		public virtual Task<DateTimeOffset> GetLockoutEndDateAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.LockoutEndDate);
		}

		public virtual Task SetLockoutEndDateAsync(TIdentityUser user, DateTimeOffset lockoutEnd)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.LockoutEndDate = lockoutEnd;

			return Task.FromResult<object>(null);
		}

		public virtual Task<int> IncrementAccessFailedCountAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.AccessFailedCount++;

			return Task.FromResult(user.AccessFailedCount);
		}

		public virtual Task ResetAccessFailedCountAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.AccessFailedCount = 0;

			return Task.FromResult<object>(null);
		}

		public virtual Task<int> GetAccessFailedCountAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.AccessFailedCount);
		}

		public virtual Task<bool> GetLockoutEnabledAsync(TIdentityUser user)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			return Task.FromResult(user.IsLockoutEnabled);
		}

		public virtual Task SetLockoutEnabledAsync(TIdentityUser user, bool enabled)
		{
			if (user == null)
			{
				throw new ArgumentNullException(nameof(user));
			}

			user.IsLockoutEnabled = enabled;

			return Task.FromResult<object>(null);
		}

		protected async Task<TIdentityUser> FindUserAsync(Func<TDataModel, Task<TDbUser>> findUserAsyncFunc)
		{
			return MapUser(await findUserAsyncFunc(dataModel));
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
		}

		protected static void MapUser(TIdentityUser fromUser, TDbUser toUser)
		{
			fromUser.PopulateDbUser(toUser);
		}

		protected static TIdentityUser MapUser(TDbUser dbUser)
		{
			if (dbUser == null)
			{
				return null;
			}

			var user = new TIdentityUser();

			user.PopulateFromDbUser(dbUser);

			return user;
		}
	}
}


text:
/**
 *
 */
package addressbook

/**
 * @author Hariharan
 *
 */
class Main {
// refer AnotherMain class
}


text:
title: Upgrade JStorm0.9.x To JStorm2.1.1
is_beta: false

sub-nav-group: Upgrade
sub-nav-id: UpgradeApplication
sub-nav-pos: 3
---

* This will be replaced by the TOC
{:toc}

JStorm 2.x are new version series, they have all features of 0.9.x, besides, they have these additional features:

1. Better performance: jstorm 2.1.1 did a lot of optimization to JStorm core and metrics. In our performance tests, JStorm 2.1.1 is at least 10% faster than JStorm 0.9.8 in the worst case.

2. Redesigned metrics core, from web ui(koala, not open source yet) we can see all history metrics instead of single static points in 0.9.x. It's also very easy to use user-defined metrics, with a few lines of code, users can see history metrics in web ui.

3. Minimum 1-min window metrics ensures more accurate metrics data.

4. Supports simple log search and topology log search, both forward and backward search are supported.

5. JStorm 2.1.1 supports jdk 1.8

But JStorm 2.1.1 is not quite backward compatible to JStorm 0.9x, mainly because changes to thrift/thrift dependency version and metrics client, the following steps are required to migrate JStorm 0.9.x to JStorm 2.1.1:

### 1.Upgrade your cluster

See: [Upgrade Guide]({{site.baseurl}}/quickstart/upgrade)

### 2.Code changes

a. Remove all old JStorm dependencies in your pom, including jstorm-client, jstorm-server, jstorm-client-extension.

b. Add jstorm-core dependency:

```xml
<dependency>
    <groupId>com.alibaba.jstorm</groupId>
    <artifactId>jstorm-core</artifactId>
    <version>2.1.1</version>
</dependency>
```

c. Rebuild your code, there might be errors in this step when you used user-defined metrics and MetricsClient since in JStorm 2.1.1 packages are changed, you may need to delete old packages and reimport the classes.

### 3. About logging frameworks [Very Important]
JStorm 2.1.1 has switched to logback instead of log4j in JStorm 0.9.x.

#### Use logback as your logging framework
In most cases, log4j can be bridged to logback, the detailed steps are:

a. add slf4j-api, log4j-over-slf4j and logback dependencies:

```
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>log4j-over-slf4j</artifactId>
    <version>1.7.10</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.0.13</version>
</dependency>
```

b. Exclude slf4j-log4j12 in your pom since it conflicts with log4j-over-slf4j:

```
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
    <scope>provided</scope>
</dependency>
```

Note that we use `<scope>provided</scope>` to exclude slf4j-log4j12, it's also fine to use `<excludes>`.
Theoretically this should do the work.

#### Use log4j as your logging framework
Above guides you to bridge log4j to logback, but if you use `Pattern, Appender` programmatically in your code, this may not work because some old versions of log4j-over-slf4j don't provide the same class/methods, in this case you may have to use log4j.

The steps are kind of opposite:

a. exclude log4j-over-slf4j dependency(if any), exclude logback dependency, then add slf4j-log4j12 to your pom:

```
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>log4j-over-slf4j</artifactId>
    <version>1.7.10</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.0.13</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
```

b. Besides changes in your pom, you also need to add a line of code before calling `TopologyBuilder.buildTopology`:

```
ConfigExtension.setUserDefinedLog4jConf(conf, "jstorm.log4j.properties");
```

This line tells JStorm to use log4j and use `jstorm.log4j.properties` as log4j config(this file is in ${JSTORM_HOME}/conf), also you can provide your own log4j property file as long as it's in your classpath or anywhere JStorm can find it.

You can also add this to your conf before submitting your topology.

```
user.defined.log4j.conf: jstorm.log4j.properties
```

In you want to use log4j by default in your cluster rather than logback, you may put the above line into your storm.yaml and sync storm.yaml to all supervisors.

The cost of doing so is that when you want to use logback, you need to add following conf in your topology:

```
user.defined.log4j.conf:
```

The above conf resets log4j conf thus JStorm will use logback.

### 4.How to use user-defined metrics
Use MetricClient to register user-defined metrics, the following kinds of metrics are supported:

COUNTER: as the name indicates, it records count like `emitted, acked, failed`.

METER: basically used to calculate qps/tps like `sendTps, recvTps` in JStorm.

GAUGE: used to record an instant value like `memUsed, cpuRatio, queueSize`,etc. **Note that gauges cannot be aggregated**, i.e., if you have registered a task-level gauge, JStorm won't aggregate its value to component-level since it doesn't make any sense.

HISTOGRAM: used for timing, like `EmitTime, nextTupleTime` etc.

You can refer to `TotalCount` class for detailed usage of user-defined metrics and MetricClient in sequence-split-merge project in the example module.


text:
// Class: Context3DTriangleFace
module Shumway.AVMX.AS.flash.display3D {
  import notImplemented = Shumway.Debug.notImplemented;
  import axCoerceString = Shumway.AVMX.axCoerceString;
  export class Context3DTriangleFace extends ASObject {

    // Called whenever the class is initialized.
    static classInitializer: any = null;

    // List of static symbols to link.
    static classSymbols: string [] = null; // [];

    // List of instance symbols to link.
    static instanceSymbols: string [] = null; // [];

    constructor () {
      super();
    }

    // JS -> AS Bindings
    static NONE: string = "none";
    static BACK: string = "back";
    static FRONT: string = "front";
    static FRONT_AND_BACK: string = "frontAndBack";

    // AS -> JS Bindings

  }
}


text:
namespace Elementary.Hierarchy.Test.TraverseWithInterfaces
{
    using Moq;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Xunit;

    public class HasChildNodesDescendantsTest
    {
        public interface MockableNodeType : IHasChildNodes<MockableNodeType>
        { }

        private readonly Mock<MockableNodeType> rootNode;
        private readonly Mock<MockableNodeType> leftNode;
        private readonly Mock<MockableNodeType> rightNode;
        private readonly Mock<MockableNodeType> leftLeaf;
        private readonly Mock<MockableNodeType> leftRightLeaf;
        private readonly Mock<MockableNodeType> rightRightLeaf;

        public HasChildNodesDescendantsTest()
        {
            //                rootNode
            //                /      \
            //        leftNode        rightNode
            //           /            /       \
            //     leftLeaf    leftRightLeaf  rightRightLeaf

            this.rightRightLeaf = new Mock<MockableNodeType>();
            this.rightRightLeaf // has no children
                .Setup(n => n.HasChildNodes).Returns(false);

            this.leftRightLeaf = new Mock<MockableNodeType>();
            this.leftRightLeaf // has no children
                .Setup(n => n.HasChildNodes).Returns(false);

            this.leftLeaf = new Mock<MockableNodeType>();
            this.leftLeaf // has no children
                .Setup(n => n.HasChildNodes).Returns(false);

            this.leftNode = new Mock<MockableNodeType>();
            this.leftNode // has single child
                .Setup(n => n.HasChildNodes).Returns(true);
            this.leftNode // returns leftLeaf as child
                .Setup(n => n.ChildNodes).Returns(new[] { this.leftLeaf.Object });

            this.rightNode = new Mock<MockableNodeType>();
            this.rightNode // has two children
                .Setup(n => n.HasChildNodes).Returns(true);
            this.rightNode // return leftRight and rightRightLeaf as children
                .Setup(n => n.ChildNodes).Returns(new[] { this.leftRightLeaf.Object, this.rightRightLeaf.Object });

            this.rootNode = new Mock<MockableNodeType>();
            this.rootNode // has a tw children
                .Setup(n => n.HasChildNodes).Returns(true);
            this.rootNode // returns the left node and right node as children
                .Setup(n => n.ChildNodes).Returns(new[] { this.leftNode.Object, this.rightNode.Object });
        }

        [Fact]
        public void IHasChildNodes_leaf_returns_no_children_on_Descendants()
        {
            // ACT

            IEnumerable<MockableNodeType> result = this.rightRightLeaf.Object.Descendants().ToArray();

            // ASSERT

            Assert.NotNull(result);
            Assert.False(result.Any());

            this.rightRightLeaf.Verify(n => n.HasChildNodes, Times.Once());
            this.rightRightLeaf.Verify(n => n.ChildNodes, Times.Never());
            this.rightRightLeaf.VerifyAll();
        }

        [Fact]
        public void IHasChildNodes_inconsistent_leaf_returns_no_children_on_Descendants()
        {
            // ARRANGE

            var badLeaf = new Mock<MockableNodeType>();
            badLeaf // claims to hav subnodes
                .Setup(n => n.HasChildNodes).Returns(true);
            badLeaf //  but returns empty set of subnodes
                .Setup(n => n.ChildNodes).Returns(Enumerable.Empty<MockableNodeType>());

            // ACT
            // leaf says it has a child but doesn't returns one

            IEnumerable<MockableNodeType> result = badLeaf.Object.Descendants();

            // ASSERT

            Assert.False(result.Any());

            badLeaf.Verify(n => n.HasChildNodes, Times.Once());
            badLeaf.Verify(n => n.ChildNodes, Times.Once());
        }

        [Fact]
        public void IHasChildNodes_inconsistent_leaf_returns_converts_null_to_empty_children_on_Descendants()
        {
            // ARRANGE

            var badLeaf = new Mock<MockableNodeType>();
            badLeaf // claims to hav subnodes
                .Setup(n => n.HasChildNodes).Returns(true);
            badLeaf //  but returns empty set of subnodes
                .Setup(n => n.ChildNodes).Returns((IEnumerable<MockableNodeType>)null);

            // ACT
            // leaf says it has a child but does returns null

            IEnumerable<MockableNodeType> result = badLeaf.Object.Descendants();

            // ASSERT

            Assert.False(result.Any());

            badLeaf.Verify(n => n.HasChildNodes, Times.Once());
            badLeaf.Verify(n => n.ChildNodes, Times.Once());
        }

        [Fact]
        public void IHasChildNodes_node_returns_single_child_on_Descendants()
        {
            // ACT

            IEnumerable<MockableNodeType> result = this.leftNode.Object.Descendants().ToArray();

            // ASSERT

            Assert.Equal(1, result.Count());
            Assert.Same(this.leftLeaf.Object, result.Single());

            this.leftNode.VerifyAll();
            this.leftLeaf.VerifyAll();
        }

        [Fact]
        public void IHasChildNodes_node_returns_left_child_first_on_Descendants()
        {
            // ACT

            IEnumerable<MockableNodeType> result = this.rightNode.Object.Descendants();

            // ASSERT

            Assert.Equal(2, result.Count());
            Assert.Equal(new[] { this.leftRightLeaf.Object, this.rightRightLeaf.Object }, result);

            this.rightNode.VerifyAll();
            this.leftRightLeaf.VerifyAll();
            this.rightRightLeaf.VerifyAll();
        }

        [Fact]
        public void IHasChildNodes_root_returns_descendants_breadthFirst_on_Descendants()
        {
            // ACT

            IEnumerable<MockableNodeType> result = this.rootNode.Object.Descendants().ToArray();

            // ASSERT

            Assert.Equal(5, result.Count());
            Assert.Equal(new[]
            {
                this.leftNode.Object,
                this.rightNode.Object,
                this.leftLeaf.Object,
                this.leftRightLeaf.Object,
                this.rightRightLeaf.Object
            }, result);

            this.rootNode.VerifyAll();
            this.leftNode.VerifyAll();
            this.rightNode.VerifyAll();
            this.leftLeaf.VerifyAll();
            this.leftRightLeaf.VerifyAll();
            this.rightRightLeaf.VerifyAll();
        }

        [Fact]
        public void IHasChildNodes_root_returns_descendants_depthFirst_on_Descendants()
        {
            // ACT

            IEnumerable<MockableNodeType> result = this.rootNode.Object.Descendants(depthFirst: true).ToArray();

            // ASSERT

            Assert.Equal(5, result.Count());
            Assert.Equal(new[] {
                this.leftNode,
                this.leftLeaf,
                this.rightNode,
                this.leftRightLeaf,
                this.rightRightLeaf
            }.Select(n => n.Object), result);

            this.rootNode.VerifyAll();
            this.leftNode.VerifyAll();
            this.rightNode.VerifyAll();
            this.leftLeaf.VerifyAll();
            this.leftRightLeaf.VerifyAll();
            this.rightRightLeaf.VerifyAll();
        }

        [Fact]
        public void IHasChildNodes_root_returns_children_as_level1_descendants_on_Descendants()
        {
            // ACT

            var descendants = this.rootNode.Object.Descendants(maxDepth: 1).ToArray();

            // ASSERT

            Assert.Equal(new[] { this.leftNode.Object, this.rightNode.Object }, descendants);
        }

        [Fact]
        public void IHasChildNodes_root_returns_empty_set_of_nodes_as_level0_descendants_on_Descendants()
        {
            // ACT

            var descendants = this.rootNode.Object.Descendants(maxDepth: 0).ToArray();

            // ASSERT

            Assert.False(descendants.Any());
        }

        [Fact]
        public void IHasChildNodes_root_throws_ArgumentException_on_level_lt0_on_Descendants()
        {
            // ACT

            ArgumentException ex = Assert.Throws<ArgumentException>(() => this.rootNode.Object.Descendants(maxDepth: -1));

            // ASSERT

            Assert.Contains("must be > 0", ex.Message);
            Assert.Equal("maxDepth", ex.ParamName);
        }

        [Fact]
        public void IHasChildNodes_root_returns_all_descendants_on_highLevel_breadthFirst_on_Descendants()
        {
            // ACT

            MockableNodeType[] result = this.rootNode.Object.Descendants(maxDepth: 3).ToArray();

            // ASSERT

            Assert.Equal(new[]
            {
                this.leftNode.Object,
                this.rightNode.Object,
                this.leftLeaf.Object,
                this.leftRightLeaf.Object,
                this.rightRightLeaf.Object
            }, result);
        }

        [Fact]
        public void IHasChildNodes_root_returns_all_descendants_on_highLevel_depthFirst_on_Descendants()
        {
            // ACT

            MockableNodeType[] result = this.rootNode.Object.Descendants(maxDepth: 3, depthFirst: true).ToArray();

            // ASSERT

            Assert.Equal(new[]
            {
                this.leftNode.Object,
                this.leftLeaf.Object,
                this.rightNode.Object,
                this.leftRightLeaf.Object,
                this.rightRightLeaf.Object
            }, result);
        }
    }
}


text:
package com.twitter.inject.app

import com.twitter.finagle.{Dtab, DtabFlags}

/**
 * When using the `dtab.add` Flag defined in [[com.twitter.finagle.DtabFlags]]
 * users can mix in this trait to add the ability to correctly apply supplemental
 * delegation tables to their base Dtab.
 *
 * @see [[com.twitter.finagle.Dtab]]
 * @see [[com.twitter.finagle.DtabFlags]]
 */
trait DtabResolution { self: App with DtabFlags =>

  /** Ensure we apply any supplemental delegation table(s) */
  premain {
    this.addDtabs()
    val entries = for (entry <- Dtab.base) yield { "\t" + entry.show }
    info("Installed Dtab:\n" + entries.mkString(";\n"))
  }

}


text:
package org.elasticsearch.action.admin.indices.upgrade.post;

import org.elasticsearch.action.support.broadcast.BroadcastShardRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.index.shard.ShardId;

import java.io.IOException;

public final class ShardUpgradeRequest extends BroadcastShardRequest {

    private UpgradeRequest request = new UpgradeRequest();

    public ShardUpgradeRequest() {
    }

    ShardUpgradeRequest(ShardId shardId, UpgradeRequest request) {
        super(shardId, request);
        this.request = request;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        request.readFrom(in);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        request.writeTo(out);
    }

    public UpgradeRequest upgradeRequest() {
        return this.request;
    }
}


text:
package com.goodow.realtime.html;

import com.goodow.realtime.core.Handler;
import com.goodow.realtime.core.Scheduler;
import com.goodow.realtime.json.Json;
import com.goodow.realtime.json.JsonObject;

import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;

class HtmlScheduler implements Scheduler {
  // @formatter:off
  private static native <T> void nativeHandle(Object handler, T event) /*-{
    handler(event);
  }-*/;
  // @formatter:on

  private int timerId = -1;
  private final JsonObject timers = Json.createObject();

  @Override
  public boolean cancelTimer(int id) {
    String key = "" + id;
    if (timers.has(key)) {
      timers.remove(key);
      return true;
    }
    return false;
  }

  @SuppressWarnings("unchecked")
  @Override
  public void handle(Object handler, Object event) {
    if (handler instanceof Handler) {
      ((Handler<Object>) handler).handle(event);
    } else {
      nativeHandle(handler, event);
    }
  }

  @Override
  public void scheduleDeferred(final Handler<Void> handler) {
    com.google.gwt.core.client.Scheduler.get().scheduleDeferred(new ScheduledCommand() {
      @Override
      public void execute() {
        handler.handle(null);
      }
    });
  }

  @Override
  public int scheduleDelay(int delayMs, final Handler<Void> handler) {
    final String key = "" + (++timerId);
    RepeatingCommand cmd = new RepeatingCommand() {
      @Override
      public boolean execute() {
        if (timers.has(key)) {
          timers.remove(key);
          handler.handle(null);
        }
        return false;
      }
    };
    timers.set(key, cmd);
    com.google.gwt.core.client.Scheduler.get().scheduleFixedDelay(cmd, delayMs);
    return timerId;
  }

  @Override
  public int schedulePeriodic(int delayMs, final Handler<Void> handler) {
    final String key = "" + (++timerId);
    RepeatingCommand cmd = new RepeatingCommand() {
      @Override
      public boolean execute() {
        if (timers.has(key)) {
          handler.handle(null);
          return true;
        }
        return false;
      }
    };
    timers.set(key, cmd);
    com.google.gwt.core.client.Scheduler.get().scheduleFixedPeriod(cmd, delayMs);
    return timerId;
  }
}


text:
package org.nexu.outdoors.web.model;

import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.DefaultAuthorizationRequest;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class AuthorizationResponse {

    private ClientDetails client;
    private DefaultAuthorizationRequest authRequest;
    private String scope;

    public AuthorizationResponse() {
    }

    public AuthorizationResponse(ClientDetails client, DefaultAuthorizationRequest authRequest, String scope) {
        this.client = client;
        this.authRequest = authRequest;
        this.scope = scope;
    }

    public ClientDetails getClient() {
        return client;
    }

    public void setClient(ClientDetails client) {
        this.client = client;
    }

    public DefaultAuthorizationRequest getAuthRequest() {
        return authRequest;
    }

    public void setAuthRequest(DefaultAuthorizationRequest authRequest) {
        this.authRequest = authRequest;
    }

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }
}


text:
    <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
    <title>org.hexworks.zircon.api.modifier.impl</title>
    <link href="../../images/logo-icon.svg" rel="icon" type="image/svg">

    <link href="../../styles/style.css" rel="Stylesheet">
    <link href="../../styles/logo-styles.css" rel="Stylesheet">
    <link href="../../styles/jetbrains-mono.css" rel="Stylesheet">
    <link href="../../styles/main.css" rel="Stylesheet">

zircon.core/org.hexworks.zircon.api.modifier.impl

<button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button>

Package org.<wbr></wbr>hexworks.<wbr></wbr>zircon.<wbr></wbr>api.<wbr></wbr>modifier.<wbr></wbr>impl

<button class="section-tab" data-active="" data-togglable="Types">Types</button>

Types

Fade

Link copied to clipboard

common

interface Fade
Content copied to clipboard

© 2020 CopyrightSponsored and developed by dokka


text:
function test_del_att ( ncfile )

if nargin == 0
	ncfile = 'foo.nc';
end

create_ncfile(ncfile);

test_normal_delete(ncfile);
test_bad_ncid(ncfile);
test_bad_varid(ncfile);
test_empty_name(ncfile);
test_bad_name(ncfile);
test_empty_ncid(ncfile);
test_empty_varid(ncfile);
test_empty_attname(ncfile);
test_bad_ncid_datatype(ncfile);
test_bad_varid_datatype(ncfile);
test_bad_attname_datatype(ncfile);

fprintf('DEL_ATT succeeded.\n');

%--------------------------------------------------------------------------
function create_ncfile(ncfile)

[ncid, status] = mexnc ( 'create', ncfile, nc_clobber_mode );
if status, error(mexnc('strerror',status)), end

[xdimid, status] = mexnc ( 'def_dim', ncid, 'x', 20 );
if status, error(mexnc('strerror',status)), end

[varid, status] = mexnc ( 'def_var', ncid, 'x', nc_double, 1, xdimid );
if status, error(mexnc('strerror',status)), end

input_data = 3.14159;
status = mexnc ( 'put_att_double', ncid, varid, 'test_double', nc_double, 1, input_data );
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'enddef', ncid  );
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_normal_delete(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'del_att', ncid, varid, 'test_double' );
if status, error(mexnc('strerror',status)), end

[attnum, status] = mexnc ( 'inq_attid', ncid, varid, 'test_double' );
if ( status >= 0 )
	error('attribute was not deleted');
end

input_data = 3.14159;
status = mexnc ( 'put_att_double', ncid, varid, 'to_be_deleted', nc_double, 1, input_data );
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'close', ncid );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_bad_ncid(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'del_att', -2000, varid, 'to_be_deleted' );
if ( status == 0 )
	error('failed');
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_bad_varid(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'del_att', ncid, -2000, 'to_be_deleted' );
if ( status == 0 )
	error('failed');
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_empty_name(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', ncid, varid, '' );
	error('failed');
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_bad_name(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'del_att', ncid, varid, 'I know nothing' );
if ( status == 0 )
	error('failed');
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_empty_ncid(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', [], varid, 'I know less than nothing' );
	error('failed');
catch
	;
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_empty_varid(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', ncid, [], 'I know less than nothing' );
	error('failed');
catch
	;
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_empty_attname(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', ncid, varid, [] );
	error('failed');
catch
	;
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_bad_ncid_datatype(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', 'ncid', varid, 'to_be_deleted' );
	error('failed');
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_bad_varid_datatype(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', ncid, 'varid', 'to_be_deleted' );
	error('failed');
end

status = mexnc ( 'close', ncid  );
if status, error(mexnc('strerror',status)), end

%--------------------------------------------------------------------------
function test_bad_attname_datatype(ncfile)

[ncid,status] = mexnc('open',ncfile,nc_write_mode);
if status, error(mexnc('strerror',status)), end

status = mexnc ( 'redef', ncid  );
if status, error(mexnc('strerror',status)), end

[varid,status] = mexnc('inq_varid',ncid,'x');
if status, error(mexnc('strerror',status)), end

try
	status = mexnc ( 'del_att', ncid, varid, 5 );
	error('failed');
end

status = mexnc ( 'close', ncid );
if status, error(mexnc('strerror',status)), end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:layout_height="match_parent"
    android:background="#803C4850">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:id="@+id/nav_icon"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginLeft="40dp"
            android:id="@+id/title"
            android:gravity="left"
            android:text="Title"
            android:textStyle="bold"
            android:textColor="#3C4850"
            android:textSize="20sp"/>

</LinearLayout>


text:
package io.crate.auth.user;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import io.crate.action.sql.SessionContext;
import io.crate.analyze.user.Privilege;
import io.crate.exceptions.RelationValidationException;
import io.crate.exceptions.SchemaUnknownException;
import io.crate.exceptions.UnhandledServerException;
import io.crate.exceptions.UnsupportedFeatureException;
import io.crate.metadata.RelationName;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.core.Is.is;

public class AccessControlMaySeeTest extends ESTestCase {

    private List<List<Object>> validationCallArguments;
    private User user;
    private AccessControl accessControl;

    @Before
    public void setUpUserAndValidator() {
        validationCallArguments = new ArrayList<>();
        user = new User("normal", ImmutableSet.of(), ImmutableSet.of(), null) {

            @Override
            public boolean hasAnyPrivilege(Privilege.Clazz clazz, String ident) {
                validationCallArguments.add(Lists.newArrayList(clazz, ident, user.name()));
                return true;
            }
        };
        accessControl = new AccessControlImpl(userName -> user, new SessionContext(user));
    }

    @SuppressWarnings("unchecked")
    private void assertAskedAnyForCluster() {
        Matcher<Iterable<?>> matcher = (Matcher) hasItem(contains(Privilege.Clazz.CLUSTER, null, user.name()));
        assertThat(validationCallArguments, matcher);
    }

    @SuppressWarnings("unchecked")
    private void assertAskedAnyForSchema(String ident) {
        Matcher<Iterable<?>> matcher = (Matcher) hasItem(contains(Privilege.Clazz.SCHEMA, ident, user.name()));
        assertThat(validationCallArguments, matcher);
    }

    @SuppressWarnings("unchecked")
    private void assertAskedAnyForTable(String ident) {
        Matcher<Iterable<?>> matcher = (Matcher) hasItem(contains(Privilege.Clazz.TABLE, ident, user.name()));
        assertThat(validationCallArguments, matcher);
    }

    @Test
    public void testTableScopeException() throws Exception {
        accessControl.ensureMaySee(new RelationValidationException(Lists.newArrayList(
            RelationName.fromIndexName("users"),
            RelationName.fromIndexName("my_schema.foo")
        ), "bla"));
        assertAskedAnyForTable("doc.users");
        assertAskedAnyForTable("my_schema.foo");
    }

    @Test
    public void testSchemaScopeException() throws Exception {
        accessControl.ensureMaySee(new SchemaUnknownException("my_schema"));
        assertAskedAnyForSchema("my_schema");
    }

    @Test
    public void testClusterScopeException() throws Exception {
        accessControl.ensureMaySee(new UnsupportedFeatureException("unsupported"));
        assertAskedAnyForCluster();
    }

    @Test
    public void testUnscopedException() throws Exception {
        accessControl.ensureMaySee(new UnhandledServerException("unhandled"));
        assertThat(validationCallArguments.size(), is(0));
    }
}


text:
package org.pentaho.di.ui.core;

import org.eclipse.swt.widgets.Shell;

import java.util.List;

/**
 * Created by ddiroma on 8/15/18.
 */
public class GetFieldsDialogOperation {
  private Shell shell;
  private int width;
  private int height;
  private String filename;
  private String title;
  private List<String> paths;

  public GetFieldsDialogOperation( Shell shell, int width, int height, String filename, String title, List<String>
          paths ) {
    this.shell = shell;
    this.width = width;
    this.height = height;
    this.filename = filename;
    this.title = title;
    this.paths = paths;
  }

  public Shell getShell() {
    return shell;
  }

  public void setShell( Shell shell ) {
    this.shell = shell;
  }

  public int getWidth() {
    return width;
  }

  public void setWidth( int width ) {
    this.width = width;
  }

  public int getHeight() {
    return height;
  }

  public void setHeight( int height ) {
    this.height = height;
  }

  public String getFilename() {
    return filename;
  }

  public void setFilename( String filename ) {
    this.filename = filename;
  }

  public List<String> getPaths() {
    return paths;
  }

  public void setPaths( List<String> paths ) {
    this.paths = paths;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle( String title ) {
    this.title = title;
  }
}


text:
CC = python -m ppci cc --html-report hello_report.html
CFLAGS = -O1

all: hello

# Now link all compiled objects (here, just one) into executable. For this,
# we need to provide linker with memory layout file. We'll also use main()
# as the executable entrypoint.
hello: hello.o
	python -m ppci ld --entry main --layout linux64.ld $^ -o $@

# We build object files as usual with $(CC) (using the builtin make rule).
hello.o: hello.c

clean:
	rm -f *.o hello


text:
using namespace std;

TEST(ReadingTest, IntValue)
{
	DatapointValue value((long) 10);
	Reading reading(string("test1"), new Datapoint("x", value));
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"asset_code\" : \"test1\"")), 0);
	ASSERT_NE(json.find(string("\"reading\" : { \"x\" : \"10\" }")), 0);
	ASSERT_NE(json.find(string("\"ser_ts\" : ")), 0);
}

TEST(ReadingTest, FloatValue)
{
	DatapointValue value(3.1415);
	Reading reading(string("test1"), new Datapoint("pi", value));
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"asset_code\" : \"test1\"")), 0);
	ASSERT_NE(json.find(string("\"reading\" : { \"pi\" : \"3.1415\" }")), 0);
	ASSERT_NE(json.find(string("\"ser_ts\" : ")), 0);
}

TEST(ReadingTest, AString)
{
	DatapointValue value("just a string");
	Reading reading(string("test3"), new Datapoint("str", value));
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"asset_code\":\"test3\"")), std::string::npos);
	ASSERT_NE(json.find(string("\"reading\":{\"str\":\"just a string\"}")), std::string::npos);
	ASSERT_NE(json.find(string("\"user_ts\":")), std::string::npos);
}

TEST(ReadingTest, FloatArray)
{
	std::vector<double> v {3.1415, -128, 0, -0.0021, 0.2345};
	DatapointValue value(v);
	Reading reading(string("test55"), new Datapoint("a", value));
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"asset_code\":\"test55\"")), std::string::npos);
	ASSERT_NE(json.find(string("\"reading\":{\"a\":[3.1415, -128, 0, -0.0021, 0.2345]}")), std::string::npos);
	ASSERT_NE(json.find(string("\"user_ts\":")), std::string::npos);
}

TEST(ReadingTest, GMT)
{
	DatapointValue value((long) 10);
	Reading reading(string("test1"), new Datapoint("x", value));
	reading.setUserTimestamp("2019-01-10 10:01:03.123456+0:00");
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"user_ts\" : \"2019-01-10 10:01:03.123456+0:00\"")), 0);
}

TEST(ReadingTest, CET)
{
	DatapointValue value((long) 10);
	Reading reading(string("test1"), new Datapoint("x", value));
	reading.setUserTimestamp("2019-01-10 10:01:03.123456-1:00");
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"user_ts\" : \"2019-01-10 11:01:03.123456+0:00\"")), 0);
}

TEST(ReadingTest, PST)
{
	DatapointValue value((long) 10);
	Reading reading(string("test1"), new Datapoint("x", value));
	reading.setUserTimestamp("2019-01-10 10:01:03.123456+8:00");
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"user_ts\" : \"2019-01-10 18:01:03.123456+0:00\"")), 0);
}

TEST(ReadingTest, IST)
{
	DatapointValue value((long) 10);
	Reading reading(string("test1"), new Datapoint("x", value));
	reading.setUserTimestamp("2019-01-10 10:01:03.123456-5:30");
	string json = reading.toJSON();
	ASSERT_NE(json.find(string("\"user_ts\" : \"2019-01-10 15:31:03.123456+0:00\"")), 0);
}

TEST(ReadingTest, rmDatapoint)
{
	DatapointValue value((long) 10);
	Reading reading(string("test1"), new Datapoint("x", value));
	DatapointValue val2((long) 20);
	reading.addDatapoint(new Datapoint("y", val2));
	ASSERT_EQ(reading.getDatapointCount(), 2);
	Datapoint *removed = reading.removeDatapoint("x");
	ASSERT_EQ(reading.getDatapointCount(), 1);
	ASSERT_EQ(removed->getName().compare("x"), 0);
	delete removed;
	removed = reading.removeDatapoint("x");
	ASSERT_EQ(removed,  (Datapoint *)0);
}


text:
package com.facebook.buck.android;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;

import com.facebook.buck.io.ProjectFilesystem;
import com.google.common.base.Optional;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;

public class AndroidResourceDescriptionTest {

  @Rule
  public TemporaryFolder tmpFolder = new TemporaryFolder();

  @Test
  public void testNonAssetFilesAndDirsAreIgnored() throws IOException {
    tmpFolder.newFolder("res");

    tmpFolder.newFile("res/image.png");
    tmpFolder.newFile("res/layout.xml");
    tmpFolder.newFile("res/_file");

    tmpFolder.newFile("res/.gitkeep");
    tmpFolder.newFile("res/.svn");
    tmpFolder.newFile("res/.git");
    tmpFolder.newFile("res/.ds_store");
    tmpFolder.newFile("res/.scc");
    tmpFolder.newFile("res/CVS");
    tmpFolder.newFile("res/thumbs.db");
    tmpFolder.newFile("res/picasa.ini");
    tmpFolder.newFile("res/file.bak~");

    tmpFolder.newFolder("res/dirs");
    tmpFolder.newFolder("res/dirs/values");
    tmpFolder.newFile("res/dirs/values/strings.xml");
    tmpFolder.newFile("res/dirs/values/strings.xml.orig");

    tmpFolder.newFolder("res/dirs/.gitkeep");
    tmpFolder.newFile("res/dirs/.gitkeep/ignore");
    tmpFolder.newFolder("res/dirs/.svn");
    tmpFolder.newFile("res/dirs/.svn/ignore");
    tmpFolder.newFolder("res/dirs/.git");
    tmpFolder.newFile("res/dirs/.git/ignore");
    tmpFolder.newFolder("res/dirs/.ds_store");
    tmpFolder.newFile("res/dirs/.ds_store/ignore");
    tmpFolder.newFolder("res/dirs/.scc");
    tmpFolder.newFile("res/dirs/.scc/ignore");
    tmpFolder.newFolder("res/dirs/CVS");
    tmpFolder.newFile("res/dirs/CVS/ignore");
    tmpFolder.newFolder("res/dirs/thumbs.db");
    tmpFolder.newFile("res/dirs/thumbs.db/ignore");
    tmpFolder.newFolder("res/dirs/picasa.ini");
    tmpFolder.newFile("res/dirs/picasa.ini/ignore");
    tmpFolder.newFolder("res/dirs/file.bak~");
    tmpFolder.newFile("res/dirs/file.bak~/ignore");
    tmpFolder.newFolder("res/dirs/_dir");
    tmpFolder.newFile("res/dirs/_dir/ignore");

    AndroidResourceDescription description = new AndroidResourceDescription();
    Set<Path> inputs = description.collectInputFiles(
            new ProjectFilesystem(tmpFolder.getRoot().toPath()),
            Optional.of(Paths.get("res")));

    assertThat(
        inputs,
        containsInAnyOrder(
            Paths.get("res/image.png"),
            Paths.get("res/layout.xml"),
            Paths.get("res/_file"),
            Paths.get("res/dirs/values/strings.xml")));
  }
}