text:
from six.moves import queue
import time

from oslo_serialization import jsonutils

from networking_cisco._i18n import _LE, _LI

from networking_cisco.apps.saf.agent import detect_uplink as uplink_det
from networking_cisco.apps.saf.agent.topo_disc import topo_disc
from networking_cisco.apps.saf.agent.vdp import ovs_vdp
from networking_cisco.apps.saf.common import constants
from networking_cisco.apps.saf.common import dfa_logger as logging
from networking_cisco.apps.saf.common import dfa_sys_lib as sys_utils
from networking_cisco.apps.saf.common import rpc
from networking_cisco.apps.saf.common import utils

LOG = logging.getLogger(__name__)

class VdpMsgPriQue(object):

    """VDP Message Queue. """

    def __init__(self):
        self._queue = queue.PriorityQueue()

    def enqueue(self, priority, msg):
        msg_tupl = (priority, msg)
        self._queue.put(msg_tupl)

    def dequeue(self):
        msg_tupl = self._queue.get()
        return msg_tupl[0], msg_tupl[1]

    def dequeue_nonblock(self):
        msg_tupl = self._queue.get_nowait()
        return msg_tupl[0], msg_tupl[1]

    def is_not_empty(self):
        return not self._queue.empty()

class VdpQueMsg(object):

    """Construct VDP Message. """

    def __init__(self, msg_type, port_uuid=None, vm_mac=None, oui=None,
                 net_uuid=None, segmentation_id=None, status=None,
                 vm_bulk_list=None, phy_uplink=None, br_int=None, br_ex=None,
                 root_helper=None):
        self.msg_dict = {}
        self.msg_type = msg_type
        if msg_type == constants.VM_MSG_TYPE:
            self.construct_vm_msg(port_uuid, vm_mac, net_uuid,
                                  segmentation_id, status, oui, phy_uplink)
        elif msg_type == constants.UPLINK_MSG_TYPE:
            self.construct_uplink_msg(status, phy_uplink, br_int, br_ex,
                                      root_helper)
        elif msg_type == constants.VM_BULK_SYNC_MSG_TYPE:
            self.construct_vm_bulk_sync_msg(vm_bulk_list, phy_uplink)

    def construct_vm_msg(self, port_uuid, vm_mac, net_uuid,
                         segmentation_id, status, oui, phy_uplink):
        self.msg_dict['port_uuid'] = port_uuid
        self.msg_dict['vm_mac'] = vm_mac
        self.msg_dict['net_uuid'] = net_uuid
        self.msg_dict['segmentation_id'] = segmentation_id
        self.msg_dict['status'] = status
        self.msg_dict['oui'] = oui
        self.msg_dict['phy_uplink'] = phy_uplink

    def construct_vm_bulk_sync_msg(self, vm_bulk_list, phy_uplink):
        self.msg_dict['phy_uplink'] = phy_uplink
        self.msg_dict['vm_bulk_list'] = vm_bulk_list

    def construct_uplink_msg(self, status, phy_uplink, br_int, br_ex,
                             root_helper):
        self.msg_dict['status'] = status
        self.msg_dict['phy_uplink'] = phy_uplink
        self.msg_dict['br_int'] = br_int
        self.msg_dict['br_ex'] = br_ex
        self.msg_dict['root_helper'] = root_helper

    def get_oui(self):
        return self.msg_dict['oui']

    def get_uplink(self):
        return self.msg_dict['phy_uplink']

    def get_mac(self):
        return self.msg_dict['vm_mac']

    def get_status(self):
        return self.msg_dict['status']

    def get_segmentation_id(self):
        return self.msg_dict['segmentation_id']

    def get_net_uuid(self):
        return self.msg_dict['net_uuid']

    def get_port_uuid(self):
        return self.msg_dict['port_uuid']

    def get_integ_br(self):
        return self.msg_dict['br_int']

    def get_ext_br(self):
        return self.msg_dict['br_ex']

    def get_root_helper(self):
        return self.msg_dict['root_helper']

    def set_uplink(self, uplink):
        self.msg_dict['phy_uplink'] = uplink

class VdpMgr(object):

    """Responsible for Handling VM/Uplink requests. """

    def __init__(self, config_dict, rpc_client, hostname):
        self.br_integ = config_dict.get('integration_bridge')
        self.br_ex = config_dict.get('external_bridge')
        self.root_helper = config_dict.get('root_helper')
        self.host_id = config_dict.get('host_id')
        self.node_list = config_dict['node_list']
        self.node_uplink_list = config_dict['node_uplink_list']
        # Check for error?? fixme(padkrish)
        self.que = VdpMsgPriQue()
        self.err_que = VdpMsgPriQue()
        self.phy_uplink = None
        self.veth_intf = None
        self.restart_uplink_called = False
        self.ovs_vdp_obj_dict = {}
        self.rpc_clnt = rpc_client
        self.host_name = hostname
        self.uplink_det_compl = False
        self.process_uplink_ongoing = False
        self.uplink_down_cnt = 0
        self.is_os_run = False
        self.static_uplink = False
        self.static_uplink_port = None
        self.static_uplink_first = True
        self.bulk_vm_rcvd_flag = False
        self.bulk_vm_check_cnt = 0
        self.vdp_mgr_lock = utils.lock()
        self.read_static_uplink()
        self.start()
        self.topo_disc = topo_disc.TopoDisc(self.topo_disc_cb,
                                            self.root_helper)

    def read_static_uplink(self):
        """Read the static uplink from file, if given."""
        if self.node_list is None or self.node_uplink_list is None:
            return
        for node, port in zip(self.node_list.split(','),
                              self.node_uplink_list.split(',')):
            if node.strip() == self.host_name:
                self.static_uplink = True
                self.static_uplink_port = port.strip()
                return

    def topo_disc_cb(self, intf, topo_disc_obj):
        return self.save_topo_disc_params(intf, topo_disc_obj)

    def update_vm_result(self, port_uuid, result, lvid=None,
                         vdp_vlan=None, fail_reason=None):
        context = {'agent': self.host_id}
        if lvid is None or vdp_vlan is None:
            args = jsonutils.dumps({'port_uuid': port_uuid, 'result': result,
                                    'fail_reason': fail_reason})
        else:
            args = jsonutils.dumps({'port_uuid': port_uuid, 'local_vlan': lvid,
                                    'vdp_vlan': vdp_vlan, 'result': result,
                                    'fail_reason': fail_reason})
        msg = self.rpc_clnt.make_msg('update_vm_result', context, msg=args)
        try:
            resp = self.rpc_clnt.call(msg)
            return resp
        except rpc.MessagingTimeout:
            LOG.error(_LE("RPC timeout: Failed to update VM result on the"
                          " server"))

    def vdp_vlan_change_cb(self, port_uuid, lvid, vdp_vlan, fail_reason):
        """Callback function for updating the VDP VLAN in DB. """
        LOG.info(_LI("Vlan change CB lvid %(lvid)s VDP %(vdp)s"),
                 {'lvid': lvid, 'vdp': vdp_vlan})
        self.update_vm_result(port_uuid, constants.RESULT_SUCCESS,
                              lvid=lvid, vdp_vlan=vdp_vlan,
                              fail_reason=fail_reason)

    def process_vm_event(self, msg, phy_uplink):
        LOG.info(_LI("In processing VM Event status %(status)s for MAC "
                     "%(mac)s UUID %(uuid)s oui %(oui)s"),
                 {'status': msg.get_status(), 'mac': msg.get_mac(),
                  'uuid': msg.get_port_uuid(), 'oui': msg.get_oui()})
        time.sleep(10)
        if msg.get_status() == 'up':
            res_fail = constants.CREATE_FAIL
        else:
            res_fail = constants.DELETE_FAIL
        if (not self.uplink_det_compl or
                phy_uplink not in self.ovs_vdp_obj_dict):
            LOG.error(_LE("Uplink Port Event not received yet"))
            self.update_vm_result(msg.get_port_uuid(), res_fail)
            return
        ovs_vdp_obj = self.ovs_vdp_obj_dict[phy_uplink]
        port_event_reply = ovs_vdp_obj.send_vdp_port_event(
            msg.get_port_uuid(), msg.get_mac(), msg.get_net_uuid(),
            msg.get_segmentation_id(), msg.get_status(), msg.get_oui())
        if not port_event_reply.get('result'):
            LOG.error(_LE("Error in VDP port event, Err Queue enq"))
            self.update_vm_result(
                msg.get_port_uuid(), res_fail,
                fail_reason=port_event_reply.get('fail_reason'))
        else:
            LOG.info(_LI("Success in VDP port event"))
            lvid, vdp_vlan = ovs_vdp_obj.get_lvid_vdp_vlan(msg.get_net_uuid(),
                                                           msg.get_port_uuid())
            self.update_vm_result(
                msg.get_port_uuid(), constants.RESULT_SUCCESS,
                lvid=lvid, vdp_vlan=vdp_vlan,
                fail_reason=port_event_reply.get('fail_reason'))

    def process_bulk_vm_event(self, msg, phy_uplink):
        """Process the VM bulk event usually after a restart. """
        LOG.info("In processing Bulk VM Event status %s", msg)
        time.sleep(3)
        if (not self.uplink_det_compl or
                phy_uplink not in self.ovs_vdp_obj_dict):
            # This condition shouldn't be hit as only when uplink is obtained,
            # save_uplink is called and that in turns calls this process_bulk.
            LOG.error(_LE("Uplink Port Event not received,"
                          "yet in bulk process"))
            return
        ovs_vdp_obj = self.ovs_vdp_obj_dict[phy_uplink]
        for vm_dict in msg.msg_dict.get('vm_bulk_list'):
            if vm_dict['status'] == 'down':
                ovs_vdp_obj.pop_local_cache(vm_dict['port_uuid'],
                                            vm_dict['vm_mac'],
                                            vm_dict['net_uuid'],
                                            vm_dict['local_vlan'],
                                            vm_dict['vdp_vlan'],
                                            vm_dict['segmentation_id'])
            vm_msg = VdpQueMsg(constants.VM_MSG_TYPE,
                               port_uuid=vm_dict['port_uuid'],
                               vm_mac=vm_dict['vm_mac'],
                               net_uuid=vm_dict['net_uuid'],
                               segmentation_id=vm_dict['segmentation_id'],
                               status=vm_dict['status'],
                               oui=vm_dict['oui'],
                               phy_uplink=phy_uplink)
            self.process_vm_event(vm_msg, phy_uplink)

    def process_uplink_event(self, msg, phy_uplink):
        LOG.info(_LI("Received New uplink Msg %(msg)s for uplink %(uplink)s"),
                 {'msg': msg.get_status(), 'uplink': phy_uplink})
        if msg.get_status() == 'up':
            ovs_exc_raised = False
            ovs_exc_reason = ""
            try:
                self.ovs_vdp_obj_dict[phy_uplink] = ovs_vdp.OVSNeutronVdp(
                    phy_uplink, msg.get_integ_br(), msg.get_ext_br(),
                    msg.get_root_helper(), self.vdp_vlan_change_cb)
            except Exception as exc:
                ovs_exc_reason = str(exc)
                LOG.error(_LE("OVS VDP Object creation failed %s"),
                          str(ovs_exc_reason))
                ovs_exc_raised = True
            if (ovs_exc_raised or not self.ovs_vdp_obj_dict[phy_uplink].
                    is_lldpad_setup_done()):
                # Is there a way to delete the object??
                if not ovs_exc_reason:
                    uplink_fail_reason = (self.ovs_vdp_obj_dict[phy_uplink].
                                          get_uplink_fail_reason())
                else:
                    uplink_fail_reason = ovs_exc_reason
                LOG.error(_LE("UP Event Processing NOT Complete"))
                self.err_que.enqueue(constants.Q_UPL_PRIO, msg)
                self.save_uplink(uplink=self.phy_uplink,
                                 fail_reason=uplink_fail_reason)
            else:
                self.uplink_det_compl = True
                veth_intf = (self.ovs_vdp_obj_dict[self.phy_uplink].
                             get_lldp_local_bridge_port())
                LOG.info(_LI("UP Event Processing Complete Saving uplink "
                             "%(ul)s and veth %(veth)s"),
                         {'ul': self.phy_uplink, 'veth': veth_intf})
                self.save_uplink(uplink=self.phy_uplink, veth_intf=veth_intf)
                self.topo_disc.uncfg_intf(self.phy_uplink)
                self.topo_disc.cfg_intf(veth_intf,
                                        phy_interface=self.phy_uplink)
        elif msg.get_status() == 'down':
            # Free the object fixme(padkrish)
            if phy_uplink in self.ovs_vdp_obj_dict:
                self.ovs_vdp_obj_dict[phy_uplink].clear_obj_params()
            else:
                ovs_vdp.delete_uplink_and_flows(self.root_helper, self.br_ex,
                                                phy_uplink)
            self.save_uplink()
            self.topo_disc.uncfg_intf(self.veth_intf)
            self.topo_disc.cfg_intf(phy_uplink)

    def process_queue(self):
        LOG.info(_LI("Entered process_q"))
        while True:
            prio, msg = self.que.dequeue()
            msg_type = msg.msg_type
            phy_uplink = msg.get_uplink()
            LOG.info(_LI("Msg dequeued type is %d"), msg_type)
            try:
                if msg_type == constants.VM_MSG_TYPE:
                    self.process_vm_event(msg, phy_uplink)
                elif msg_type == constants.VM_BULK_SYNC_MSG_TYPE:
                    self.process_bulk_vm_event(msg, phy_uplink)
                elif msg_type == constants.UPLINK_MSG_TYPE:
                    try:
                        self.process_uplink_event(msg, phy_uplink)
                    except Exception as eu:
                        LOG.exception(_LE("Exception caught in process_uplink"
                                          " %s"), str(eu))
                    self.process_uplink_ongoing = False
            except Exception as e:
                LOG.exceptin(_LE("Exception caught in process_q %s"), str(e))

    def process_err_queue(self):
        LOG.info(_LI("Entered Err process_q"))
        try:
            while self.err_que.is_not_empty():
                prio, msg = self.err_que.dequeue_nonblock()
                msg_type = msg.msg_type
                LOG.info(_LI("Msg dequeued from err queue type is %d"),
                         msg_type)
                if msg_type == constants.UPLINK_MSG_TYPE:
                    self.que.enqueue(constants.Q_UPL_PRIO, msg)
        except Exception as e:
            LOG.exceptin(_LE("Exception caught in proc_err_que %s "), str(e))

    def start(self):
        # Spawn the thread
        # Pass the Que as last argument so that in case of exception, the
        # daemon can exit gracefully. fixme(padkrish)
        thr_q = utils.EventProcessingThread("VDP_Mgr", self, 'process_queue')
        thr_q.start()
        task_err_proc = utils.PeriodicTask(constants.ERR_PROC_INTERVAL,
                                           self.process_err_queue)
        task_err_proc.run()
        task_uplink = utils.PeriodicTask(constants.UPLINK_DET_INTERVAL,
                                         self.vdp_uplink_proc_top)
        task_uplink.run()

    def is_openstack_running(self):
        """Currently it just checks for the presence of both the bridges. """
        try:
            if (ovs_vdp.is_bridge_present(self.br_ex, self.root_helper) and
                    ovs_vdp.is_bridge_present(self.br_integ,
                                              self.root_helper)):
                return True
            else:
                return False
        except Exception as e:
            LOG.error(_LE("Exception in is_openstack_running %s"), str(e))
            return False

    def vdp_uplink_proc_top(self):
        try:
            self.vdp_uplink_proc()
        except Exception as e:
            LOG.error(_LE("VDP uplink proc exception %s"), e)

    def save_uplink(self, uplink="", veth_intf="", fail_reason=""):
        context = {}
        # If uplink physical interface is a part of bond, then this function
        # will be called with uplink=bond0, as an example
        memb_port_list = sys_utils.get_member_ports(uplink)
        args = jsonutils.dumps({'agent': self.host_id, 'uplink': uplink,
                                'veth_intf': veth_intf,
                                'memb_port_list': memb_port_list,
                                'fail_reason': fail_reason})
        msg = self.rpc_clnt.make_msg('save_uplink', context, msg=args)
        try:
            resp = self.rpc_clnt.call(msg)
            return resp
        except rpc.MessagingTimeout:
            LOG.error(_LE("RPC timeout: Failed to save link name on the "
                          "server"))

    def _fill_topology_cfg(self, topo_dict):
        """Fills the extra configurations in the topology. """
        cfg_dict = {}
        if topo_dict.bond_member_ports is not None:
            cfg_dict.update({'bond_member_ports':
                             topo_dict.bond_member_ports})
        if topo_dict.bond_interface is not None:
            cfg_dict.update({'bond_interface':
                             topo_dict.bond_interface})
        return cfg_dict

    def save_topo_disc_params(self, intf, topo_disc_obj):
        context = {}
        topo_cfg = self._fill_topology_cfg(topo_disc_obj)
        args = jsonutils.dumps(
            {'host': self.host_id, 'protocol_interface': intf,
             'heartbeat': time.ctime(),
             'phy_interface': topo_disc_obj.phy_interface,
             'remote_evb_cfgd': topo_disc_obj.remote_evb_cfgd,
             'remote_evb_mode': topo_disc_obj.remote_evb_mode,
             'remote_mgmt_addr': topo_disc_obj.remote_mgmt_addr,
             'remote_system_desc': topo_disc_obj.remote_system_desc,
             'remote_system_name': topo_disc_obj.remote_system_name,
             'remote_port': topo_disc_obj.remote_port,
             'remote_chassis_id_mac': topo_disc_obj.remote_chassis_id_mac,
             'remote_port_id_mac': topo_disc_obj.remote_port_id_mac,
             'configurations': jsonutils.dumps(topo_cfg)})
        msg = self.rpc_clnt.make_msg('save_topo_disc_params', context,
                                     msg=args)
        try:
            resp = self.rpc_clnt.call(msg)
            return resp
        except rpc.MessagingTimeout:
            LOG.error("RPC timeout: Failed to send topo disc on the server")

    def uplink_bond_intf_process(self):
        """Process the case when uplink interface becomes part of a bond.

        This is called to check if the phy interface became a part of the
        bond. If the below condition is True, this means, a physical
        interface that was not a part of a bond was earlier discovered as
        uplink and now that interface became part of the bond.
        Usually, this doesn't happen as LLDP and in turn this function will
        first detect a 'down' followed by an 'up'. When regular interface
        becomes part of bond, it's rare for it to hit this 'normal' case.
        But, still providing the functionality if it happens.
        The following is done :
        a. Bring down the physical interface by sending a 'down' event
        b. Add the bond interface by sending an 'up' event
        Consquently, when bond is added that will be assigned to
        self.phy_uplink. Then, the below condition will be False. i.e..
        'get_bond_intf' will return False, when the argument is 'bond0'.
        """
        bond_intf = sys_utils.get_bond_intf(self.phy_uplink)
        if bond_intf is None:
            return False
        self.save_uplink(
            fail_reason=constants.port_transition_bond_down_reason)
        self.process_uplink_ongoing = True
        upl_msg = VdpQueMsg(constants.UPLINK_MSG_TYPE, status='down',
                            phy_uplink=self.phy_uplink,
                            br_int=self.br_integ, br_ex=self.br_ex,
                            root_helper=self.root_helper)
        self.que.enqueue(constants.Q_UPL_PRIO, upl_msg)
        self.phy_uplink = None
        self.veth_intf = None
        self.uplink_det_compl = False

        # No veth interface
        self.save_uplink(
            uplink=bond_intf,
            fail_reason=constants.port_transition_bond_up_reason)
        self.phy_uplink = bond_intf
        self.process_uplink_ongoing = True
        upl_msg = VdpQueMsg(constants.UPLINK_MSG_TYPE, status='up',
                            phy_uplink=self.phy_uplink,
                            br_int=self.br_integ, br_ex=self.br_ex,
                            root_helper=self.root_helper)
        self.que.enqueue(constants.Q_UPL_PRIO, upl_msg)
        return True

    def check_periodic_bulk_vm_notif_rcvd(self):
        """Bulk VM check handler called from periodic uplink detection.

        This gets called by the 'normal' stage of uplink detection.
        The bulk VM event sends all the VM's running in this agent.
        Sometimes during upgrades, it was found that due to some race
        condition, the server does not send the Bulk VM event.
        Whenever, a save_uplink is done by the agent, the server sends
        the Bulk VM event.
        If Bulk VM event is not received after few attempts, save_uplink is
        done to request the Bulk VM list.
        It's not protected with a mutex, since worst case,
        Bulk VM event will be sent twice, which is not that bad. When
        uplink is detected for the first time, it will hit the below
        else case and there a save_uplink is anyways done.
        """
        if not self.bulk_vm_rcvd_flag:
            if self.bulk_vm_check_cnt >= 1:
                self.bulk_vm_check_cnt = 0
                self.save_uplink(uplink=self.phy_uplink,
                                 veth_intf=self.veth_intf)
                LOG.info(_LI("Doing save_uplink again to request "
                             "Bulk VM's"))
            else:
                LOG.info(_LI("Bulk VM not received, incrementing count"))
                self.bulk_vm_check_cnt += 1

    def static_uplink_detect(self, veth):
        """Return the static uplink based on argument passed.

        The very first time, this function is called, it returns the uplink
        port read from a file.
        After restart, when this function is called the first time, it
        returns 'normal' assuming a veth is passed to this function which will
        be the case if uplink processing is successfully done.
        If user modified the uplink configuration and restarted, a 'down'
        will be returned to clear the old uplink.
        """
        LOG.info(_LI("In static_uplink_detect %(veth)s"), {'veth': veth})
        if self.static_uplink_first:
            self.static_uplink_first = False
            if self.phy_uplink is not None and (
               self.phy_uplink != self.static_uplink_port):
                return 'down'
        if veth is None:
            return self.static_uplink_port
        else:
            return 'normal'

    def vdp_uplink_proc(self):
        """Periodic handler to detect the uplink interface to the switch.

        -> restart_uplink_called: should be called by agent initially to set
           the stored uplink and veth from DB
        -> process_uplink_ongoing: Will be set when uplink message is enqueue
           and reset when dequeued and processed completely
        -> uplink_det_compl: Will be set to True when a valid uplink is
           detected and object created. Will be reset when uplink is down
        -> phy_uplink: Is the uplink interface
        -> veth_intf : Signifies the veth interface.
        """
        LOG.info(_LI("In Periodic Uplink Task"))
        if not self.is_os_run:
            if not self.is_openstack_running():
                LOG.info(_LI("OpenStack is not running"))
                return
            else:
                self.is_os_run = True
        if not self.restart_uplink_called or self.process_uplink_ongoing:
            LOG.info(_LI("Uplink before restart not refreshed yet..states "
                         "%(ruc)d %(puo)d"),
                     {'ruc': self.restart_uplink_called,
                      'puo': self.process_uplink_ongoing})
            return
        if self.phy_uplink is not None:
            if (self.uplink_det_compl and (
               self.phy_uplink not in self.ovs_vdp_obj_dict)):
                LOG.error(_LE("Not Initialized for phy %s"), self.phy_uplink)
                return
            if self.phy_uplink in self.ovs_vdp_obj_dict:
                self.veth_intf = (self.ovs_vdp_obj_dict[self.phy_uplink].
                                  get_lldp_local_bridge_port())
            # The below logic has a bug when agent is started
            # and openstack is not running fixme(padkrish)
            else:
                if self.veth_intf is None:
                    LOG.error(_LE("Incorrect state, Bug"))
                    return
        if self.static_uplink:
            ret = self.static_uplink_detect(self.veth_intf)
        else:
            ret = uplink_det.detect_uplink(self.veth_intf)
        if ret is 'down':
            if self.phy_uplink is None:
                LOG.error(_LE("Wrong status down"))
                return
            # Call API to set the uplink as "" DOWN event
            self.uplink_down_cnt = self.uplink_down_cnt + 1
            if not self.static_uplink and (
               self.uplink_down_cnt < constants.UPLINK_DOWN_THRES):
                return
            self.process_uplink_ongoing = True
            upl_msg = VdpQueMsg(constants.UPLINK_MSG_TYPE,
                                status='down',
                                phy_uplink=self.phy_uplink,
                                br_int=self.br_integ, br_ex=self.br_ex,
                                root_helper=self.root_helper)
            self.que.enqueue(constants.Q_UPL_PRIO, upl_msg)
            self.phy_uplink = None
            self.veth_intf = None
            self.uplink_det_compl = False
            self.uplink_down_cnt = 0
        elif ret is None:
            if self.veth_intf is not None:
                LOG.error(_LE("Wrong status None"))
                return
            # Call API to set the uplink as "" Uplink not discovered yet
            self.save_uplink(fail_reason=constants.uplink_undiscovered_reason)
        elif ret is 'normal':
            if self.veth_intf is None:
                LOG.error(_LE("Wrong status Normal"))
                return
            # Uplink already discovered, nothing to be done here
            # Resetting it back, happens when uplink was down for a very short
            # time and no need to remove flows
            self.uplink_down_cnt = 0
            bond_det = self.uplink_bond_intf_process()
            # Revisit this logic.
            # If uplink detection fails, it will be put in Error queue, which
            # will dequeue and put it back in the main queue
            # At the same time this periodic task will also hit this normal
            # state and will put the message in main queue. fixme(padkrish)
            # The below lines are put here because after restart when
            # eth/veth are passed to uplink script, it will return normal
            # But OVS object would not have been created for the first time,
            # so the below lines ensures it's done.
            if not self.uplink_det_compl and not bond_det:
                if self.phy_uplink is None:
                    LOG.error(_LE("Incorrect state, bug"))
                    return
                self.process_uplink_ongoing = True
                upl_msg = VdpQueMsg(constants.UPLINK_MSG_TYPE,
                                    status='up',
                                    phy_uplink=self.phy_uplink,
                                    br_int=self.br_integ, br_ex=self.br_ex,
                                    root_helper=self.root_helper)
                self.que.enqueue(constants.Q_UPL_PRIO, upl_msg)
                # yield
                LOG.info(_LI("Enqueued Uplink Msg from normal"))
            self.check_periodic_bulk_vm_notif_rcvd()
        else:
            LOG.info(_LI("In Periodic Uplink Task uplink found %s"), ret)
            bond_intf = sys_utils.get_bond_intf(ret)
            if bond_intf is not None:
                ret = bond_intf
                LOG.info(_LI("Interface %(memb)s part of bond %(bond)s") %
                         {'memb': ret, 'bond': bond_intf})
            # Call API to set the uplink as ret
            self.save_uplink(uplink=ret, veth_intf=self.veth_intf)
            self.phy_uplink = ret
            self.process_uplink_ongoing = True
            upl_msg = VdpQueMsg(constants.UPLINK_MSG_TYPE,
                                status='up',
                                phy_uplink=self.phy_uplink,
                                br_int=self.br_integ, br_ex=self.br_ex,
                                root_helper=self.root_helper)
            self.que.enqueue(constants.Q_UPL_PRIO, upl_msg)
            # yield
            LOG.info(_LI("Enqueued Uplink Msg"))

    def vdp_vm_event(self, vm_dict_list):
        if isinstance(vm_dict_list, list):
            vm_msg = VdpQueMsg(constants.VM_BULK_SYNC_MSG_TYPE,
                               vm_bulk_list=vm_dict_list,
                               phy_uplink=self.phy_uplink)
            self.bulk_vm_rcvd_flag = True
        else:
            vm_dict = vm_dict_list
            LOG.info(_LI("Obtained VM event Enqueueing Status %(status)s "
                         "MAC %(mac)s uuid %(uuid)s oui %(oui)s"),
                     {'status': vm_dict['status'], 'mac': vm_dict['vm_mac'],
                      'uuid': vm_dict['net_uuid'], 'oui': vm_dict['oui']})
            vm_msg = VdpQueMsg(constants.VM_MSG_TYPE,
                               port_uuid=vm_dict['port_uuid'],
                               vm_mac=vm_dict['vm_mac'],
                               net_uuid=vm_dict['net_uuid'],
                               segmentation_id=vm_dict['segmentation_id'],
                               status=vm_dict['status'],
                               oui=vm_dict['oui'],
                               phy_uplink=self.phy_uplink)
        self.que.enqueue(constants.Q_VM_PRIO, vm_msg)

    def is_uplink_received(self):
        """Returns whether uplink information is received after restart.

        Not protecting this with a mutex, since this gets called inside the
        loop from dfa_agent and having a mutex is a overkill. Worst case,
        during multiple restarts on server and when the corner case is hit,
        this may return an incorrect value of False when _dfa_uplink_restart
        is at the middle of execution. Returning an incorrect value of False,
        may trigger an RPC to the server to retrieve the uplink one extra time.
        _dfa_uplink_restart will not get executed twice, since that is anyway
        protected with a mutex.
        """
        return self.restart_uplink_called

    def dfa_uplink_restart(self, uplink_dict):
        try:
            with self.vdp_mgr_lock:
                if not self.restart_uplink_called:
                    self._dfa_uplink_restart(uplink_dict)
        except Exception as exc:
            LOG.error(_LE("Exception in dfa_uplink_restart %s") % str(exc))

    def _dfa_uplink_restart(self, uplink_dict):
        LOG.info(_LI("Obtained uplink after restart %s "), uplink_dict)
        # This shouldn't happen
        if self.phy_uplink is not None:
            LOG.error(_LE("Uplink detection already done %s"), self.phy_uplink)
            return
        uplink = uplink_dict.get('uplink')
        veth_intf = uplink_dict.get('veth_intf')
        # Logic is as follows:
        # If DB didn't have any uplink it means it's not yet detected or down
        # if DB has uplink and veth, then no need to scan all ports we can
        # start with this veth.
        # If uplink has been removed or modified during restart, then a
        # down will be returned by uplink detection code and it will be
        # removed then.
        # If DB has uplink, but no veth, it's an error condition and in
        # which case remove the uplink port from bridge and start fresh
        if uplink is None or len(uplink) == 0:
            LOG.info(_LI("uplink not discovered yet"))
            self.restart_uplink_called = True
            return
        if veth_intf is not None and len(veth_intf) != 0:
            LOG.info(_LI("veth interface is already added, %(ul)s %(veth)s"),
                     {'ul': uplink, 'veth': veth_intf})
            self.phy_uplink = uplink
            self.veth_intf = veth_intf
            self.restart_uplink_called = True
            return
        LOG.info(_LI("Error case removing the uplink %s from bridge"), uplink)
        ovs_vdp.delete_uplink_and_flows(self.root_helper, self.br_ex, uplink)
        self.restart_uplink_called = True


text:
'''
Global settings module for Color Switch
By @blopker
'''
import sublime
import os

plugin_name = 'ColorSwitch'
FOLDER_REL = 'Packages/User/' + plugin_name
FOLDER_THEMES_REL = FOLDER_REL + '/themes'
FOLDER_ABS = None
FOLDER_THEMES_ABS = None

PLUGIN_PREF = 'ColorSwitch.sublime-settings'
SUBLIME_PREF = 'Preferences.sublime-settings'

pluginObj = {}
sublimeObj = {}

def load():
    global FOLDER_ABS, FOLDER_THEMES_ABS
    FOLDER_ABS = os.path.join(sublime.packages_path(), 'User', plugin_name)
    FOLDER_THEMES_ABS = os.path.join(FOLDER_ABS, 'themes')

    global pluginObj
    pluginObj = sublime.load_settings(PLUGIN_PREF)

    global sublimeObj
    sublimeObj = sublime.load_settings(SUBLIME_PREF)

    # In case settings file is missing the debug value.
    debug = pluginObj.get('debug', None)
    if debug is None:
        pluginObj.set('debug', True)

def get(*args):
    return pluginObj.get(*args)

def get_themes_abs():
    return FOLDER_THEMES_ABS

def get_themes_rel():
    return FOLDER_THEMES_REL

def get_color_scheme():
    return sublimeObj.get('color_scheme', '')

def set_color_scheme(path):
    return sublimeObj.set('color_scheme', path)

def save_user():
    sublime.save_settings(SUBLIME_PREF)

def isDebug():
    return get('debug')

def platform():
    return sublime.platform()

def sublime_version():
    return int(sublime.version())

redpajama_set_name: RedPajamaGithub


text:
package org.crazyit.app.action;

import com.opensymphony.xwork2.*;
import java.util.Date;
import java.util.Set;

public class LoginAction extends ActionSupport
{
	private Set users;
	private Date birth;
	//userÊôÐÔµÄsetterºÍgetter·½·¨
	public void setUsers(Set users)
	{
		this.users = users;
	}
	public Set getUsers()
	{
		return this.users;
	}
	//birthÊôÐÔµÄsetterºÍgetter·½·¨
	public void setBirth(Date birth)
	{
		this.birth = birth;
	}
	public Date getBirth()
	{
		return this.birth;
	}
	//ûÓÐÌṩexecute()·½·¨,
	//½«Ö±½ÓʹÓÃActionSupportµÄexecute()·½·¨
}


text:
<?php
use common\models\ContentBlock;
use yii\db\Migration;

/**
 * Handles the creation of table `content_block`.
 */
class m170406_083622_create_content_block_table extends Migration {

    /**
     * @inheritdoc
     */
    public function safeUp() {
        if (Yii::$app->db->schema->getTableSchema('content_blocks', true)
            === null
        ) {
            $this->createTable('content_blocks', [
                'id' => $this->primaryKey(),
                'pageId' => $this->integer(),
                'ordering' => $this->integer(),
                'name' => $this->string(),
                'title' => $this->string(),
                'content' => $this->string(),
            ]);
        } else {
            $blocks = ContentBlock::find()->all();
            foreach ($blocks as $block) {
                $block->delete();
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->dropTable('content_blocks');
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAccountPayableAndReceivableTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('account_payable_and_receivable', function ($table) {
            $table->increments('id');
            $table->timestamp('form_date');
            $table->integer('formulir_reference_id')->unsigned()->index();
            $table->foreign('formulir_reference_id')
                ->references('id')->on('formulir')
                ->onUpdate('cascade')
                ->onDelete('cascade');
            $table->integer('account_id')->unsigned()->index();
            $table->foreign('account_id')
                ->references('id')->on('coa')
                ->onUpdate('restrict')
                ->onDelete('restrict');
            $table->decimal('amount', 16, 4);
            $table->string('type', 10); // payable or receivable
            $table->text('notes');
            $table->integer('person_id')->unsigned()->index();
            $table->foreign('person_id')
                ->references('id')->on('person')
                ->onUpdate('restrict')
                ->onDelete('restrict');
            $table->integer('reference_id')->index()->nullable();
            $table->string('reference_type')->index()->nullable();
            $table->boolean('done')->default(false);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('account_payable_and_receivable');
    }
}


text:
from .. import IICCCMessage as IICCCMessage
from . import ICCCGetListenersAnswer as ICCCGetListenersAnswer

class ICCCGetListeners(IICCCMessage):

    def __init__(self):
        self.__answer = ICCCGetListenersAnswer()

    def getAnswerObject(self) -> IICCCMessage:
        return self.__answer

    def getChannel(self) -> str:
        return "System::ICCC"

    def getCommand(self) -> str:
        return "ICCC::GetListeners"

    def setAnswerObject(self, answerObject: IICCCMessage):
        self.__answer = answerObject


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:background="@color/white"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textColor="#333333"
        android:textSize="16sp"
        tools:text="测试文字" />

    <com.jaeger.ninegridimageview.NineGridImageView
        android:id="@+id/ngl_images"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:imgGap="3dp"
        app:showStyle="grid"
        app:singleImgSize="500dp" />
</LinearLayout>


text:
import { Flex, Text } from 'componentry'
import FancyText from './fancy-text'
import { jsx as _jsx } from 'react/jsx-runtime'
export default function Test() {
  // Test that:
  // 1. as="string" works
  // 2. as={Identifier} works
  return /*#__PURE__*/ _jsx('main', {
    className: 'flex',
    children: /*#__PURE__*/ _jsx(FancyText, {
      className: 'C9Y-Text-base C9Y-Text-body mt-3',
      fancy: true,
      children: 'Precompiled for speed',
    }),
  })
}


text:
package org.calrissian.accumlorecipes.changelog.support;

import org.calrissian.commons.domain.Tuple;

import java.util.Comparator;

public class TupleComparator implements Comparator<Tuple> {

    @Override
    public int compare(Tuple tuple, Tuple tuple1) {
        try {
            String tupleString = Utils.tupleToString(tuple);
            String tuple1String = Utils.tupleToString(tuple1);

            return tupleString.compareTo(tuple1String);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


text:
(function() {
  angular.module('myApp', ['myApp.directives.sample'])
})();


text:
package telebot

import (
	"encoding/json"
	"fmt"
	"strings"
)

// Option is a shortcut flag type for certain message features
// (so-called options). It means that instead of passing
// fully-fledged SendOptions* to Send(), you can use these
// flags instead.
//
// Supported options are defined as iota-constants.
type Option int

const (
	// NoPreview = SendOptions.DisableWebPagePreview
	NoPreview Option = iota

	// Silent = SendOptions.DisableNotification
	Silent

	// ForceReply = ReplyMarkup.ForceReply
	ForceReply

	// OneTimeKeyboard = ReplyMarkup.OneTimeKeyboard
	OneTimeKeyboard
)

// SendOptions has most complete control over in what way the message
// must be sent, providing an API-complete set of custom properties
// and options.
//
// Despite its power, SendOptions is rather inconvenient to use all
// the way through bot logic, so you might want to consider storing
// and re-using it somewhere or be using Option flags instead.
type SendOptions struct {
	// If the message is a reply, original message.
	ReplyTo *Message

	// See ReplyMarkup struct definition.
	ReplyMarkup *ReplyMarkup

	// For text messages, disables previews for links in this message.
	DisableWebPagePreview bool

	// Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.
	DisableNotification bool

	// ParseMode controls how client apps render your message.
	ParseMode ParseMode

	// DisableContentDetection abilities to disable server-side file content type detection.
	DisableContentDetection bool

	// AllowWithoutReply allows sending messages not a as reply if the replied-to message has already been deleted.
	AllowWithoutReply bool
}

func (og *SendOptions) copy() *SendOptions {
	cp := *og
	if cp.ReplyMarkup != nil {
		cp.ReplyMarkup = cp.ReplyMarkup.copy()
	}
	return &cp
}

// ReplyMarkup controls two convenient options for bot-user communications
// such as reply keyboard and inline "keyboard" (a grid of buttons as a part
// of the message).
type ReplyMarkup struct {
	// InlineKeyboard is a grid of InlineButtons displayed in the message.
	//
	// Note: DO NOT confuse with ReplyKeyboard and other keyboard properties!
	InlineKeyboard [][]InlineButton `json:"inline_keyboard,omitempty"`

	// ReplyKeyboard is a grid, consisting of keyboard buttons.
	//
	// Note: you don't need to set HideCustomKeyboard field to show custom keyboard.
	ReplyKeyboard [][]ReplyButton `json:"keyboard,omitempty"`

	// ForceReply forces Telegram clients to display
	// a reply interface to the user (act as if the user
	// has selected the bot's message and tapped "Reply").
	ForceReply bool `json:"force_reply,omitempty"`

	// Requests clients to resize the keyboard vertically for optimal fit
	// (e.g. make the keyboard smaller if there are just two rows of buttons).
	//
	// Defaults to false, in which case the custom keyboard is always of the
	// same height as the app's standard keyboard.
	ResizeReplyKeyboard bool `json:"resize_keyboard,omitempty"`

	// Requests clients to hide the reply keyboard as soon as it's been used.
	//
	// Defaults to false.
	OneTimeKeyboard bool `json:"one_time_keyboard,omitempty"`

	// Requests clients to remove the reply keyboard.
	//
	// Defaults to false.
	ReplyKeyboardRemove bool `json:"remove_keyboard,omitempty"`

	// Use this param if you want to force reply from
	// specific users only.
	//
	// Targets:
	// 1) Users that are @mentioned in the text of the Message object;
	// 2) If the bot's message is a reply (has SendOptions.ReplyTo),
	//       sender of the original message.
	Selective bool `json:"selective,omitempty"`
}

func (r *ReplyMarkup) copy() *ReplyMarkup {
	cp := *r

	if len(r.ReplyKeyboard) > 0 {
		cp.ReplyKeyboard = make([][]ReplyButton, len(r.ReplyKeyboard))
		for i, row := range r.ReplyKeyboard {
			cp.ReplyKeyboard[i] = make([]ReplyButton, len(row))
			copy(cp.ReplyKeyboard[i], row)
		}
	}

	if len(r.InlineKeyboard) > 0 {
		cp.InlineKeyboard = make([][]InlineButton, len(r.InlineKeyboard))
		for i, row := range r.InlineKeyboard {
			cp.InlineKeyboard[i] = make([]InlineButton, len(row))
			copy(cp.InlineKeyboard[i], row)
		}
	}

	return &cp
}

// ReplyButton represents a button displayed in reply-keyboard.
//
// Set either Contact or Location to true in order to request
// sensitive info, such as user's phone number or current location.
// (Available in private chats only.)
type ReplyButton struct {
	Text string `json:"text"`

	Contact  bool     `json:"request_contact,omitempty"`
	Location bool     `json:"request_location,omitempty"`
	Poll     PollType `json:"request_poll,omitempty"`
}

// InlineKeyboardMarkup represents an inline keyboard that appears
// right next to the message it belongs to.
type InlineKeyboardMarkup struct {
	// Array of button rows, each represented by
	// an Array of KeyboardButton objects.
	InlineKeyboard [][]InlineButton `json:"inline_keyboard,omitempty"`
}

// MarshalJSON implements json.Marshaler. It allows to pass
// PollType as keyboard's poll type instead of KeyboardButtonPollType object.
func (pt PollType) MarshalJSON() ([]byte, error) {
	var aux = struct {
		Type string `json:"type"`
	}{
		Type: string(pt),
	}
	return json.Marshal(&aux)
}

// Row represents an array of buttons, a row
type Row []Btn

// Row create a row of buttons
func (r *ReplyMarkup) Row(many ...Btn) Row {
	return many
}

func (r *ReplyMarkup) Inline(rows ...Row) {
	inlineKeys := make([][]InlineButton, 0, len(rows))
	for i, row := range rows {
		keys := make([]InlineButton, 0, len(row))
		for j, btn := range row {
			btn := btn.Inline()
			if btn == nil {
				panic(fmt.Sprintf(
					"telebot: button row %d column %d is not an inline button",
					i, j))
			}
			keys = append(keys, *btn)
		}
		inlineKeys = append(inlineKeys, keys)
	}

	r.InlineKeyboard = inlineKeys
}

func (r *ReplyMarkup) Reply(rows ...Row) {
	replyKeys := make([][]ReplyButton, 0, len(rows))
	for i, row := range rows {
		keys := make([]ReplyButton, 0, len(row))
		for j, btn := range row {
			btn := btn.Reply()
			if btn == nil {
				panic(fmt.Sprintf(
					"telebot: button row %d column %d is not a reply button",
					i, j))
			}
			keys = append(keys, *btn)
		}
		replyKeys = append(replyKeys, keys)
	}

	r.ReplyKeyboard = replyKeys
}

func (r *ReplyMarkup) Text(text string) Btn {
	return Btn{Text: text}
}

func (r *ReplyMarkup) Contact(text string) Btn {
	return Btn{Contact: true, Text: text}
}

func (r *ReplyMarkup) Location(text string) Btn {
	return Btn{Location: true, Text: text}
}

func (r *ReplyMarkup) Poll(text string, poll PollType) Btn {
	return Btn{Poll: poll, Text: text}
}

func (r *ReplyMarkup) Data(text, unique string, data ...string) Btn {
	return Btn{
		Unique: unique,
		Text:   text,
		Data:   strings.Join(data, "|"),
	}
}

func (r *ReplyMarkup) URL(text, url string) Btn {
	return Btn{Text: text, URL: url}
}

func (r *ReplyMarkup) Query(text, query string) Btn {
	return Btn{Text: text, InlineQuery: query}
}

func (r *ReplyMarkup) QueryChat(text, query string) Btn {
	return Btn{Text: text, InlineQueryChat: query}
}

func (r *ReplyMarkup) Login(text string, login *Login) Btn {
	return Btn{Login: login, Text: text}
}

// Btn is a constructor button, which will later become either a reply, or an inline button.
type Btn struct {
	Unique          string
	Text            string
	URL             string
	Data            string
	InlineQuery     string
	InlineQueryChat string
	Contact         bool
	Location        bool
	Poll            PollType
	Login           *Login
}

func (b Btn) Inline() *InlineButton {
	return &InlineButton{
		Unique:          b.Unique,
		Text:            b.Text,
		URL:             b.URL,
		Data:            b.Data,
		InlineQuery:     b.InlineQuery,
		InlineQueryChat: b.InlineQueryChat,
		Login:           b.Login,
	}
}

func (b Btn) Reply() *ReplyButton {
	if b.Unique != "" {
		return nil
	}

	return &ReplyButton{
		Text:     b.Text,
		Contact:  b.Contact,
		Location: b.Location,
		Poll:     b.Poll,
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

-->

<types xmlns="commonj.sdo"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:sdoJava="commonj.sdo/java"
  xsi:schemaLocation="commonj.sdo sdoModel.xsd commonj.sdo/java sdoJava.xsd commonj.sdo/xml sdoXML.xsd">

<!--
   Global properties used in open content for
   the Java binding of SDO Types and Properties.
-->

  <type uri="commonj.sdo/java">
    <property name="javaClass" type="commonj.sdo#String"/>
  </type>

  <!-- JavaInfo deprecated in 2.1.0 -->
  <type name="JavaInfo" uri="commonj.sdo/java">
    <property name="javaClass" type="commonj.sdo#String"/>
  </type>

<!--
   The Java object data types.
-->

  <type name="BooleanObject" dataType="true" sdoJava:instanceClass="java.lang.Boolean" uri="commonj.sdo/java"/>
  <type name="ByteObject" dataType="true" sdoJava:instanceClass="java.lang.Byte" uri="commonj.sdo/java"/>
  <type name="CharacterObject" dataType="true" sdoJava:instanceClass="java.lang.Character" uri="commonj.sdo/java"/>
  <type name="DoubleObject" dataType="true" sdoJava:instanceClass="java.lang.Double" uri="commonj.sdo/java"/>
  <type name="FloatObject" dataType="true" sdoJava:instanceClass="java.lang.Float" uri="commonj.sdo/java"/>
  <type name="IntObject" dataType="true" sdoJava:instanceClass="java.lang.Int" uri="commonj.sdo/java"/>
  <type name="LongObject" dataType="true" sdoJava:instanceClass="java.lang.Long" uri="commonj.sdo/java"/>
  <type name="ShortObject" dataType="true" sdoJava:instanceClass="java.lang.Short" uri="commonj.sdo/java"/>

</types>


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:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent">
    </FrameLayout>

</LinearLayout>


text:
NodeJS task for publishing a project. Intended to be used in NPM script.

The workflow is set for my personal projects. I plan to add the support for per-project configuration. In the meantime, use at your own risk.

# Install

```shell
npm install bag-and-tag
```

## How to use it

Add task to your `package.json`:

```json
{
  "scripts": {
    "release": "./node_modules/.bin/bag-and-tag"
  }
}
```

Then, when you want to release a new version of the project:

```shell
npm run release
```

## Bug reports, feature requests and contact

If you found any bugs, if you have feature requests or any questions, please, either [file an issue at GitHub](https://github.com/fczbkk/bag-and-tag/issues) or send me an e-mail at [riki@fczbkk.com](mailto:riki@fczbkk.com).

## License

This library is published under the [MIT license](https://github.com/fczbkk/bag-and-tag/blob/master/LICENSE).


text:
The v10.0 release of *kubernetes-engine* is a backwards incompatible
release.

## Provider Version

- For beta modules, support for Google provider versions older than v3.29 has been removed.
- For GA modules, provider version constraints are unchanged.

## Default Machine Type
The new default machine type for node pools is now `e2-medium`. These VMs are more cost-effective. e2-medium machine types sustain 2 vCPUs at 50% of CPU time, yielding the same processing capacity as 1 vCPU and can temporarily burst to 2 vCPUs. Thus the sustained throughput is the same as n1-standard-1, so long as there are multiple threads running on the node -- and if you have multiple containers -- this is almost certainly the case.

However, `e2-medium` nodes don't work for all use cases. In particular, if you are using any of these features you should choose another machine type:

1. You're running single-threaded applications with sensitive performance requirements.
2. You use GPUs or local SSDs or sole tenancy, all of which are unsupported by the new default machine type e2-medium.

If you want to keep the old node type (`n1-standard-2`), you should specify it explicitly:

```diff
module "gke" {
    source        = "terraform-google-modules/kubernetes-engine/google"
-   version       = "~> 9.0"
+   version       = "~> 10.0"
...
    node_pools = [
      {
        name         = "pool-01"
+       machine_type = "n1-standard-2"
      },
    ]
}
```

## Pod Security Policy
The interface for configuring pod security policy has been [simplified](https://github.com/terraform-google-modules/terraform-google-kubernetes-engine/commit/6069ece9cd12acbbba8ff16ab0cbc9b17bc47985) to a simple boolean. If you've changed the default, you'll need to update your config:

```diff
module "gke" {
    source        = "terraform-google-modules/kubernetes-engine/google"
-   version       = "~> 9.0"
+   version       = "~> 10.0"
...
-   pod_security_policy_config = [{
-     enabled = true
-   }]
+   enable_pod_security_policy = true
}
```


text:
function foo () {
  return baz();
}

function bar () {
  return foo(baz);
}

function baz () {
  return bar();
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEpwPaymentTransactionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('epw_payment_transactions', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('epw_txnid')->nullable()->unique();
            $table->primary('id');
            $table->decimal('amount',12,4);
            $table->string('currency',5);
            $table->string('desc',1000);

            $table->boolean('payment_successful')->default(false);

            //customer details
            $table->string('cus_name',100);
            $table->string('cus_email',255);
            $table->string('cus_add1', 80);
            $table->string('cus_add2', 80)->nullable();
            $table->string('cus_city', 80);
            $table->string('cus_state', 80);
            $table->string('cus_postcode', 10);
            $table->string('cus_country', 50);
            $table->string('cus_phone', 20);
            $table->string('cus_fax', 20)->nullable();

            //optional payment details
            $table->string('payment_type',10)->nullable();
            $table->decimal('amount_vat',12,4)->nullable();
            $table->decimal('amount_vatRatio',12,4)->nullable();
            $table->decimal('amount_tax',12,4)->nullable();
            $table->decimal('amount_taxRatio',12,4)->nullable();
            $table->decimal('amount_processingfee',12,4)->nullable();
            $table->decimal('amount_processingfee_ratio',12,4)->nullable();

            //Shipping details
            $table->string('ship_name',100)->nullable();
            $table->string('ship_add1', 80)->nullable();
            $table->string('ship_add2', 80)->nullable();
            $table->string('ship_city', 80)->nullable();
            $table->string('ship_state', 80)->nullable();
            $table->string('ship_postcode', 10)->nullable();
            $table->string('ship_country', 50)->nullable();

            //optional fields
            $table->string('opt_a',60)->nullable();
            $table->string('opt_b',60)->nullable();
            $table->string('opt_c',60)->nullable();
            $table->string('opt_d',60)->nullable();

            $table->nullableTimestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('epw_payment_transactions');
    }
}


text:
<?php

class sfValidatorReCaptcha extends sfValidatorBase
{
  const RECAPTCHA_API_VERIFY='http://api-verify.recaptcha.net/verify';

  protected function configure($options = array(), $messages = array())
  {
    $this->addRequiredOption('privatekey');

    $this->setOption('required',false);
  }

  protected function getEmptyValue()
  {
    throw new sfValidatorError($this,'invalid',array('recaptcha'=>'incorrect-captcha-sol'));
  }

  protected function doClean($values)
  {
    if (!(is_array($values)&&isset($values['challenge'])&&isset($values['response'])))
    {
      throw new sfValidatorError($this,'invalid',array('recaptcha'=>'verify-params-incorrect'));
    }

    $data=http_build_query(array(
      'privatekey'=>$this->getOption('privatekey'),
      'remoteip'=>$_SERVER['REMOTE_ADDR'],
      'challenge'=>$values['challenge'],
      'response'=>$values['response']
    ));
    $opts = array(
      'http'=>array(
        'method'=>"POST",
        'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
                  "Content-length: " . strlen($data) . "\r\n".
                  "Connection: close\r\n",
        'content'=>$data
      )
    );

    $ctx=stream_context_create($opts);
    $ret=@file_get_contents(self::RECAPTCHA_API_VERIFY,0,$ctx);
    if ($ret===false)
    {
      $ret="false\nrecaptcha-not-reachable";
    }
    $resp=explode(chr(10),str_replace(chr(13),'',$ret));

    if ($resp[0]==='false')
    {
      throw new sfValidatorError($this,'invalid',array('recaptcha'=>$resp[1]));
    }
    else if ($resp[0]==='true')
    {
      return null;
    }
    else
    {
      throw new sfValidatorError($this,'invalid',array('recaptcha'=>'recaptcha-not-reachable'));
    }
  }
}


text:
var modules = [];

var v = function(modules) {
  // Check all modules for deduplicated modules
  for(var i in modules) {
    if(Object.prototype.hasOwnProperty.call(modules, i)) {
      switch(typeof modules[i]) {
        case "function": break;
        case "object":
          // Module can be created from a template
          modules[i] = (function(_m) {
            var args = _m.slice(1), fn = modules[_m[0]];
            return function (a,b,c) {
              fn.apply(this, [a,b,c].concat(args)); // Breaks here
            };
          }(modules[i]));
          break;
        default:
          // Module is a copy of another module
          modules[i] = modules[modules[i]];
          break;
      }
    }
  }
  return modules;
}


text:
namespace EmergencyV
{
    using System;
    using System.Collections.Generic;

    using Rage;

    internal class CPRManager
    {
        private static CPRManager instance;
        internal static CPRManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new CPRManager();
                return instance;
            }
        }

        internal Dictionary<Ped, bool> TreatedPeds { get; } = new Dictionary<Ped, bool>();

        internal bool ShouldSearchLocally { get; set; } = true;

        private List<CPR> Active { get; } = new List<CPR>();

        internal void Start(CPR cpr)
        {
            if (Active.Contains(cpr))
                return;
            Active.Add(cpr);
            cpr.Start();
        }

        internal bool HasActiveCPR(Ped patient)
        {
            foreach (CPR cpr in Active)
            {
                if (cpr.Patient == patient)
                    return true;
            }
            return false;
        }

        private void onFinished(CPR cpr)
        {
            TreatedPeds.Add(cpr.Patient, cpr.WasSuccessful);

            if (!cpr.WasSuccessful && cpr.ShouldShowDeathReportWhenFinished)
                DeathManager.Instance.ShowReport(cpr.Patient);
        }

        private void searchLocally()
        {
            if (Game.LocalPlayer.Character.IsOnFoot)
            {
                Ped localPatient = Util.GetClosestDeadPed(Game.LocalPlayer.Character.Position, 1.75f);

                if (localPatient && !HasActiveCPR(localPatient) && !TreatedPeds.ContainsKey(localPatient))
                {
                    Game.DisplayHelp("Press ~INPUT_CONTEXT~ to attempt CPR", 20);

                    if (Game.IsControlJustPressed(0, GameControl.Context))
                    {
                        Start(new CPR(localPatient, Game.LocalPlayer.Character));
                    }
                }
            }
        }

        internal void Update()
        {
            if (ShouldSearchLocally)
                searchLocally();

            if (Active.Count > 0)
            {
                foreach (CPR cpr in Active)
                {
                    cpr.Update();

                    if (cpr.IsFinished)
                        onFinished(cpr);
                }
                Active.RemoveAll(cpr => cpr.IsFinished);
            }
        }
    }
}


text:
package org.jolokia.docker.maven.assembly;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;

import org.apache.maven.project.MavenProject;
import org.jolokia.docker.maven.config.AssemblyConfiguration;
import org.jolokia.docker.maven.util.EnvUtil;
import org.jolokia.docker.maven.util.MojoParameters;
import org.junit.Before;
import org.junit.Test;

public class DockerAssemblyConfigurationSourceTest {

    private AssemblyConfiguration assemblyConfig;

    @Before
    public void setup() {
        // set 'ignorePermissions' to something other then default
        this.assemblyConfig = new AssemblyConfiguration.Builder()
                .descriptor("assembly.xml")
                .descriptorRef("project")
                .ignorePermissions(false)
                .build();
    }

    @Test
    public void testCreateSourceAbsolute() {
        testCreateSource(buildParameters(".", "/src/docker".replace("/", File.separator), "/output/docker".replace("/", File.separator)));
    }

    @Test
    public void testCreateSourceRelative() {
        testCreateSource(buildParameters(".","src/docker".replace("/", File.separator), "output/docker".replace("/", File.separator)));
    }

    @Test
    public void testOutputDirHasImage() {
        String image = "image";
        MojoParameters params = buildParameters(".","src/docker", "output/docker");
        DockerAssemblyConfigurationSource source = new DockerAssemblyConfigurationSource(params,
                                                                                new BuildDirs(params,image),assemblyConfig);

        assertTrue(containsDir(image, source.getOutputDirectory()));
        assertTrue(containsDir(image, source.getWorkingDirectory()));
        assertTrue(containsDir(image, source.getTemporaryRootDirectory()));
    }

    private MojoParameters buildParameters(String projectDir, String sourceDir, String outputDir) {
        MavenProject mavenProject = new MavenProject();
        mavenProject.setFile(new File(projectDir));
        return new MojoParameters(null, mavenProject, null, null, null, sourceDir, outputDir);
    }

    @Test
    public void testEmptyAssemblyConfig() {
        DockerAssemblyConfigurationSource source = new DockerAssemblyConfigurationSource(
               new MojoParameters(null, null, null, null, null, "/src/docker", "/output/docker"),
               null,null
        );
        assertEquals(0,source.getDescriptors().length);
    }

    private void testCreateSource(MojoParameters params) {
        DockerAssemblyConfigurationSource source =
                new DockerAssemblyConfigurationSource(params, new BuildDirs(params,"image"),assemblyConfig);

        String[] descriptors = source.getDescriptors();
        String[] descriptorRefs = source.getDescriptorReferences();

        assertEquals("count of descriptors", 1, descriptors.length);
        assertEquals("directory of assembly", EnvUtil.prepareAbsoluteSourceDirPath(params, "assembly.xml").getAbsolutePath(), descriptors[0]);

        assertEquals("count of descriptors references", 1, descriptorRefs.length);
        assertEquals("reference must be project", "project", descriptorRefs[0]);

        assertFalse("We must not ignore permissions problems", source.isIgnorePermissions());

        String outputDir = params.getOutputDirectory();

        assertStartsWithDir(outputDir, source.getOutputDirectory());
        assertStartsWithDir(outputDir, source.getWorkingDirectory());
        assertStartsWithDir(outputDir, source.getTemporaryRootDirectory());
    }

    private boolean containsDir(String outputDir, File path) {
        return path.toString().contains(outputDir + File.separator);
    }

    private void assertStartsWithDir(String outputDir, File path) {
        String expectedStartsWith = outputDir + File.separator;
        int length = expectedStartsWith.length();
        assertEquals(expectedStartsWith, path.toString().substring(0, length));
    }
}


text:
package pm

import (
	"archive/tar"
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"time"
)

func Build(m *Metadata, outputDir string) error {
	tarGzPath := filepath.Join(outputDir, fmt.Sprintf("%s.tar.gz", m.PackageName()))
	tgz, err := os.Create(tarGzPath)
	if err != nil {
		return fmt.Errorf("pm: error creating %q: %v", tarGzPath, err)
	}

	gzw := gzip.NewWriter(tgz)
	defer gzw.Close()

	tarw := tar.NewWriter(gzw)
	defer tarw.Close()

	// Add the metadata file.
	if err := writeMetadata(tarw, m); err != nil {
		return err
	}

	// Add the binaries.
	for _, binPath := range m.Binaries {
		if err := tarAddBinary(tarw, m, binPath); err != nil {
			return err
		}
	}

	// Add resources (extra files).
	for baseDir, globs := range m.Resources {
		for _, g := range globs {
			resourceGlob := filepath.Join(baseDir, g)
			matches, err := filepath.Glob(resourceGlob)
			if err != nil {
				return fmt.Errorf("pm: bad globbing pattern: %q", resourceGlob)
			}

			for _, match := range matches {
				if err := writeResource(tarw, m, match); err != nil {
					return err
				}
			}
		}
	}

	return nil
}

func writeResource(tw *tar.Writer, m *Metadata, resourcePath string) error {
	f, err := os.Open(resourcePath)
	if err != nil {
		return fmt.Errorf("pm: error opening resource %q: %v", resourcePath, err)
	}
	defer f.Close()

	fileInfo, err := f.Stat()
	if err != nil {
		return fmt.Errorf("pm: error getting info for file %q: %v", resourcePath, err)
	}

	hdr, err := tar.FileInfoHeader(fileInfo, "")
	if err != nil {
		return fmt.Errorf("pm: error creating tar header for file %q: %v", resourcePath, err)
	}

	name := filepath.Join(fmt.Sprintf("%s-%s", m.Name, m.Version), filepath.Clean(resourcePath))
	hdr.Name = name
	hdr.Uid = 0
	hdr.Gid = 0
	hdr.Mode = 0444

	if err := tw.WriteHeader(hdr); err != nil {
		return fmt.Errorf("pm: error writing resource tar header for %q: %v", resourcePath, err)
	}

	if _, err := io.Copy(tw, f); err != nil {
		return fmt.Errorf("pm: error writing resource %q to archive: %v", resourcePath, err)
	}

	return nil
}

func writeMetadata(tw *tar.Writer, m *Metadata) error {
	b, err := json.MarshalIndent(m, "", "\t")
	if err != nil {
		return fmt.Errorf("pm: error marshaling metadata: %v", err)
	}

	now := time.Now()

	name := filepath.Join(fmt.Sprintf("%s-%s", m.Name, m.Version), "metadata.json")
	hdr := &tar.Header{
		Name:       name,
		Size:       int64(len(b)),
		ModTime:    now,
		AccessTime: now,
		ChangeTime: now,
		Mode:       0444,
	}

	if err := tw.WriteHeader(hdr); err != nil {
		return fmt.Errorf("pm: error writing metadata tar header: %v", err)
	}

	if _, err := tw.Write(b); err != nil {
		return fmt.Errorf("pm: error writing metadata: %v", err)
	}

	return nil
}

func tarAddBinary(tw *tar.Writer, m *Metadata, binPath string) error {
	bf, err := os.Open(binPath)
	if err != nil {
		return fmt.Errorf("pm: error opening binary file %q: %v", binPath, err)
	}
	defer bf.Close()

	info, err := bf.Stat()
	if err != nil {
		return fmt.Errorf("pm: error getting stat info on binary file %q: %v", binPath, err)
	}

	var hdr *tar.Header
	if hdr, err = tar.FileInfoHeader(info, ""); err != nil {
		return fmt.Errorf("pm: error creating header for binary file %q: %v", binPath, err)
	}

	name := filepath.Join(fmt.Sprintf("%s-%s", m.Name, m.Version), filepath.Clean(binPath))
	hdr.Name = name
	hdr.Uid = 0
	hdr.Gid = 0
	hdr.Mode = 0555

	if err := tw.WriteHeader(hdr); err != nil {
		return fmt.Errorf("pm: error writing tar header for %q: %v", binPath, err)
	}

	if _, err := io.Copy(tw, bf); err != nil {
		return fmt.Errorf("pm: error writing binary file %q: %v", binPath, err)
	}

	return nil
}


text:
package ru.assisttech.assistsdk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.github.dmstocking.optional.java.util.Optional;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wallet.AutoResolveHelper;
import com.google.android.gms.wallet.IsReadyToPayRequest;
import com.google.android.gms.wallet.PaymentData;
import com.google.android.gms.wallet.PaymentDataRequest;
import com.google.android.gms.wallet.PaymentsClient;
import com.google.android.gms.wallet.Wallet;
import com.google.android.gms.wallet.WalletConstants;
import com.samsung.android.sdk.samsungpay.v2.PartnerInfo;
import com.samsung.android.sdk.samsungpay.v2.SamsungPay;
import com.samsung.android.sdk.samsungpay.v2.SpaySdk;
import com.samsung.android.sdk.samsungpay.v2.StatusListener;
import com.samsung.android.sdk.samsungpay.v2.payment.CardInfo;
import com.samsung.android.sdk.samsungpay.v2.payment.CustomSheetPaymentInfo;
import com.samsung.android.sdk.samsungpay.v2.payment.PaymentManager;
import com.samsung.android.sdk.samsungpay.v2.payment.sheet.AmountBoxControl;
import com.samsung.android.sdk.samsungpay.v2.payment.sheet.AmountConstants;
import com.samsung.android.sdk.samsungpay.v2.payment.sheet.CustomSheet;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Locale;

import ru.assisttech.sdk.AssistMerchant;
import ru.assisttech.sdk.AssistPaymentData;
import ru.assisttech.sdk.AssistResult;
import ru.assisttech.sdk.AssistSDK;
import ru.assisttech.sdk.FieldName;
import ru.assisttech.sdk.engine.AssistPayEngine;
import ru.assisttech.sdk.engine.PayEngineListener;
import ru.assisttech.sdk.engine.PaymentTokenType;
import ru.assisttech.sdk.storage.AssistTransaction;
import ru.assisttech.sdk.storage.AssistTransactionStorage;

/**
 * Экран подтверждения данных платежа и выбора способа оплаты web или AndroidPay если доступен
 */
public class ConfirmationActivity extends FragmentActivity {

    public static final String TAG = "ConfirmationActivity";

    private static final String AMOUNT_CONTROL_ID = "amountControlId";
    private static final String PRODUCT_ITEM_ID = "productItemId";
    private static final String PRODUCT_TAX_ID = "productTaxId";
    private static final String PRODUCT_SHIPPING_ID = "productShippingId";
    private static final String PRODUCT_FUEL_ID = "productFuelId";

    private ApplicationConfiguration configuration;
    private AssistPayEngine engine;
    private AssistPaymentData data;

    private ProgressDialog progressDialog;

    // Google Pay (https://developers.google.com/pay/api/android/guides/tutorial)
    private static final int LOAD_PAYMENT_DATA_REQUEST_CODE = 42;
    private PaymentsClient paymentsClient;
    private Button btGooglePay;

    // Samsung Pay
    private Button btSamsungPay;
    private SamsungPay samsungPay;
    private Bundle bundle;
    private PaymentManager paymentManager;
    final String serviceId = "c84b694b18674b8f92e598";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirmation);

        configuration = ApplicationConfiguration.getInstance();
        engine = AssistSDK.getPayEngine(this);
        data = configuration.getPaymentData();

        if (data != null) {
            TextView tvServer = findViewById(R.id.tvServer);
            TextView tvMerchant = findViewById(R.id.tvMerchant);
            TextView tvOrderNumber = findViewById(R.id.tvOrderNumber);
            TextView tvOrderAmount = findViewById(R.id.tvOrderAmount);
            TextView tvOrderComment = findViewById(R.id.tvOrderComment);
            TextView tvLink = findViewById(R.id.tvLink);

            tvServer.setText(configuration.getServer());

            tvMerchant.setText(
                    String.format(
                            Locale.getDefault(),
                            "%1$s [%2$s: %3$s]",
                            data.getMerchantID(), data.getLogin(), data.getPassword()
                    )
            );
            tvOrderNumber.setText(data.getFields().get(FieldName.OrderNumber));
            if (data.getLink() == null) {
                tvOrderAmount.setText(
                        String.format(
                                Locale.getDefault(),
                                "%1$s %2$s",
                                data.getFields().get(FieldName.OrderAmount), data.getFields().get(FieldName.OrderCurrency)
                        )
                );
                tvOrderComment.setText(data.getFields().get(FieldName.OrderComment));
                findViewById(R.id.llLink).setVisibility(View.GONE);
            } else {
                tvLink.setText(data.getLink());
                findViewById(R.id.llOrderAmount).setVisibility(View.GONE);
                findViewById(R.id.llOrderComment).setVisibility(View.GONE);
            }

            Button btPayWeb = findViewById(R.id.btPay);
            btPayWeb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    payWeb();
                }
            });

            enableGooglePay();
            enableSamsungPay();
        } else {
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
        }
    }

    private void enableGooglePay() {

        // initialize a Google Pay API client for an environment suitable for testing
        paymentsClient = Wallet.getPaymentsClient(
                this,
                new Wallet.WalletOptions.Builder()
                        .setEnvironment(WalletConstants.ENVIRONMENT_TEST)
                        //.setEnvironment(WalletConstants.ENVIRONMENT_PRODUCTION)
                        .build()
        );

        final Optional<JSONObject> isReadyToPayJson = GooglePay.getIsReadyToPayRequest();
        if (!isReadyToPayJson.isPresent()) {
            return;
        }
        IsReadyToPayRequest request = IsReadyToPayRequest.fromJson(isReadyToPayJson.get().toString());
        if (request == null) {
            return;
        }
        Task<Boolean> task = paymentsClient.isReadyToPay(request);
        task.addOnCompleteListener(
                new OnCompleteListener<Boolean>() {
                    @Override
                    public void onComplete(@NonNull Task<Boolean> task) {
                        try {
                            boolean result = task.getResult(ApiException.class);
                            if (result) {
                                // show Google as a payment option
                                btGooglePay = findViewById(R.id.btGooglePay);
                                btGooglePay.setOnClickListener(
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                getOrderData(data.getFields().get(FieldName.OrderNumber));
                                            }
                                        });
                                btGooglePay.setVisibility(View.VISIBLE);
                            }
                        } catch (ApiException exception) {
                            // handle developer errors
                            Log.e(TAG, "Checking GooglePay feature error",exception);
                        }
                    }
                });
    }

    private void enableSamsungPay() {
        btSamsungPay = findViewById(R.id.btSamsungPay);

        bundle = new Bundle();
        bundle.putString(
                SpaySdk.PARTNER_SERVICE_TYPE, SpaySdk.ServiceType.INAPP_PAYMENT.toString()
        );

        PartnerInfo pInfo = new PartnerInfo(serviceId, bundle);
        samsungPay = new SamsungPay(this, pInfo);

        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            btSamsungPay.setVisibility(View.INVISIBLE);
        } else {
            samsungPay.getSamsungPayStatus(new StatusListener() {
                @Override
                public void onSuccess(int i, Bundle bundle) {
                    processSamsungPayStatus(i);
                }

                @Override
                public void onFail(int i, Bundle bundle) {
                    btSamsungPay.setVisibility(View.INVISIBLE);
                    Log.d(TAG, "checkSamsungPayStatus onFail() : " + i);
                }
            });
        }
        btSamsungPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startSamsungPay();
            }
        });
    }

    /**
     * Handle a resolved activity from the Google Pay payment sheet
     *
     * @param requestCode the request code originally supplied to AutoResolveHelper in
     *     requestPayment()
     * @param resultCode the result code returned by the Google Pay API
     * @param data an Intent from the Google Pay API containing payment or error data
     * @see Getting a result
     *     from an Activity
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "requestCode: " + requestCode + "; resultCode: " + resultCode);
        if (requestCode == LOAD_PAYMENT_DATA_REQUEST_CODE) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    Log.d("TAG", "RESULT_OK");
                    try {
                        PaymentData paymentData = PaymentData.getFromIntent(data);
                        String json = paymentData.toJson();
                        Log.d(TAG, "PAYMENT_DATA: " + json);
                        // if using gateway tokenization, pass this token without modification
                        JSONObject paymentMethodData = new JSONObject(json).getJSONObject("paymentMethodData");
                        String paymentToken = paymentMethodData
                                .getJSONObject("tokenizationData")
                                .getString("token");

                        payToken(paymentToken, PaymentTokenType.GOOGLE_PAY);

                    } catch (Exception e) {
                        Log.e(TAG, "Getting GooglePay payment data error ", e);
                    }
                    break;
                case Activity.RESULT_CANCELED:
                    Log.d("TAG", "RESULT_CANCELED");
                    break;
                case AutoResolveHelper.RESULT_ERROR:
                    Log.d("TAG", "RESULT_ERROR");
                    Status status = AutoResolveHelper.getStatusFromIntent(data);
                    // Log the status for debugging.
                    // Generally, there is no need to show an error to the user.
                    // The Google Pay payment sheet will present any account errors.
                    Log.e(TAG, "Getting Google Pay token error: " + status);
                    break;
                default:
                    Log.d("TAG", "DEFAULT");
                    // Do nothing.
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * Display the Google Pay payment sheet after interaction with the Google Pay payment button
     */
    public void requestPayment() {
        Optional<JSONObject> paymentDataRequestJson =
                GooglePay.getPaymentDataRequest(
                        "Example Merchant",
                        data.getMerchantID(),
                        data.getFields().get(FieldName.OrderAmount),
                        data.getFields().get(FieldName.OrderCurrency));
        if (!paymentDataRequestJson.isPresent()) {
            return;
        }
        PaymentDataRequest request =
                PaymentDataRequest.fromJson(paymentDataRequestJson.get().toString());
        if (request != null) {
            AutoResolveHelper.resolveTask(
                    paymentsClient.loadPaymentData(request), this, LOAD_PAYMENT_DATA_REQUEST_CODE);
        }
    }

    private void payWeb() {
        engine.setEngineListener(new PEngineListener());
        engine.payWeb(this, data, configuration.isUseCamera());
    }

    private void payToken(String token, PaymentTokenType type) {
        Log.d("TAG", "Pay with token: [" + token + "] " + type);
        data.setPaymentToken(token);
        engine.setEngineListener(new PEngineListener());
        showProgress(getString(R.string.please_wait));
        engine.payToken(this, data, type);
    }

    private void declineByNumber(String orderNumber) {
        Log.d(TAG, "Decline by orderNumber=" + orderNumber);
        AssistMerchant m = new AssistMerchant(data.getMerchantID(), data.getLogin(), data.getPassword());
        AssistTransactionStorage storage = engine.transactionStorage();
        Cursor cursor = storage.getData(orderNumber);
        if (cursor != null) {
            cursor.moveToFirst();
            AssistTransaction t = storage.transactionFromCursor(cursor);

            if (t != null) {
                AssistResult.OrderState state = t.getResult().getOrderState();
                if (AssistResult.OrderState.IN_PROCESS.equals(state) || AssistResult.OrderState.UNKNOWN.equals(state)) {
                    engine.setEngineListener(new PEngineListener());
                    showProgress(getString(R.string.please_wait));
                    engine.declineByNumberPayment(this, t, m);
                }
            }
        }
    }

    private void getOrderData(String orderNumber) {
        Log.d(TAG, "Get data for orderNumber=" + orderNumber);
        data.setOrderNumber(orderNumber);
        engine.setEngineListener(new OrderDataListener());
        showProgress(getString(R.string.please_wait));
        engine.getAmountForOrder(this, data);
    }

    private void showAlertDialog(Activity activity, String dlgTitle, String dlgMessage) {
        showAlertDialog(activity, dlgTitle, dlgMessage, false);
    }

    private void showAlertDialog(Activity activity, String dlgTitle, String dlgMessage, final boolean finish) {
        Log.d(TAG, "Show alert: " + dlgTitle);
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(dlgTitle);
        builder.setMessage(dlgMessage);
        builder.setNeutralButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (finish) {
                    finish();
                }
            }
        });
        builder.show();
    }

    void showProgress(String message) {
        // Construct a progress dialog to prevent user from actions until connection is finished.
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            if (TextUtils.isEmpty(message)) {
                progressDialog.setMessage(getString(R.string.please_wait));
            } else {
                progressDialog.setMessage(message);
            }
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        } else {
            progressDialog.setMessage(message);
        }
    }

    void hideProgress() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * Слушатель результата проведения оплаты
     */
    private class PEngineListener implements PayEngineListener {
        @Override
        public void onFinished(Activity activity, AssistTransaction assistTransaction) {
            hideProgress();
            Intent intent = new Intent(ConfirmationActivity.this, ViewResultActivity.class);
            intent.putExtra(ViewResultActivity.TRANSACTION_ID_EXTRA, assistTransaction != null ? assistTransaction.getId() : -1);
            startActivity(intent);
        }
        @Override
        public void onCanceled(Activity activity, AssistTransaction assistTransaction) {
            hideProgress();
        }
        @Override
        public void onFailure(Activity activity, String info) {
            hideProgress();
            showAlertDialog(activity, getString(R.string.alert_dlg_title_error), info, true);
        }
        @Override
        public void onNetworkError(Activity activity, String message) {
            hideProgress();
            showAlertDialog(activity, getString(R.string.alert_dlg_title_network_error), message);
        }
    }

    private class OrderDataListener implements PayEngineListener {
        @Override
        public void onFinished(Activity activity, AssistTransaction t) {
            hideProgress();
            if (t != null) {
                data.setOrderAmount(t.getOrderAmount());
                data.setOrderCurrency(t.getOrderCurrency());
            }
            requestPayment();
        }
        @Override
        public void onCanceled(Activity activity, AssistTransaction t) {
            hideProgress();
        }
        @Override
        public void onFailure(Activity activity, String info) {
            hideProgress();
            showAlertDialog(activity, getString(R.string.alert_dlg_title_error), info);
        }
        @Override
        public void onNetworkError(Activity activity, String message) {
            hideProgress();
            showAlertDialog(activity, getString(R.string.alert_dlg_title_network_error), message);
        }
    }

    private void processSamsungPayStatus(int status) {
        switch (status) {
            case SpaySdk.SPAY_NOT_SUPPORTED:
                btSamsungPay.setVisibility(View.INVISIBLE);
                break;
            case SpaySdk.SPAY_NOT_READY:
                int extraReason = bundle.getInt(SpaySdk.EXTRA_ERROR_REASON);
                switch(extraReason) {
                    case SpaySdk.ERROR_SPAY_APP_NEED_TO_UPDATE:
                        samsungPay.goToUpdatePage();
                        break;
                    case SpaySdk.ERROR_SPAY_SETUP_NOT_COMPLETED:
                        samsungPay.activateSamsungPay();
                        break;
                    default:
                        btSamsungPay.setVisibility(View.INVISIBLE);
                        Log.e(TAG, "Samsung PAY is not ready, extra reason: " + extraReason);
                }
                btSamsungPay.setVisibility(View.INVISIBLE);
                break;
            case SpaySdk.SPAY_READY:
                // Samsung Pay is ready
                btSamsungPay.setVisibility(View.VISIBLE);
                break;
            default:
                // Not expected result
                btSamsungPay.setVisibility(View.INVISIBLE);
                break;
        }
    }

    private void startSamsungPay() {
        try {
            Bundle bundle = new Bundle();
            bundle.putString(SpaySdk.PARTNER_SERVICE_TYPE, SpaySdk.ServiceType.INAPP_PAYMENT.toString());

            PartnerInfo partnerInfo = new PartnerInfo(serviceId, bundle);
            paymentManager = new PaymentManager(this, partnerInfo);
            paymentManager.startInAppPayWithCustomSheet(makeCustomSheetPaymentInfo(), transactionListener);
        } catch (NullPointerException e) {
            Toast.makeText(this, "All mandatory fields cannot be null.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Toast.makeText(this, "IllegalStateException", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (NumberFormatException e) {
            Toast.makeText(this, "Amount values is not valid", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            Toast.makeText(this, "PaymentInfo values not valid or all mandatory fields not set.",
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    /*
     * TransactionInfoListener is for listening to callback events of online (in-app) payments.
     * This is invoked when card or address is changed by the user on the payment sheet,
     * and also with the success or failure of online (in-app) payment.
     */
    private final PaymentManager.CustomSheetTransactionInfoListener transactionListener
            = new PaymentManager.CustomSheetTransactionInfoListener() {
        // This callback is received when the user changes card on the custom payment sheet in Samsung Pay
        @Override
        public void onCardInfoUpdated(CardInfo selectedCardInfo, CustomSheet customSheet) {
            double amount = Double.parseDouble(data.getFields().get(FieldName.OrderAmount));
            /*
             * Called when the user changes card in Samsung Pay.
             * Newly selected cardInfo is passed so merchant app can update transaction amount
             * based on different card (if needed),
             */
            try {
                AmountBoxControl amountBoxControl = (AmountBoxControl) customSheet.getSheetControl(AMOUNT_CONTROL_ID);
                amountBoxControl.updateValue(PRODUCT_ITEM_ID, amount); //item price
                amountBoxControl.updateValue(PRODUCT_TAX_ID, 0); // sales tax
                amountBoxControl.updateValue(PRODUCT_SHIPPING_ID, 0); // Shipping fee
                amountBoxControl.updateValue(PRODUCT_FUEL_ID, 0, "Pending"); // additional item status
                amountBoxControl.setAmountTotal(amount, AmountConstants.FORMAT_TOTAL_PRICE_ONLY); // grand total
                customSheet.updateControl(amountBoxControl);
                // Call updateAmount() method. This is mandatory.
                paymentManager.updateSheet(customSheet);
            } catch (IllegalStateException | NullPointerException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onSuccess(CustomSheetPaymentInfo response, String paymentCredential, Bundle extraPaymentData) {
            payToken(paymentCredential, PaymentTokenType.SAMSUNG_PAY);
        }

        @Override
        public void onFailure(int errorCode, Bundle errorData) {
            Toast.makeText(ConfirmationActivity.this, "Transaction : onFailure : " + errorCode,
                            Toast.LENGTH_LONG).show();
        }
    };

    private CustomSheetPaymentInfo makeCustomSheetPaymentInfo() {
        ArrayList<SpaySdk.Brand> brandList = new ArrayList<>();
        // If the supported brand is not specified, all card brands in Samsung Pay are
        // listed in the Payment Sheet.
        brandList.add(SpaySdk.Brand.VISA);
        brandList.add(SpaySdk.Brand.MASTERCARD);
        /*
         * Make the SheetControls you want and add them to custom sheet.
         * Place each control in sequence with AmountBoxControl listed last.
         */
        CustomSheet customSheet = new CustomSheet();
        AmountBoxControl amountBoxControl
                = new AmountBoxControl(AMOUNT_CONTROL_ID, data.getFields().get(FieldName.OrderCurrency));

        double amount = Double.parseDouble(data.getFields().get(FieldName.OrderAmount));

        amountBoxControl.addItem(PRODUCT_ITEM_ID, "Item", amount, ""); //item price
        amountBoxControl.addItem(PRODUCT_TAX_ID, "Tax", 0, ""); // sales tax
        amountBoxControl.addItem(PRODUCT_SHIPPING_ID, "Shipping", 0, ""); // Shipping fee
        amountBoxControl.addItem(PRODUCT_FUEL_ID, "Fuel", 0, ""); // additional item status
        amountBoxControl.setAmountTotal(amount, AmountConstants.FORMAT_TOTAL_PRICE_ONLY); // grand total
        customSheet.addControl(amountBoxControl);
        String merchantId = data.getMerchantID();
        return new CustomSheetPaymentInfo.Builder()
                .setMerchantId(merchantId)
                .setMerchantName("Sample Merchant")
                .setOrderNumber(data.getFields().get(FieldName.OrderNumber))
                .setPaymentProtocol(CustomSheetPaymentInfo.PaymentProtocol.PROTOCOL_3DS)
                .setAddressInPaymentSheet(CustomSheetPaymentInfo.AddressInPaymentSheet.DO_NOT_SHOW)
                .setAllowedCardBrands(brandList)
                .setCardHolderNameEnabled(true)
                .setRecurringEnabled(false)
                .setCustomSheet(customSheet)
                .build();
    }
}


text:
configuration = {
    isAppInProductionMode: function () {
        return false;
    },
    getAppName: function () {
        var strPath = window.location.pathname;
        return strPath.substr(1, strPath.substr(1, strPath.length).indexOf('/'));
    },
    getAppClientUrl: function () {
        return location.protocol + '//' + location.hostname + ':' + location.port + '/' + this.getAppName();
    },
    getAppUrl: function () {
        return location.protocol + '//' + location.hostname + ':' + location.port + '/' + this.getAppName() + '/json';
    },
    resetCSS: function () {
        $('link[rel="stylesheet"]').each(function () {
            this.remove();
        })
        $('<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>').appendTo("head");
        $('<link href="vendor/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css"/>').appendTo("head");
        $('<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>').appendTo("head");
        $('<link href="http://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css"/>').appendTo("head");
        $('<link href="http://fonts.googleapis.com/css?family=Questrial" rel="stylesheet" type="text/css"/>').appendTo("head");
//        $('<link href="css/main/main.css" rel="stylesheet" type="text/css"/>').appendTo("head");
        $('<link href="css/main/main.css" rel="stylesheet" type="text/css"/>').appendTo("head");
        $('<link href="css/main/style.css" rel="stylesheet" type="text/css"/>').appendTo("head");

    }
}


text:
/* Commentary:
 *
 */

/* Change log:
 *
 */

#ifndef DTKCOMPOSERMETATYPE_H
#define DTKCOMPOSERMETATYPE_H

#include <QtCore>
#include <QImage>

// /////////////////////////////////////////////////////////////////
//
// /////////////////////////////////////////////////////////////////

Q_DECLARE_METATYPE(bool *);

Q_DECLARE_METATYPE(int *);
Q_DECLARE_METATYPE(uint *);

Q_DECLARE_METATYPE(qlonglong *);
Q_DECLARE_METATYPE(qulonglong *);

Q_DECLARE_METATYPE(qreal *);
Q_DECLARE_METATYPE(double **)

Q_DECLARE_METATYPE(QString *);

Q_DECLARE_METATYPE(QImage *);

//Q_DECLARE_METATYPE(QStringList*);
Q_DECLARE_METATYPE(QByteArray *);

#endif


text:
var repl = require('repl');

repl.start('>>> ').context.sayHello = function () {
  return 'Hello';
};


text:
import { beforeEach, describe, it } from 'mocha'
import { expect } from 'chai'
import { promisify } from 'bluebird'
import fs from 'mz/fs'
import path from 'path'
import ProfileLoader from './profile_loader'
import tmp from 'tmp'

describe('ProfileLoader', () => {
  describe('getArgv', () => {
    beforeEach(async function() {
      this.tmpDir = await promisify(tmp.dir)({ unsafeCleanup: true })
      this.profileLoader = new ProfileLoader(this.tmpDir)
    })

    describe('with no identifiers', () => {
      describe('no definition file', () => {
        it('returns an empty array', async function() {
          const result = await this.profileLoader.getArgv([])
          expect(result).to.eql([])
        })
      })

      describe('with definition file', () => {
        describe('with a default', () => {
          beforeEach(async function() {
            const fileContent = 'module.exports = {default: "--opt1 --opt2"}'
            await fs.writeFile(
              path.join(this.tmpDir, 'cucumber.js'),
              fileContent
            )
          })

          it('returns the argv for the default profile', async function() {
            const result = await this.profileLoader.getArgv([])
            expect(result).to.eql(['--opt1', '--opt2'])
          })
        })

        describe('without a default', () => {
          beforeEach(async function() {
            const fileContent = 'module.exports = {profile1: "--opt1 --opt2"}'
            await fs.writeFile(
              path.join(this.tmpDir, 'cucumber.js'),
              fileContent
            )
          })

          it('returns an empty array', async function() {
            const result = await this.profileLoader.getArgv([])
            expect(result).to.eql([])
          })
        })
      })
    })

    describe('with identifiers', () => {
      describe('no definition file', () => {
        it('throws', async function() {
          let thrown = false
          try {
            await this.profileLoader.getArgv(['profile1'])
          } catch (error) {
            thrown = true
            expect(error.message).to.eql('Undefined profile: profile1')
          }
          expect(thrown).to.eql(true)
        })
      })

      describe('with definition file', () => {
        beforeEach(async function() {
          const fileContent =
            'module.exports = {\n' +
            '  profile1: "--opt1 --opt2",\n' +
            '  profile2: "--opt3 \'some value\'"\n' +
            '}'
          await fs.writeFile(path.join(this.tmpDir, 'cucumber.js'), fileContent)
        })

        describe('profile is defined', () => {
          it('returns the argv for the given profile', async function() {
            const result = await this.profileLoader.getArgv(['profile1'])
            expect(result).to.eql(['--opt1', '--opt2'])
          })
        })

        describe('profile is defined and contains quoted string', () => {
          it('returns the argv for the given profile', async function() {
            const result = await this.profileLoader.getArgv(['profile2'])
            expect(result).to.eql(['--opt3', 'some value'])
          })
        })

        describe('profile is not defined', () => {
          it('throws', async function() {
            let thrown = false
            try {
              await this.profileLoader.getArgv(['profile3'])
            } catch (error) {
              thrown = true
              expect(error.message).to.eql('Undefined profile: profile3')
            }
            expect(thrown).to.eql(true)
          })
        })
      })
    })
  })
})