text:
"""The compiler that turns topologies into xml network definitions"""

from Core.Item import nodeTypes
from Core.Device import Device
from Core.globals import options, environ, mainWidgets
from PyQt4 import QtCore
import os, re

class Compiler:
    def __init__(self, device_list, filename):
        """
        Create a compile instance with a list of devices and the filename.
        """
        self.warnings = 0
        self.errors = 0

        self.device_list = device_list
        self.filename = filename.replace(".gsav", ".xml")
        self.output = open(self.filename, "w")
        self.log = mainWidgets["log"]

        self.compile_list = {}
        for nodeType in nodeTypes:
            self.compile_list[nodeType] = []
        for device in device_list:
            if isinstance(device, Device):
                self.compile_list[device.device_type].append(device)

    def compile(self):
        """
        Compile the topology into xml.
        """
        if options["autogen"]:
            self.log.append("Auto-generate IP/MAC Addresses is ON.")
        else:
            self.log.append("Auto-generate IP/MAC Addresses is OFF.")
        if options["autorouting"]:
            self.log.append("Auto-routing is ON.")
        else:
            self.log.append("Auto-routing is OFF.")

        self.output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        self.output.write("<!DOCTYPE gloader SYSTEM \"" + os.environ["GINI_SHARE"] + "/gloader/gloader.dtd"+"\">\n")
        self.output.write("<gloader>\n\n")

        if options["autogen"]:
            self.autogen_subnet()
            self.autogen_switch()

        self.compile_subnet()
        self.compile_switch()
        self.switch_pass_mask()

        if options["autogen"]:
            self.autogen_wireless_access_point()
        self.compile_wireless_access_point()

        if options["autogen"]:
            self.autogen_router()
            self.autogen_cloud()
            self.autogen_tunnel()
            self.autogen_UML()
            self.autogen_REALM()
            self.autogen_mobile()

        self.routing_table_clear()
        if options["autorouting"]:
            self.routing_table_router()
            self.routing_table_cloud()
            self.routing_table_tunnel()
            #self.routing_table_wireless_access_point()
            self.routing_table_entry()
            self.routing_table_uml()
            #self.routing_table_mobile()

        self.compile_router()
        self.compile_tunnel()
        self.compile_cloud()
        self.compile_UML()
        self.compile_REALM()
        self.compile_mobile()

        self.output.write("</gloader>\n")
        self.output.close()

        self.log.append("Compile finished with " + str(self.errors) + \
                        " error(s) and " + str(self.warnings) + " warning(s).\n")

        if self.errors:
            os.remove(self.filename)
            return ""

        return self.filename

    def autogen_subnet(self):
        """
        Auto-generate properties for Subnets.
        """
        for subnet in self.compile_list["Subnet"]:
            subnet.setProperty("mask", "255.255.255.0")
            if subnet.getProperty("subnet"):
                continue
            subnet.setProperty("subnet", "192.168.%d.0" % subnet.getID())

    def writeProperty(self, prop, value):
        """
        Write a property and value in xml format to file.
        """
        self.output.write("\t\t<" + prop + ">")
        self.output.write(value)
        self.output.write("</" + prop + ">\n")

    def generateREALMError(self):
        self.errors += 1
        self.log.append("Error: there is more than one REALM")

    def generateError(self, device, prop, errorType, interface = None):
        """
        Generate a compile error.
        """
        self.errors += 1
        message = "Error: " + device.getName() + "'s " + prop
        if not errorType == "missing":
            message += " value"
        if interface:
            message += " of interface " + str(device.getInterfaces().index(interface) + 1)
        message += " is " + errorType + "."
        self.log.append(message)

    def generateConnectionError(self, device, numCons):
        """
        Generate a compile error.
        """
        self.errors += 1
        message = ' '.join(("Error:", device.getName(), "has less than", str(numCons), "connection(s)."))
        self.log.append(message)

    def generateConnectionWarning(self, device, numCons):
        """
        Generate a compile warning.
        """
        self.warnings += 1
        message = ' '.join(("Warning:", device.getName(), "has less than", str(numCons), "connection(s)."))
        self.log.append(message)

    def compile_subnet(self):
        """
        Compile all the Subnets.
        """
        for subnet in self.compile_list["Subnet"]:

            edges = subnet.edges()
            if len(edges) < 1:
                self.generateConnectionWarning(subnet, 1)

            for prop in ["subnet", "mask"]:
                value = subnet.getProperty(prop)
                if not value:
                    self.generateError(subnet, prop, "empty")
                elif not self.validate(prop, value):
                    self.generateError(subnet, prop, "invalid")

            self.pass_mask(subnet)

    def autogen_tunnel(self):
        """
        Auto-generate properties for Routers.
        """
        for router in self.compile_list["Tunnel"]:
            i = 0
            for con in router.edges():
                i += 1
                node = con.getOtherDevice(router)
                node = node.getTarget(router)

                if options["autogen"]:
                    subnet = str(router.getInterfaceProperty("subnet", node)).rsplit(".", 1)[0]
                    router.setInterfaceProperty("ipv4", "%s.%d" % (subnet, 127 + 20-router.getID()), node)
                    router.setInterfaceProperty("mac", "fe:fd:03:%02x:00:%02x" % (20-router.getID(), i), node)

    def compile_tunnel(self):
        """
        Compile all the Routers.
        """
        for router in self.compile_list["Tunnel"]:
            self.output.write("<vr name=\"" + router.getName() + "\">\n")

            edges = router.edges()
            if len(edges) < 2:
                self.generateConnectionWarning(router, 2)

            for con in edges:
                node = con.getOtherDevice(router)
                if(node.device_type=="Subnet"):
                    node = node.getTarget(router)
                if(node.device_type =="Cloud"):
                    type ="\t<loctun>\n"
                    end ="\t</loctun>\n"
                else:
                    type ="\t<netif>\n"
                    end = "\t</netif>\n"

                self.output.write(type)

                interface = router.getInterface(node)
                mapping = {"subnet":"network", "mac":"nic", "ipv4":"ip"}

                self.writeInterface(router, interface, mapping)

                self.output.write(end)
            self.output.write("</vr>\n\n")

    def autogen_cloud(self):
        """
        Auto-generate properties for Routers.
        """
        for router in self.compile_list["Cloud"]:
            i = 0
            for con in router.edges():
                i += 1
                node = con.getOtherDevice(router)
                node = node.getTarget(router)

                if options["autogen"]:
                    subnet = str(router.getInterfaceProperty("subnet", node)).rsplit(".", 1)[0]
                    router.setInterfaceProperty("ipv4", "%s.%d" % (subnet, 127 + 10-router.getID()), node)
                    router.setInterfaceProperty("mac", "fe:fd:03:%02x:00:%02x" % (10-router.getID(), i), node)

    def compile_cloud(self):
        """
        Compile all the Routers.
        """
        for router in self.compile_list["Cloud"]:
            self.output.write("<vr name=\"" + router.getName() + "\">\n")

            edges = router.edges()
            if len(edges) < 2:
                self.generateConnectionWarning(router, 2)

            for con in edges:
                node = con.getOtherDevice(router)
                node = node.getTarget(router)

                self.output.write("\t<clotun>\n")

                interface = router.getInterface(node)
                mapping = {"subnet":"network", "mac":"nic", "ipv4":"ip"}

                self.writeInterface(router, interface, mapping)
                self.output.write("</clotun>\n\n")
            self.output.write("</vr>\n\n")

    def autogen_router(self):
        """
        Auto-generate properties for Routers.
        """
        for router in self.compile_list["Router"]:
            i = 0
            for con in router.edges():
                i += 1
                node = con.getOtherDevice(router)
                node = node.getTarget(router)

                if options["autogen"]:
                    subnet = str(router.getInterfaceProperty("subnet", node)).rsplit(".", 1)[0]
                    router.setInterfaceProperty("ipv4", "%s.%d" % (subnet, 127 + router.getID()), node)
                    router.setInterfaceProperty("mac", "fe:fd:03:%02x:00:%02x" % (router.getID(), i), node)

    def compile_router(self):
        """
        Compile all the Routers.
        """
        for router in self.compile_list["Router"]:
            self.output.write("<vr name=\"" + router.getName() + "\">\n")

            edges = router.edges()
            if len(edges) < 2:
                self.generateConnectionWarning(router, 2)

            for con in edges:
                node = con.getOtherDevice(router)
                node = node.getTarget(router)

                self.output.write("\t<netif>\n")

                interface = router.getInterface(node)
                mapping = {"subnet":"network", "mac":"nic", "ipv4":"ip"}

                self.writeInterface(router, interface, mapping)

                self.output.write("\t</netif>\n")

            self.output.write("</vr>\n\n")

    def autogen_wireless_access_point(self):
        """
        Auto-generate properties for Wireless_access_points.
        """
        for router in self.compile_list["Wireless_access_point"]:
            if options["autogen"]:
                subnet = router.getInterfaceProperty("subnet")
                if not subnet:
                    subnet = "192.168.%d.0" % (256 - router.getID())
                    router.setInterfaceProperty("subnet", subnet)
                subnet = str(subnet).rsplit(".", 1)[0]
                router.setInterfaceProperty("mask", "255.255.255.0")
                router.setInterfaceProperty("ipv4", "%s.%d" % (subnet, router.getID()))
                router.setInterfaceProperty("mac", "fe:fd:01:%02x:00:00" % router.getID())

    def compile_wireless_access_point(self):
        """
        Compile all the Wireless_access_points.
        """
        for router in self.compile_list["Wireless_access_point"]:
            self.output.write("<vwr name=\"" + router.getName() + "\">\n")

            edges = router.edges()
            if len(edges) < 1:
                self.errors += 1
                message = "Error: " + router.getName() + " needs at least one connected Mobile to start."
                self.log.append(message)

            self.output.write("\t<netif_wireless>\n")

            interface = router.getInterface()
            mapping = {"subnet":"network", "mac":"nic", "ipv4":"ip"}

            self.writeInterface(router, interface, mapping)

            #properties=router.getProperties()
            p_types={}
            p_types["wireless_card"]=("w_type", "freq", "bandwidth", "Pt", "Pt_c", "Pr_c", "P_idle", "P_sleep", "P_off", "RX", "CS", "CP", "module")
            p_types["antenna"]=("a_type", "ant_h", "ant_g", "ant_l", "JAM")
            p_types["energy"]=("power", "PSM", "energy_amount")
            p_types["mobility"]=("m_type", "ran_max", "ran_min")
            p_types["mac_layer"]=("mac_type", "trans")

            for item in p_types:
                self.output.write("\t<"+item+">\n")
                for p in p_types[item]:
                    self.output.write("\t\t<"+p+">"+router.getProperty(p)+"</"+p+">\n")
                self.output.write("\t</"+item+">\n")

            self.output.write("\t</netif_wireless>\n")

            self.output.write("</vwr>\n\n")

            subnet = router.getInterfaceProperty("subnet")
            mask = router.getInterfaceProperty("mask")
            for edge in edges:
                target = edge.getOtherDevice(router)
                target.setInterfaceProperty("subnet", subnet, router)
                target.setInterfaceProperty("mask", mask, router)

    def writeInterface(self, device, interface, mapping):
        """
        Write an interface to file according to mapping.
        """
        if interface.has_key(QtCore.QString("target")):
            self.writeProperty("target", interface[QtCore.QString("target")].getName())

        for prop, eq in mapping.iteritems():
            try:
                value = interface[QtCore.QString(prop)]
            except:
                self.generateError(device, prop, "missing", interface)
                return

            if not value:
                self.generateError(device, prop, "empty", interface)
            elif not self.validate(prop, value, interface):
                self.generateError(device, prop, "invalid", interface)
            else:
                self.writeProperty(eq, value)

        table = self.formatRoutes(interface[QtCore.QString("routing")], device.device_type)
        self.output.write(table)

    def autogen_switch(self):
        """
        Auto-generate properties for switches.
        """
        for switch in self.compile_list["Switch"]:
            switch.setProperty("mac", "fe:fd:04:00:00:%02x" % switch.getID())

    def compile_switch(self):
        """
        Compile all the Switches.
        """
        for switch in self.compile_list["Switch"]:
            self.output.write("<vs name=\"" + switch.getName() + "\">\n")

            self.output.write("\t<priority>" + switch.getProperty("Priority") + "</priority>\n")
            self.output.write("\t<mac>" + switch.getProperty("mac") + "</mac>\n")

            subnet = None
            if len(switch.edges()) < 2:
                self.generateConnectionWarning(switch, 2)

            first = True
            Q = [switch]
            switch_seen = set([switch])
            while Q:
                t = Q.pop(0)
                for edge in t.edges():
                    node = edge.getOtherDevice(t)
                    if node.device_type == "Subnet":
                        if (subnet is None) or (subnet == node):
                            subnet = node
                        else:
                            self.generateError(t, "subnet", "inconsistent due to multiple values (only connect to a single subnet)")
                            return
                    if node.device_type == "Switch":
                        # should look around for a subnet
                        if node not in switch_seen:
                            switch_seen.add(node)
                            Q.append(node)
                            if first:
                                self.output.write("\t<target>" + node.getName() + "</target>\n")
                first = False

            if subnet is None:
                self.generateError(switch, "subnet", "missing")
                return

            switch.setProperty("subnet", subnet.getProperty("subnet"))
            if switch.getProperty("Hub mode") == "True":
                self.output.write("\t<hub/>\n")
            self.output.write("</vs>\n\n")
            # self.pass_mask(switch)

    def switch_pass_mask(self):
        for switch in self.compile_list["Switch"]:

          has_subnet = False
          for edge in switch.edges():
              node = edge.getOtherDevice(switch)
              if node.device_type == "Subnet":
                  has_subnet = True

          if has_subnet:
              target = switch.getTarget(None)
              gateway = target.getInterface(switch) if target is not None else None
              Q = [switch]
              switch_seen = set([switch])
              while Q:
                  t = Q.pop(0)
                  t.gateway = gateway
                  self.pass_mask(t)
                  for edge in t.edges():
                      node = edge.getOtherDevice(t)
                      if node.device_type == "Switch":
                          # should look around for a subnet
                          if node not in switch_seen:
                              switch_seen.add(node)
                              Q.append(node)

    def autogen_UML(self):
        """
        Auto-generate properties for UMLs.
        """
        for uml in self.compile_list["UML"]:
            for interface in uml.getInterfaces():
                if options["autogen"]:
                    try:
                        subnet = str(uml.getInterfaceProperty("subnet")).rsplit(".", 1)[0]
                    except:
                        continue
                    uml.setInterfaceProperty("ipv4", "%s.%d" % (subnet, uml.getID()+1))
                    uml.setInterfaceProperty("mac", "fe:fd:02:00:00:%02x" % uml.getID())

    def compile_UML(self):
        """
        Compile all the UMLs.
        """
        for uml in self.compile_list["UML"]:
            self.output.write("<vm name=\"" + uml.getName() + "\">\n")
            self.output.write("\t<filesystem type=\"" + uml.getProperty("filetype") + "\">"
                              + uml.getProperty("filesystem") + "</filesystem>\n")

            interfaces = uml.getInterfaces()
            if len(interfaces) < 1:
                self.generateConnectionWarning(uml, 1)

            for interface in interfaces:

                self.output.write("\t<if>\n")

                mapping = {"subnet":"network", "mac":"mac", "ipv4":"ip"}
                self.writeInterface(uml, interface, mapping)

                self.output.write("\t</if>\n")

            self.output.write("</vm>\n\n")

#********************************* REALM
    def autogen_REALM(self):
        """
        Auto-generate properties for REALMs.
        """
        for realm in self.compile_list["REALM"]:
            for interface in realm.getInterfaces():
                if options["autogen"]:
                    try:
                        subnet = str(realm.getInterfaceProperty("subnet")).rsplit(".", 1)[0]
                    except:
                        continue
                    realm.setInterfaceProperty("ipv4", "%s.%d" % (subnet, realm.getID()+1+len(self.compile_list["UML"])))
                    realm.setInterfaceProperty("mac", "fe:fd:02:00:01:%02x" % realm.getID())

    def compile_REALM(self):
        """
        Compile all the REALMs.
        """
        if len(self.compile_list["REALM"]) > 1:
            self.generateREALMError()
        for realm in self.compile_list["REALM"]:
            self.output.write("<vrm name=\"" + realm.getName() + "\">\n")
            self.output.write("\t<filesystem type=\"" + realm.getProperty("filetype") + "\">"
                          + realm.getProperty("filesystem") + "</filesystem>\n")

            interfaces = realm.getInterfaces()
            if len(interfaces) < 1:
                self.generateConnectionWarning(realm, 1)

            for interface in interfaces:

                self.output.write("\t<if>\n")

                mapping = {"subnet":"network", "mac":"mac", "ipv4":"ip"}
                self.writeInterface(realm, interface, mapping)

                self.output.write("\t</if>\n")

            self.output.write("</vrm>\n\n")
#******************************FINISH REALM

    def autogen_mobile(self):
        """
        Auto-generate properties for Mobiles.
        """
        for uml in self.compile_list["Mobile"]:
            for interface in uml.getInterfaces():
                if options["autogen"]:
                    subnet = str(uml.getInterfaceProperty("subnet")).rsplit(".", 1)[0]
                    uml.setInterfaceProperty("ipv4", "%s.%d" % (subnet, uml.getID()+1))
                    uml.setInterfaceProperty("mac", "fe:fd:00:00:00:%02x" % uml.getID())

    def compile_mobile(self):
        """
        Compile all the Mobiles.
        """
        for uml in self.compile_list["Mobile"]:
            self.output.write("<vmb name=\"" + uml.getName() + "\">\n")
            self.output.write("\t<filesystem type=\"" + uml.getProperty("filetype") + "\">"
                              + uml.getProperty("filesystem") + "</filesystem>\n")

            interfaces = uml.getInterfaces()
            if len(interfaces) < 1:
                self.generateConnectionWarning(uml, 1)

            for interface in interfaces:

                self.output.write("\t<if>\n")

                mapping = {"subnet":"network", "mac":"mac", "ipv4":"ip"}
                self.writeInterface(uml, interface, mapping)

                self.output.write("\t</if>\n")

            self.output.write("</vmb>\n\n")

    def pass_mask(self, node):
        """
        Pass the mask between connected devices.
        """
        try:
            subnet = node.getProperty("subnet")
        except:
            self.generateError(node, "subnet", "missing")
            return

        try:
            mask = node.getProperty("mask")
        except:
            self.generateError(node, "mask", "missing")
            return

        for con in node.edges():
            otherDevice = con.getOtherDevice(node)
            if otherDevice.device_type in ["Router", "UML", "REALM", "Mobile","Cloud","Tunnel"]:
                target = node
                if node.device_type == "Subnet":
                    target = node.getTarget(otherDevice)
                    if target is None:
                        continue
                otherDevice.setInterfaceProperty("subnet", subnet, target)
                otherDevice.setInterfaceProperty("mask", mask, target)
            else:
                otherDevice.setProperty("subnet", subnet)
                otherDevice.setProperty("mask", mask)

    def routing_table_clear(self):
        """
        Clear all route tables of interfaceable devices.
        """
        for interfaceable in self.compile_list["Router"]:
            interfaceable.emptyAdjacentLists()
            interfaceable.emptyRouteTable()

        for interfaceable in self.compile_list["UML"]:
            interfaceable.emptyAdjacentLists()
            interfaceable.emptyRouteTable()

        for interfaceable in self.compile_list["REALM"]:
            interfaceable.emptyAdjacentLists()
            interfaceable.emptyRouteTable()
        for interfaceable in self.compile_list["Cloud"]:
            interfaceable.emptyAdjacentLists()
            interfaceable.emptyRouteTable()
        for interfaceable in self.compile_list["Tunnel"]:
            interfaceable.emptyAdjacentLists()
            interfaceable.emptyRouteTable()

    def routing_table_interfaceable(self, devType):
        """
        Compute route tables of devices of type devType.
        """
        for interfaceable in self.compile_list[devType]:
            interfaceable.emptyAdjacentLists()
            interfaceable.emptyRouteTable()
            self.findAdjacentRouters(interfaceable)
            self.findAdjacentSubnets(interfaceable)
    def routing_table_uml(self):
        """
        Compute route tables of UMLs.
        """
        self.routing_table_interfaceable("UML")

        for uml in self.compile_list["UML"]:
            for subnet in self.compile_list["Subnet"]:
                if not uml.hasSubnet(subnet.getProperty("subnet")):
                    uml.addRoutingEntry(subnet.getProperty("subnet"))

    def routing_table_realm(self):
        """
        Compute route tables of REALMs.
        """
        self.routing_table_interfaceable("REALM")

        for uml in self.compile_list["REALM"]:
            for subnet in self.compile_list["Subnet"]:
                if not uml.hasSubnet(subnet.getProperty("subnet")):
                    uml.addRoutingEntry(subnet.getProperty("subnet"))

    def routing_table_mobile(self):
        """
        Compute route tables of Mobiles.
        """
        self.routing_table_interfaceable("Mobile")

        for uml in self.compile_list["Mobile"]:
            for subnet in self.compile_list["Subnet"]:
                if not uml.hasSubnet(subnet.getProperty("subnet")):
                    uml.addRoutingEntry(subnet.getProperty("subnet"))

    def routing_table_router(self):
        """
        Compute route tables of Routers.
        """
        self.routing_table_interfaceable("Router")

    def routing_table_cloud(self):
        """
        Compute route tables of CRouters.
        """
        self.routing_table_interfaceable("Cloud")

    def routing_table_tunnel(self):
        """
        Compute route tables of Tunnel.
        """
        self.routing_table_interfaceable("Tunnel")

    def routing_table_wireless_access_point(self):
        """
        Compute route tables of Wireless_access_points.
        """
        self.routing_table_interfaceable("Wireless_access_point")

    def routing_table_entry(self):
        """
        Add routing entries for Routers.
        """
        for uml in self.compile_list["Router"]:
            for subnet in self.compile_list["Subnet"]:
                uml.addRoutingEntry(subnet.getProperty("subnet"))

        for uml in self.compile_list["Cloud"]:
            for subnet in self.compile_list["Subnet"]:
                uml.addRoutingEntry(subnet.getProperty("subnet"))

        for uml in self.compile_list["Tunnel"]:
            for subnet in self.compile_list["Subnet"]:
                uml.addRoutingEntry(subnet.getProperty("subnet"))

    def findAdjacentRouters(self, device):
        """
        Find all Routers adjacent to device.
        """
        for interface in device.getInterfaces():
            for con in device.edges():
                otherDevice = con.getOtherDevice(device)
                if otherDevice.device_type == "Subnet":
                    otherDevice = otherDevice.getTarget(device)
                if interface[QtCore.QString("target")] == otherDevice:
                    break

            visitedNodes = []
            self.visitAdjacentRouters(device, con, device, interface, visitedNodes)

    def visitAdjacentRouters(self, myself, con, device, interface, visitedNodes):
        """
        Helper method to find adjacent Routers.
        """
        otherDevice = con.getOtherDevice(device)
        if otherDevice in visitedNodes:
            return

        visitedNodes.append(otherDevice)

        if otherDevice.device_type in ["Router", "Wireless_access_point","Cloud","Tunnel"]:
            myself.addAdjacentRouter(otherDevice, interface)
        elif otherDevice.device_type in ["UML", "Mobile", "REALM"]:
            pass
        else:
            for c in otherDevice.edges():
                if con != c:
                    self.visitAdjacentRouters(myself, c, otherDevice, interface, visitedNodes)

    def findAdjacentSubnets(self, device):
        """
        Find all Subnets adjacent to device.
        """
        for con in device.edges():
            otherDevice = con.getOtherDevice(device)
            if otherDevice.device_type == "Subnet":
                device.addAdjacentSubnet(otherDevice.getProperty("subnet"))
            elif otherDevice.device_type == "Wireless_access_point":
                device.addAdjacentSubnet(otherDevice.getProperty("subnet"))

    def formatRoutes(self, routes, devType):
        """
        Format the routes in xml.
        """
        if devType == "UML" or devType == "REALM":
            header = "\t\t<route type=\"net\" "
            gateway = "\" gw=\""
            footer = "</route>\n"
        else:
            header = "\t\t<rtentry "
            gateway = "\" nexthop=\""
            footer = "</rtentry>\n"

        # Because of gloader's getVMIFOutLine, we must preserve a specific order of the routes
        outstring = ""
        outstring2 = ""
        for route in routes:
            string = ""
            string += header
            string += "netmask=\"" + route[QtCore.QString("netmask")]
            string += gateway
            string += route[QtCore.QString("gw")]
            string += "\">" + route[QtCore.QString("subnet")]
            string += footer

            if route[QtCore.QString("gw")]:
                outstring2 += string
            else:
                outstring += string

        return outstring + outstring2

    def validate(self, prop, value, interface=None):
        """
        Validate a property of a device or interface.
        """
        if prop == "mac":
            return self.valid_mac(value)
        elif prop == "ipv4":
            return self.valid_ip_subnet(value, interface[QtCore.QString("subnet")], interface[QtCore.QString("mask")])
        elif prop == "mask":
            return self.valid_mask(value)
        else:
            return self.valid_ip(value)

    def valid_ip(self, ip):
        """
        Validate an ip-like address (includes mask).
        """
        ip = str(ip)
        if re.match(r'^\d+\.\d+\.\d+\.\d+$', ip) == None:
            return False

        p = re.compile('\d+')
        res = p.findall(ip)

        # Each chunk should be between 0 and 255 inc
        for chunk in res:
            if not int(chunk) in range(256):
                return False
        return True

    def valid_mask(self, mask):
        """
        Validate a subnet mask.
        """
        mask = str(mask)
        if mask == "255.255.255.0":
            return True
        else:
            self.warnings += 1
            message = "Warning: Using a mask other than 255.255.255.0 is not recommended."
            self.log.append(message)

        if not self.valid_ip(mask):
            return False

        # Make sure the chunks match the possible values
        chunks = mask.split(".")
        for chunk in chunks:
            if not int(chunk) in (0, 128, 192, 224, 240, 248, 252, 255):
                return False

        # The last chunk of a mask cannot be 255
        if int(chunks[-1]) == 255:
            return False

        return True

    def valid_ip_subnet(self, ip, subnet, mask):
        """
        Validate an ip address based on the subnet and mask.
        """
        ip = str(ip)
        subnet = str(subnet)
        mask = str(mask)

        if not self.valid_ip(ip):
            return False
        if not self.valid_mask(mask):
            return False

        p=re.compile('\d+')
        ip_chunk=p.findall(ip)
        subnet_chunk=p.findall(subnet)
        mask_chunk=p.findall(mask)

        # Make sure the ip addresses are not reserved
        if ip_chunk[3] == "0" or ip_chunk[3] == "255":
            return False

        # Check each chunk against subnet and mask
        for i in range(len(subnet_chunk)):
            if mask_chunk[i] == "255":
                if ip_chunk[i] != subnet_chunk[i]:
                    return False
            elif mask_chunk[i] == "0":
                if ip_chunk[i] == "0":
                    return False
            else:
                mask_value = int(mask_chunk[i])
                ip_value = int(ip_chunk[i])
                subnet_value = int(subnet_chunk[i])

                if i == 3:
                    ip_range = 254 - mask_value
                    if not ip_value - 1 in range(ip_range):
                        return False
                else:
                    ip_range = 256 - mask_value
                    if not ip_value in range(ip_range):
                        return False
        return True

    def valid_mac(self, mac):
        """
        Validate a mac address.
        """
        mac = str(mac)
        if re.match(r'^[a-f|0-9]{2}:[a-f|0-9]{2}:[a-f|0-9]{2}:[a-f|0-9]{2}:[a-f|0-9]{2}:[a-f|0-9]{2}$', mac) == None:
            return False
        else:
            return True


text:
<bill session="110" type="h" number="3961" updated="2009-01-09T01:08:19-05:00">
	<status><introduced date="1193198400" datetime="2007-10-24"/></status>

	<introduced date="1193198400" datetime="2007-10-24"/>
	<titles>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to provide relief with respect to the children of members of the Armed Forces of the United States who die as a result of service in a combat zone.</title>
	</titles>
	<sponsor id="400270"/>
	<cosponsors>
		<cosponsor id="400080" joined="2008-05-14"/>
		<cosponsor id="400274" joined="2008-09-08"/>
		<cosponsor id="400285" joined="2008-06-09"/>
		<cosponsor id="400638" joined="2008-04-29"/>
		<cosponsor id="412236" joined="2008-07-24"/>
		<cosponsor id="400047" joined="2008-07-15"/>
	</cosponsors>
	<actions>
		<action date="1193198400" datetime="2007-10-24"><text>Sponsor introductory remarks on measure. (CR E2228-2229)</text></action>
		<action date="1193198400" datetime="2007-10-24"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	10/24/2007--Introduced.<br/>Amends the Internal Revenue Code to: (1) increase to $5,000 the maximum dollar amount of the child tax credit for the surviving spouse and children of a member of the Armed Forces who dies while serving in a combat zone; and (2) waive the adjusted gross income limitation applicable to the child tax credit for such military families.
	</summary>
</bill>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

<title>Blog</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="description" content="" />
	<meta name="keywords" content="" />

	<link rel="stylesheet" href="/css/bootstrap.css" />
	<link rel="stylesheet" href="/css/bootstrap-theme.css" />

                        Home

                        Resume

                        Projects

# Hellow rold

                “Try to be a rainbow in someone's cloud.”
 Maya Angelou


text:
package uk.co.probablyfine.jenever;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import uk.co.probablyfine.jenever.download.Package;

import com.google.common.base.Joiner;

public class PackageObjectTest {

	@Test
	public void testCanonicalName() {
		String[] params = new String[]{"foo.bar","baz","1.0"};

		Package p = new Package().setSignature(Joiner.on(":").join(params));
		assertEquals(p.groupId,params[0]);
		assertEquals(p.artifactId,params[1]);
		assertEquals(p.version, params[2]);
		assertEquals(p.toString(),"foo.bar.baz-1.0");
	}

	@Test
	public void testNoVersion() {
		String[] params = new String[]{"foo.bar","baz"};

		Package p = new Package().setSignature(Joiner.on(":").join(params));
		assertEquals(p.groupId,params[0]);
		assertEquals(p.artifactId,params[1]);
		assertEquals(p.version, null);
		assertEquals(p.toString(),"foo.bar.baz");
	}

	@Test
	public void testJustArtifact() {
		String[] params = new String[]{"baz"};

		Package p = new Package().setSignature(Joiner.on(":").join(params));
		assertEquals(p.groupId,null);
		assertEquals(p.artifactId,params[0]);
		assertEquals(p.version, null);
		assertEquals(p.toString(),"baz");
	}

}


text:
#ifndef __WX_PLUGIN_H
#define __WX_PLUGIN_H

// Forward declaration
class wxHtmlAppletWindow;

#include "wx/event.h"

/*--------------------------- Class Definitions ---------------------------*/

/****************************************************************************
REMARKS:
Defines the abstract base class for wxPlugIn objects.
****************************************************************************/
class wxPlugIn : public wxEvtHandler {
private:
    wxHtmlAppletWindow *m_parent;
    DECLARE_ABSTRACT_CLASS(wxPlugIn);

public:
            // Constructor (called during dynamic creation)
            wxPlugIn() { m_parent = NULL; };

            // Psuedo virtual constructor
    virtual bool Create(wxHtmlAppletWindow *parent);

            // Function that actually executes the main plugin code
    virtual void Run(const wxString& cmdLine);

            // Virtual destructor
    virtual ~wxPlugIn();
    };

#endif // __WX_PLUGIN_H


text:
#import <Foundation/Foundation.h>

#import <ComponentKit/CKComponentDeciding.h>

@interface CKComponentConstantApprovingDecider : NSObject <CKComponentDeciding>
@end

@interface CKComponentConstantDenyingDecider : NSObject <CKComponentDeciding>
@end


text:
package traceapp

import (
	"bytes"
	"fmt"
	htmpl "html/template"
	"net/http"
	"net/url"

	"reflect"
	"strconv"
	"strings"

	"sourcegraph.com/sourcegraph/appdash"
	"sourcegraph.com/sourcegraph/appdash/traceapp/tmpl"

	"github.com/gorilla/mux"
)

var (
	// ReloadTemplates is whether to reload html/template templates
	// before each request. It is useful during development.
	ReloadTemplates = true
)

var templates = [][]string{
	{"root.html", "layout.html"},
	{"trace.html", "layout.html"},
	{"traces.html", "layout.html"},
}

// TemplateCommon is data that is passed to (and available to) all templates.
type TemplateCommon struct {
	CurrentRoute string
	CurrentURI   *url.URL
	BaseURL      *url.URL
}

func (a *App) renderTemplate(w http.ResponseWriter, r *http.Request, name string, status int, data interface{}) error {
	a.tmplLock.Lock()
	defer a.tmplLock.Unlock()

	if a.tmpls == nil || ReloadTemplates {
		if err := a.parseHTMLTemplates(templates); err != nil {
			return err
		}
	}

	w.WriteHeader(status)
	if ct := w.Header().Get("content-type"); ct == "" {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
	}
	t := a.tmpls[name]
	if t == nil {
		return fmt.Errorf("Template %s not found", name)
	}

	if data != nil {
		// Set TemplateCommon values.
		baseURL, err := a.URLTo(RootRoute)
		if err != nil {
			return err
		}
		reflect.ValueOf(data).Elem().FieldByName("TemplateCommon").Set(reflect.ValueOf(TemplateCommon{
			CurrentRoute: mux.CurrentRoute(r).GetName(),
			CurrentURI:   r.URL,
			BaseURL:      baseURL,
		}))
	}

	// Write to a buffer to properly catch errors and avoid partial output written to the http.ResponseWriter
	var buf bytes.Buffer
	err := t.Execute(&buf, data)
	if err != nil {
		return err
	}
	_, err = buf.WriteTo(w)
	return err
}

// parseHTMLTemplates parses the HTML templates from their source.
func (a *App) parseHTMLTemplates(sets [][]string) error {
	a.tmpls = map[string]*htmpl.Template{}
	for _, set := range sets {
		t := htmpl.New("")
		t.Funcs(htmpl.FuncMap{
			"urlTo":             a.URLTo,
			"urlToTrace":        a.URLToTrace,
			"itoa":              strconv.Itoa,
			"str":               func(v interface{}) string { return fmt.Sprintf("%s", v) },
			"durationClass":     durationClass,
			"filterAnnotations": filterAnnotations,
			"descendTraces":     func() bool { return false },
		})
		for _, tmp := range set {
			tmplBytes, err := tmpl.Asset(tmp)
			if err != nil {
				return fmt.Errorf("template %v: %s", set, err)
			}
			if _, err := t.Parse(string(tmplBytes)); err != nil {
				return fmt.Errorf("template %v: %s", set, err)
			}
		}
		t = t.Lookup("ROOT")
		if t == nil {
			return fmt.Errorf("ROOT template not found in %v", set)
		}
		a.tmpls[set[0]] = t
	}
	return nil
}

func durationClass(usec int64) string {
	msec := usec / 1000
	if msec < 30 {
		return "d0"
	} else if msec < 60 {
		return "d1"
	} else if msec < 90 {
		return "d2"
	} else if msec < 150 {
		return "d3"
	} else if msec < 250 {
		return "d4"
	} else if msec < 400 {
		return "d5"
	} else if msec < 600 {
		return "d6"
	} else if msec < 900 {
		return "d7"
	} else if msec < 1300 {
		return "d8"
	} else if msec < 1900 {
		return "d9"
	}
	return "d10"
}

func filterAnnotations(anns appdash.Annotations) appdash.Annotations {
	var anns2 appdash.Annotations
	for _, ann := range anns {
		if ann.Key != "" && !strings.HasPrefix(ann.Key, "_") {
			anns2 = append(anns2, ann)
		}
	}
	return anns2

}


text:
require "test_helper"

describe Blog do
  let(:user) {
    User.petergate(roles: [:root_admin, :company_admin], multiple: false)
    User.create(email: "company_admin2@example.com", password: "password1", password_confirmation: "password1", role: :company_admin)
  }

  it "must be valid" do
    user.must_be :valid?
  end
end


text:
from __future__ import with_statement

from robot.model import Statistics
from robot.reporting.outputwriter import OutputWriter

from .executionerrors import ExecutionErrors
from .configurer import SuiteConfigurer
from .testsuite import TestSuite

class Result(object):
    """Contains results of test execution.

    :ivar source: Path to the xml file where results are read from.
    :ivar suite: Hierarchical :class:`~.testsuite.TestSuite` results.
    :ivar errors: Execution :class:`~.executionerrors.ExecutionErrors`.
    """

    def __init__(self, source=None, root_suite=None, errors=None):
        self.source = source
        self.suite = root_suite or TestSuite()
        self.errors = errors or ExecutionErrors()
        self.generator = None
        self._status_rc = True
        self._stat_config = {}

    @property
    def statistics(self):
        """Test execution :class:`~robot.model.statistics.Statistics`."""
        return Statistics(self.suite, **self._stat_config)

    @property
    def return_code(self):
        """Return code (integer) of test execution."""
        if self._status_rc:
            return min(self.suite.statistics.critical.failed, 250)
        return 0

    def configure(self, status_rc=True, suite_config={}, stat_config={}):
        SuiteConfigurer(**suite_config).configure(self.suite)
        self._status_rc = status_rc
        self._stat_config = stat_config

    def visit(self, visitor):
        visitor.visit_result(self)

    def save(self, path=None):
        self.visit(OutputWriter(path or self.source))

class CombinedResult(Result):

    def __init__(self, *others):
        Result.__init__(self)
        for other in others:
            self.add_result(other)

    def add_result(self, other):
        self.suite.suites.append(other.suite)
        self.errors.add(other.errors)


text:
<?php

namespace NRTest\PetClinicBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class OwnerType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName')
            ->add('address')
            ->add('city')
            ->add('telephone')
            ->add('createdAt')
            ->add('updatedAt')
        ;
    }

    public function getName()
    {
        return 'nrtest_petclinicbundle_ownertype';
    }
}


text:
module PdfTempura
  module Render
    class FieldDataMapper

      def self.map(fields, data)
        data ||= {}

        fields.each_with_object({}){ |field, memo|
          memo[field] = data[field.name]
        }
      end

    end
  end
end


text:
<?php
/**
 * @author Tomáš Blatný
 */

namespace Tempeus\Model;

/**
 * @property-read int $id
 * @property Game $game m:hasOne
 * @property string $title
 * @property string $slug
 * @property string $content
 * @property int $order
 * @property bool $active
 */
class Information extends BaseEntity
{

}


text:
package net.oscartech.tesseract.node.log;

/**
 * It might be a memory one, also might be a file.
 * Created by tylaar on 15/5/17.
 */
public interface LogSegment {

    long id();

    long index();

    long timestamp();
}


text:
<?php

namespace branchonline\eventtracker;

use ReflectionClass;
use Yii;
use yii\base\Object;

abstract class BaseStateKeys extends Object {

    /**
     * Request the available state keys of this object.
     *
     * State key constants need to be prefixed with 'SK_' and should map a name to an integer. The function uses
     * caching if possible to speed up types lookup.
     *
     * @return array The available state keys of this object.
     */
    final public static function keys(): array {
        $cache_available = isset(Yii::$app->cache);
        $types = $cache_available ? Yii::$app->cache->get('tracking.state_keys') : false;
        if (false === $types) {
            $refl_class = new ReflectionClass(static::className());
            $types = $refl_class->getConstants();
            foreach ($types as $name => $value) {
                if (strrpos($name, 'SK_', -strlen($name)) === false) {
                    unset($types[$name]);
                }
            }
        }
        if ($cache_available) {
            Yii::$app->cache->set('tracking.state_keys', $types);
        }
        return $types;
    }

}


text:
import * as Qlik from 'qlik';

// Extension API Test
() => {
    const definition: Qlik.Definition = {
        type: 'items',
        component: 'accordion',
        items: {
            dimensions: {
                uses: 'dimensions',
                min: 1,
                ref: "qHyperCubeDef.qDimensions",
                items: {
                    isGrouping: {
                        type: 'boolean',
                        ref: 'qDef.isGrouping',
                        label: 'Is Grouping',
                        defaultValue: false,
                    },
                },
            },
            measures: {
                uses: 'measures',
                ref: "qHyperCubeDef.qMeasures",
                min: 0,
            },
        }
    };

    const initialProperties: Qlik.InitialProperties = {
        qHyperCubeDef: {
            qDimensions: [],
            qMeasures: [],
            qInitialDataFetch: [{
                qWidth: 10,
                qHeight: 100,
            }],
        },
    };

    function paint(this: Qlik.ExtensionContext, $element: JQuery, layout: Qlik.Layout) {
        const dataRow = this.backendApi.getDataRow(0);
        if (dataRow) {
            $element.html(dataRow[0].qText);
        }
    }

    const e: Qlik.Extension = {
        definition,
        initialProperties,
        paint,
    };
};


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols

Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator

    Friend NotInheritable Class LocalDeclarationRewriter

        Friend Shared Function Rewrite(compilation As VisualBasicCompilation, container As EENamedTypeSymbol, block As BoundBlock) As BoundBlock
            Dim locals = PooledHashSet(Of LocalSymbol).GetInstance()
            Dim walker As New LocalDeclarationWalker(locals)
            walker.Visit(block)

            If locals.Count > 0 Then
                Dim syntax = block.Syntax
                Dim builder = ArrayBuilder(Of BoundStatement).GetInstance()
                For Each local In locals
                    builder.Add(GenerateCreateVariableStatement(compilation, container, syntax, local))
                Next
                builder.AddRange(block.Statements)
                block = New BoundBlock(syntax, block.StatementListSyntax, block.Locals, builder.ToImmutableAndFree())
            End If

            locals.Free()
            Return block
        End Function

        ' Find all implicitly declared locals.
        Private NotInheritable Class LocalDeclarationWalker
            Inherits BoundTreeWalker

            Private ReadOnly _locals As HashSet(Of LocalSymbol)

            Friend Sub New(locals As HashSet(Of LocalSymbol))
                _locals = locals
            End Sub

            Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
                Dim local = node.LocalSymbol
                If local.DeclarationKind = LocalDeclarationKind.ImplicitVariable Then
                    _locals.Add(local)
                End If
                Return node
            End Function

        End Class

        Private Shared Function GenerateCreateVariableStatement(
            compilation As VisualBasicCompilation,
            container As EENamedTypeSymbol,
            syntax As VisualBasicSyntaxNode,
            local As LocalSymbol) As BoundStatement

            Dim typeType = compilation.GetWellKnownType(WellKnownType.System_Type)
            Dim stringType = compilation.GetSpecialType(SpecialType.System_String)

            ' CreateVariable(type As Type, name As String)
            Dim method = PlaceholderLocalSymbol.GetIntrinsicMethod(compilation, ExpressionCompilerConstants.CreateVariableMethodName)
            Dim type = New BoundGetType(syntax, New BoundTypeExpression(syntax, local.Type), typeType)
            Dim name = New BoundLiteral(syntax, ConstantValue.Create(local.Name), stringType)
            Dim expr = New BoundCall(
                syntax,
                method,
                methodGroupOpt:=Nothing,
                receiverOpt:=Nothing,
                arguments:=ImmutableArray.Create(Of BoundExpression)(type, name),
                constantValueOpt:=Nothing,
                suppressObjectClone:=False,
                type:=method.ReturnType)
            Return New BoundExpressionStatement(syntax, expr).MakeCompilerGenerated()
        End Function

    End Class

End Namespace


text:
<?php

declare(strict_types=1);

namespace Slimkit\PlusAppversion\Providers;

use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Support\ServiceProvider;
use Zhiyi\Plus\Support\BootstrapAPIsEventer;
use Zhiyi\Plus\Support\ManageRepository;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the service provider.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadRoutesFrom(
            $this->app->make('path.plus-appversion').'/router.php'
        );
        $this->app->make(BootstrapAPIsEventer::class)->listen('v2', function () {
            return [
                'plus-appversion' => [
                    'open' => (bool) $this->app->make(ConfigRepository::class)->get('plus-appversion.open'),
                ],
            ];
        });
    }

    /**
     * Regoster the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Publish admin menu.
        $this->app->make(ManageRepository::class)->loadManageFrom('App版本控制', 'plus-appversion:admin-home', [
            'route' => true,
            'icon' => '版',
        ]);
    }
}


text:
Annotation triggered connectivity checking for Android - powered by Java's Aspect Oriented Programming Framework, AspectJ

Aren't you tired of doing this all over your code?

```java
if(connectivityUtil.isConnected(context))
{
    //do something
}
else
{
   Toast.makeText(context, "Internet unavailable", LENGTH_SHORT).show();
}

```
With Flender connectivity checking couldn't be easier. Just annoate your method with `@InternetRequired` and Flender does the rest. A toast will be shown if there's no internet available and the method won't execute.

```java
@InternetRequired
public void doSomething()
{
    Log.v("Flender", "this plugin rocks");
}

```

Download
--------

```groovy
buildscript {
  repositories {
    mavenCentral()
  }

  dependencies {
    classpath 'com.github.jd-alexander:flender-plugin:1.0'
  }
}

apply plugin: 'com.android.application'
apply plugin: 'flender'
```

Usage
-----
For connectivity checking to work Flender needs access to the current context so set it like this :          `Flender.init(this);` preferably in your application class or base activity. Once that's done, annotate away!.

```java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Flender.init(this);
        test();
    }

    @InternetRequired
    public void test()
    {
        Log.v("Flender","Only logs if internet is available");
    }
}
```

You can also check for WiFi and Mobile connectivity with these annotations
```java
@WiFiRequired

@MobileRequired
```

If for some reason you don't want toast to be shown eg. using Flender in a service class then simply pass silent as a parameter to the respective annotation
```java
@WiFiRequired("Silent")

@InternetRequired("Silent")
```

If you want to trigger custom actions based on the annotation being used you can use one of the listeners associated each annotation.

```java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Flender.init(this);
        Flender.setInternetUnavailable(new InternetUnavailable() {
            @Override
            public void flenderEvent() {
                materialDialog.show();
            }
        });
        test();
    }

    @InternetRequired
    public void test()
    {
    }
```
Once these listeners are used toasts,won't be triggered.

Contribution
------------

Please fork repository and contribute using pull requests.

Any contributions, large or small, major features, bug fixes, additional language translations, unit/integration tests are welcomed and appreciated but will be thoroughly reviewed and discussed.

License
--------

    Copyright 2016 Joel Dean

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
using System.Security.Principal;

namespace JoergIsAGeek.Workshop.Enterprise.DataAccessLayer
{
  public interface IUserContextProvider
  {
    IIdentity UserIdentity { get; }
  }
}


text:
static void tests(void)
{
    CFErrorRef error = NULL;
    CFStringRef password = NULL;
    CFMutableArrayRef requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFMutableDictionaryRef passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFCharacterSetRef uppercaseLetterCharacterSet = CFCharacterSetGetPredefined(kCFCharacterSetUppercaseLetter);
    CFCharacterSetRef lowercaseLetterCharacterSet = CFCharacterSetGetPredefined(kCFCharacterSetLowercaseLetter);
    CFCharacterSetRef decimalDigitCharacterSet = CFCharacterSetGetPredefined(kCFCharacterSetDecimalDigit);

    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordDefaultForType, CFSTR("true"));

    //test default PIN
    password = SecPasswordGenerate(kSecPasswordTypePIN, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);
    CFReleaseNull(password);
    error = NULL;

    //test default icloud recovery code
    password = SecPasswordGenerate(kSecPasswordTypeiCloudRecovery, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);
    CFReleaseNull(password);
    error = NULL;

    //test default wifi
    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordDefaultForType, CFSTR("true"));
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);
    CFReleaseNull(password);
    error = NULL;
    CFRelease(passwordRequirements);

    //test default safari
    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordDefaultForType, CFSTR("true"));
    password = SecPasswordGenerate(kSecPasswordTypeSafari, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);

    //test icloud recovery code generation
    password = SecPasswordGenerate(kSecPasswordTypeiCloudRecovery, &error, NULL);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);

    //dictionary setup
    int min = 20;
    int max = 32;

    CFNumberRef minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    CFNumberRef maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    CFStringRef allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);

    //test wifi code generation
    //test with min/max in range of default
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //test with max == min
    min = 24;
    max = 24;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    passwordRequirements = NULL;

    //test disallowed characters
    min = 24;
    max = 56;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdefghijklmnopqrstuvwxyz0123456789");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordDisallowedCharacters, CFSTR("aidfl"));

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    passwordRequirements = NULL;

    //test can't start with characters
    min = 24;
    max = 56;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("diujk");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordCantStartWithChars, CFSTR("d"));

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    passwordRequirements = NULL;

    //test can't end with characters
    min = 24;
    max = 56;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("diujk89");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordCantEndWithChars, CFSTR("d"));

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    passwordRequirements = NULL;

    //test 4 digit pin generation
    for(int i =0 ; i< 100; i++){
        password = SecPasswordGenerate(kSecPasswordTypePIN, &error, passwordRequirements);
        isnt(password, NULL);
        ok(error == NULL);

        error = NULL;
        CFReleaseNull(password);
    }

    //test 6 digit pin
    min = 4;
    max = 6;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    password = SecPasswordGenerate(kSecPasswordTypePIN, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(passwordRequirements);

    //test 5 digit pin
    min = 4;
    max = 5;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    password = SecPasswordGenerate(kSecPasswordTypePIN, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(passwordRequirements);
    //test safari password
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);

    password = SecPasswordGenerate(kSecPasswordTypeSafari, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(requiredCharacterSets);

    //test flexible group size and number of groups in the password
    //test safari password
    min = 12;
    max = 19;
    int groupSize = 5;
    int numberOfGroups = 23;

    CFTypeRef groupSizeRef = CFNumberCreate(NULL, kCFNumberIntType, &groupSize);
    CFTypeRef numberOfGroupsRef = CFNumberCreate(NULL, kCFNumberIntType, &numberOfGroups);

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordGroupSize, groupSizeRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordNumberOfGroups, numberOfGroupsRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordSeparator, CFSTR("*"));

    password = SecPasswordGenerate(kSecPasswordTypeSafari, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(requiredCharacterSets);

    //test at least N characters
    //test safari password
    min = 24;
    max = 32;
    int N = 5;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);
    CFNumberRef threshold = CFNumberCreate(NULL, kCFNumberIntType, &N);

    CFStringRef characters = CFSTR("ab");
    CFMutableDictionaryRef atLeast = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(atLeast, kSecPasswordCharacters, characters);
    CFDictionaryAddValue(atLeast, kSecPasswordCharacterCount, threshold);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordContainsAtLeastNSpecificCharacters, atLeast);

    password = SecPasswordGenerate(kSecPasswordTypeSafari, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(requiredCharacterSets);

    //test no More than N characters
    //test safari password
    min = 24;
    max = 32;
    N = 5;

    threshold = CFNumberCreate(NULL, kCFNumberIntType, &N);
    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    CFMutableDictionaryRef noMoreThan = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFStringRef noMore = CFSTR("ab");
    CFDictionaryAddValue(noMoreThan, kSecPasswordCharacters, noMore);
    CFDictionaryAddValue(noMoreThan, kSecPasswordCharacterCount, threshold);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordContainsNoMoreThanNSpecificCharacters, noMoreThan);

    password = SecPasswordGenerate(kSecPasswordTypeSafari, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(requiredCharacterSets);

    //test identical character threshold
    //test safari password
    min = 12;
    max = 19;
    N = 2;

    threshold = CFNumberCreate(NULL, kCFNumberIntType, &N);
    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordContainsNoMoreThanNConsecutiveIdenticalCharacters, threshold);

    password = SecPasswordGenerate(kSecPasswordTypeSafari, &error, passwordRequirements);
    isnt(password, NULL);
    ok(error == NULL);

    error = NULL;
    CFReleaseNull(password);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(requiredCharacterSets);

/////////////////now test all the error cases
    //test with no required characters

    min = 24;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);
    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    CFRelease(error);
    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(passwordRequirements);

    //test with no allowed characters
    min = 24;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    CFRelease(error);
    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(passwordRequirements);

    //test with min > max
    min = 32;
    max = 20;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(passwordRequirements);

    //test by ommitting dictionary parameters

    //omit max length
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(passwordRequirements);

    //omit min length
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(passwordRequirements);

    //omit allowed characters
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(passwordRequirements);

    //omit required characters
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);
    CFRelease(passwordRequirements);

    //pass in wrong type for min
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong type for max
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, allowedCharacters);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong type for allowed
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong type for required
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, minRef);
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong type for no less than
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordContainsAtLeastNSpecificCharacters, CFSTR("hehe"));
    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong type for no more than
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordContainsNoMoreThanNSpecificCharacters, CFSTR("hehe"));

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong disallowed characters
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordDisallowedCharacters, requiredCharacterSets);

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    //pass in wrong type for no more than's dictionary
    min = 20;
    max = 32;

    minRef = CFNumberCreate(NULL, kCFNumberIntType, &min);
    maxRef = CFNumberCreate(NULL, kCFNumberIntType, &max);

    CFMutableDictionaryRef wrongCount = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(wrongCount, kSecPasswordCharacters, CFSTR("lkj"));
    CFDictionaryAddValue(wrongCount, kSecPasswordCharacterCount, CFSTR("sdf"));

    passwordRequirements = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    requiredCharacterSets = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(requiredCharacterSets, uppercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, lowercaseLetterCharacterSet);
    CFArrayAppendValue(requiredCharacterSets, decimalDigitCharacterSet);

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, requiredCharacterSets);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMinLengthKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordMaxLengthKey, maxRef);
    allowedCharacters = CFSTR("abcdsefw2345");

    CFDictionaryAddValue(passwordRequirements, kSecPasswordAllowedCharactersKey, allowedCharacters);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordRequiredCharactersKey, minRef);
    CFDictionaryAddValue(passwordRequirements, kSecPasswordContainsNoMoreThanNSpecificCharacters, wrongCount);

    password = SecPasswordGenerate(kSecPasswordTypeWifi, &error, passwordRequirements);
    ok(password == NULL);
    ok(error != NULL);

    error = NULL;
    CFRelease(wrongCount);
    CFRelease(passwordRequirements);
    CFRelease(minRef);
    CFRelease(maxRef);
    CFRelease(allowedCharacters);

    password = CFSTR("Apple1?");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("Singhal190");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("1Hollow2");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("1Hollow/");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("baj/paj1");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("Zaxs1009?");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("6666");
    isnt(false, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("123456");
    isnt(false, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("654321");
    isnt(false, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("A");
    isnt(false, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("password");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("password1");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("P@ssw0rd");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("facebook!{}");
    isnt(true, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    password = CFSTR("12345678");
    isnt(false, SecPasswordIsPasswordWeak(password));
    CFRelease(password);

    bool isSimple = false;

    password = CFSTR("Apple1?");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("Singhal190");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("1Hollow2");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("1Hollow/");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("baj/paj1");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("Zaxs1009?");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("6666");
    is(true, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("1235");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    isSimple = true;
    password = CFSTR("6666");
    is(true, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("1235");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    isSimple = false;
    password = CFSTR("123456");
    is(true, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("654321");
    is(true, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("1577326");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("A");
    is(true, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("password");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("password1");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("P@ssw0rd");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("facebook!{}");
    is(false, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

    password = CFSTR("12345678");
    is(true, SecPasswordIsPasswordWeak2(isSimple, password));
    CFRelease(password);

}

int si_73_secpasswordgenerate(int argc, char *const *argv)
{
	plan_tests(298);
	tests();

	return 0;
}


text:
using System;
using System.Reflection;

namespace NuGet.Lucene.Web
{
    internal class SimpleParameterInfo<T> : ParameterInfo
    {
        private readonly string name;
        private readonly T defaultValue;
        private readonly bool hasDefault;
        private readonly ParameterAttributes attributes;

        public SimpleParameterInfo(string name)
        {
            this.name = name;
            this.defaultValue = default(T);
            this.hasDefault = false;
            this.attributes = ParameterAttributes.None;
        }

        public SimpleParameterInfo(string name, T defaultValue)
        {
            this.name = name;
            this.defaultValue = defaultValue;
            this.hasDefault = true;
            this.attributes = ParameterAttributes.Optional;
        }

        public override ParameterAttributes Attributes
        {
            get { return attributes; }
        }

        public override bool HasDefaultValue { get { return hasDefault; } }

        public override object DefaultValue
        {
            get
            {
                return defaultValue;
            }
        }

        public override Type ParameterType { get { return typeof(T); } }

        public override string Name { get { return name; } }

        public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
        {
            return (object[])Array.CreateInstance(attributeType, 0);
        }

    }
}


text:
<?php

class CoScale_Monitor_Model_Metric_Observer
{
    public function generate(Varien_Event_Observer $observer)
    {
        $event = $observer->getEvent();

        /** @var CoScale_Monitor_Helper_Data $logger */
        $logger = $event->getLogger();
        /** @var CoScale_Monitor_Model_Output_Generator $output */
        $output = $event->getOutput();

        // Get Metrics Collection
        try {
            $logger->debugStart('Metrics Collection');

            $metricOrderDelete = Mage::getSingleton('coscale_monitor/metric_order');
            $collection = Mage::getModel('coscale_monitor/metric')->getCollection();
            /** @var CoScale_Monitor_Model_Metric $metric */
            foreach ($collection as $metric) {
                $data = array(
                    'name' => $metric->getName(),
                    'unit' => $metric->getUnit(),
                    'value' => (float)$metric->getValue(),
                    'store_id' => (int)$metric->getStoreId(),
                    'type' => $metric->getTypeText()
                );
                if ($code = $metric->getCalculationTypeCode()) {
                    $data['calctype'] = $code;
                }
                $output->addMetric($data);

                // Check if metric need to be reset after collection
                if ($metricOrderDelete->resetOnCollect($metric->getKey())) {
                    $metric->setValue(0);
                }
            }
            $logger->debugEnd('Metrics Collection');
        } catch (Exception $ex) {
            $logger->debugEndError('Metrics Collection', $ex);
        }
    }
}


text:
<?php
namespace LangridSettingClient\Client\Google;

use \LangridSettingClient\API\Google as API;

class GoogleClient {
    var $setting;

    public function __construct($setting) {
        $this->setting = $setting;
    }

    public function getTranslator() {
        return new API\GoogleTranslator($this->setting);
    }
}