text
stringlengths
29
850k
#!/usr/bin/env python #-*- coding: utf-8 -*- from random import randint, choice from Bot import ChatBot from requests import get from bs4 import BeautifulSoup as BS from json import dump as jdump class DumbBot(ChatBot): """ Dumb Bot is a basic toy bot integration He has some built in functionality as well as webhook-bot integrations to provide a connection to webhooks WebHook data is stored in the 'shared' folder, so we allow Dumb Bot to access the shared pool """ STATUS = "I'm a bot, Beep Bloop!" GIT_URL = "https://github.com/sleibrock/discord-bots" # Other strings YOUTUBE_URL = "https://www.youtube.com" # Used to convert chars to emojis for self.roll() emojis = {f"{i}":x for i, x in enumerate([f":{x}:" for x in ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")])} def __init__(self, name): super(DumbBot, self).__init__(name) self.filegen = self._create_filegen("shared") @ChatBot.action('<Command>') async def help(self, args, mobj): """ Show the documentation string for a given command If you came here from '!help help', hi and thanks for using me! Example: !help roll """ if args: key = args[0] if not args[0].startswith(ChatBot.PREFIX): key = f'{ChatBot.PREFIX}{args[0]}' if key in self.ACTIONS: t = self.pre_text(f'Help for \'{key}\':{self.ACTIONS[key].__doc__}') return await self.message(mobj.channel, t) keys = [f'{k}' for k in self.ACTIONS.keys()] longest = max((len(s) for s in keys)) + 2 output = 'Thank you for choosing Dumb Bot™ for your channel\n' output += 'Here are the available commands\n\n' for c in keys: output += f'* {c.ljust(longest)} {self.HELPMSGS.get(c, "")}\n' output += f'\nFor more info on each command, use \'{ChatBot.PREFIX}help <command>\'' output += f'\nVisit {self.GIT_URL} for more info' return await self.message(mobj.channel, self.pre_text(output)) @ChatBot.action('<Status String>') async def status(self, args, mobj): """ Change the bot's status to a given string Example: !status haha ur dumb """ return await self.set_status(" ".join(args)) @ChatBot.action('<Dota ID String>') async def dota(self, args, mobj): """ Register a Dota ID (enable your profile as Public!) Example: !dota 40281889 """ p = self.filegen(f"{mobj.author.id}.dota") if not args: if p.is_file(): return await self.message(mobj.channel, f"ID: {p.read_text()}") return await self.message(mobj.channel, "No Dota ID supplied") # Get the first argument in the list and check if it's valid u = args[0].strip().strip("\n") if len(u) > 30 or not u.isnumeric(): return await self.message(mobj.channel, "Invalid ID given") # Write to file and finish with open(p, 'w') as f: jdump({'dota_id': u}, f) return await self.message(mobj.channel, f"Registered ID {u}") @ChatBot.action() async def coin(self, args, mobj): """ Do a coin flip Example: !coin """ return await self.message(mobj.channel, choice([":monkey:", ":snake:"])) @ChatBot.action('<Number>') async def roll(self, args, mobj): """ Make a roll (similar to Dota 2's /roll) between [1..1000] Example: !roll 100 """ if not args or len(args) > 1: return await self.message(mobj.channel, "Invalid arg count") x, = args if not x.isnumeric(): return await self.message(mobj.channel, "Non-numeric arg given") num = int(x) # bad if num < 1 or num > 1000: return await self.message(mobj.channel, "Invalid range given") res = [self.emojis[x] for x in str(randint(1, num)).zfill(len(x))] return await self.message(mobj.channel, "".join(res)) @ChatBot.action('[Search terms]') async def yt(self, args, mobj): """ Get the first Youtube search result video Example: !yt how do I take a screenshot """ if not args: return await self.message(mobj.channel, "Empty search terms") resp = get(f"{self.YOUTUBE_URL}/results?search_query={self.replace(' '.join(args))}") if resp.status_code != 200: return await self.message(mobj.channel, "Failed to retrieve search") # Build a BS parser and find all Youtube links on the page bs = BS(resp.text, "html.parser") main_d = bs.find('div', id='results') if not main_d: return await self.message(mobj.channel, 'Failed to find results') items = main_d.find_all("div", class_="yt-lockup-content") if not items: return await self.message(mobj.channel, "No videos found") # Loop until we find a valid non-advertisement link for container in items: href = container.find('a', class_='yt-uix-sessionlink')['href'] if href.startswith('/watch'): return await self.message(mobj.channel, f'{self.YOUTUBE_URL}{href}') return await self.message(mobj.channel, "No YouTube video found") @ChatBot.action('[String]') async def spam(self, args, mobj): """ Spam a channel with dumb things Example: !spam :ok_hand: """ if not args or len(args) > 10: return await self.message(mobj.channel, "Invalid spam input") y = args * randint(5, 20) return await self.message(mobj.channel, f"{' '.join(y)}") @ChatBot.action('<Poll Query>') async def poll(self, args, mobj): """ Turn a message into a 'poll' with up/down thumbs Example: !poll should polling be a feature? """ await self.client.add_reaction(mobj, '👍') await self.client.add_reaction(mobj, '👎') return @ChatBot.action('[Users]') async def ban(self, args, mobj): """ Ban a user from using bot commands (admin required) Example: !ban @Username @Username2 ... """ if not self.is_admin(mobj): return await self.message(mobj.channel, "Admin permissions needed") bancount = 0 ids = [self.convert_user_tag(x) for x in args] for uid in ids: if uid is not False: r = self.add_ban(uid) bancount += 1 if r else 0 return await self.message(mobj.channel, f"{bancount} users banned") @ChatBot.action('[Users]') async def unban(self, args, mobj): """ Unban a user from the bot commands (admin required) Example: !unban @Username @Username2 ... """ if not self.is_admin(mobj): return await self.message(mobj.channel, "Admin permissions needed") unbanc = 0 ids = [self.convert_user_tag(x) for x in args] for uid in ids: if uid is not False: r = self.del_ban(uid) unbanc += 1 if r else 0 return await self.message(mobj.channel, f"{unbanc} users unbanned") @ChatBot.action() async def botinfo(self, args, mobj): """ Print out debug information about the bot Example: !botinfo """ lines = [] with open('.git/refs/heads/master') as f: head_hash = f.read()[:-1] # All the lines used in the output lines = [ f'Name: {self.name}', f'Actions loaded: {len(self.ACTIONS)}', f'Ban count: {len(self.BANS)}', f'Commit version: #{head_hash[:7]}' f'Commit URL: {self.GIT_URL}/commit/{head_hash}' ] return await self.message(mobj.channel, '```{}```'.format('\n'.join(lines))) if __name__ == '__main__': DumbBot('dumb-bot').run() pass # end
How to android root lyf ls 4512 2019? Easy Step By Step manual, 100% working method. Free download top popular app for android root lyf ls 4512 with/without PC, windows, MAC, laptop. How To easy access android root for models: lyf ls 4508 c 451, lyf ls 4503, lyf ls 5020, lyf ls 5018 hl l51p, lyf ls 5201 panda01a msm8952 64, lyf ls 5002, lyf ls 4510, lyf ls 4511, lyf ls 5009, lyf water f1 ls 5505, hipstreet ls 5507 lyf, lyf ls 4505, .
from Conexion import * import hashlib import cherrypy class Administrador(object): @cherrypy.expose def index(self): return """<html> <head></head> <body> <a href="aviones"> Aviones </a> </br> <a href="registrarse"> Registrarse </a> </body> </html> """ @cherrypy.expose def registrarse(self): return """<html> <head></head> <body> <form action="createlogin"> Nombres: <input type="text" name="nombre"><br> Apellidos: <input type="text" name="apellido"><br> Correo: <input type="text" name="correo"><br> Contrasena: <input type="text" name="secreto"><br> Confirma Contrasena: <button type="submit">Give it now!</button> </form> </body> </html>""" @cherrypy.expose def createlogin(self, nombre, apellido, correo, secreto): con = Conexion() secret = hashlib.sha1() secret.update(secreto) if con.actualiza("insert into logins values('"+correo+"', '"+secret.hexdigest()+"', 'y');") == 1 : if con.actualiza("insert into administrador values('"+correo+"', '"+nombre+"', '"+apellido+"');") == 1: return "se creo" return "no se creo" else: return "no se creo" @cherrypy.expose def login(self): return """<html> <head> <scrip> </script> </head> <body> <form method="get" action="inicia"> Correo: <input type="text" value="" name="correo"><br> Contrasena: <input type="password" value="" name="secreto"><br> <button type="submit">Give it now!</button> </form> </body> </html>""" @cherrypy.expose def inicia(self, correo, secreto): con = Conexion() secret = hashlib.sha1() secret.update(secreto) if(con.consulta("select secreto from logins where correo = '"+correo+"';") is None): return self.login() else: if(con.consulta("select secreto from logins where correo = '"+correo+"';")[0][0] == secret.hexdigest()): return self.admin(correo) return self.login() @cherrypy.expose def admin(self, correo): con = Conexion() usuario = con.consulta("select * from administrador where correo = '"+ correo+ "';") return "Bienvenido "+ usuario[0][1] @cherrypy.expose def promociones(self): return "Aqui se manejaran las promociones" @cherrypy.expose def estadisticas(self): return "Aqui se pondra todo lo de las estadisticas" @cherrypy.expose def vuelos(self): return "vuelos lalalala" @cherrypy.expose def aviones(self): con = Conexion() cuerpo = """<html> <head></head> <body>""" aviones = con.consulta("select * from avion") for avion in aviones: cuerpo = cuerpo + avion[1] + " "+ avion [2]+"" + " </br>" cuerpo = cuerpo + """ </body> </html>""" return cuerpo @cherrypy.expose def viajes(self): con = Conexion() cuerpo = """<html> <head> <script> function quita(){ var x = document.getElementById("viaje_origen"); var s = x.value; var y = "Todos menos seleccionado "+ s; var n = document.getElementById("viaje_destino"); var i; var j; for(j = 0; j < x.length; j++){ n.remove(0); } if(s == 0){ var o = document.createElement("option"); o.text = "no ha seleccionado un pais"; o.value = 0; fecha(0); } else{ for(i = 1; i < x.length; i++){ if(s != x.options[i].value){ var o = document.createElement("option"); o.text = x.options[i].text; o.value = x.options[i].value; n.add(o); } } fecha(1); } } function fecha(p){ var m = document.getElementById("viaje_mes"); var v = m.value; var i; var meses = ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sept", "Oct", "Nov", "Dic"]; if(p == 1){ for(i = 0; i < 12; i++){ var o = document.createElement("option"); o.text = meses[i]; m.add(o); } } else { for(i = 0; i < 12; i++){ m.remove(0); } } } </script> </head> <body > <form method="post" action="createlogin"> Origen: <select id="viaje_origen" name="origen" onchange="quita()"> <option value="0">--Selecciona</option>""" ciudades = con.consulta("select nombre from ciudads") for ciudad in ciudades: cuerpo = cuerpo + """<option value=\""""+ ciudad[0] +"""">"""+ ciudad[0]+"""</option>""" cuerpo = cuerpo + """</select><br>Destino: <select id="viaje_destino" name="destino">""" cuerpo = cuerpo + """</select></br> Fecha:<select id="viaje_anio" name="anio"> <option value="2014">2014</option><option value="2015">2015</option></select> <select id="viaje_mes" name="mes"> </select> <select id="viaje_dia" name="dia"></select></br> Hora Salida: <select id="viaje_hora" name="hora"></select> <select id="viaje_minuto" name="minuto"></select></br> Distancia<input id="viaje_distancia" type="text" name="distancia"/></br> Avion:<select id="viaje_avion" name="idavion"> """ aviones = con.consulta("select * from avion") for avion in aviones: cuerpo = cuerpo + """<option value""""+avion[0]+"""">"""+avion[1]+", capacidad "+str(avion[3]+avion[4])+"""</option>""" cuerpo = cuerpo + """</select></br><button type="submit">Crea Viaje</button> </form> </body> </html>""" return cuerpo if __name__ == '__main__': cherrypy.quickstart(Administrador())
Let us help you really visualize your event, brand activation or wedding with our 3D CAD software. The images are to scale and can best help to work out flow and maximum seating so there will be no surprises on the day of the event. Come into our showroom to see many many examples of past events, weddings or brand activations for our Adelaide, interstate or overseas clients. NEW! Check out our new AHC Event sliders. We can style your event with our hire furniture into our pavilions or your existing space. In the case of the AHC Event Hire team setting up, we would set up from our pre-approved CAD drawing, streamlining the process of delivery and set up. If you need more reasons to engage our services, click here for our thoroughly attractive skill stack.
# Rekall Memory Forensics # Copyright 2013 Google Inc. All Rights Reserved. # # Authors: # Mike Auty # Michael Cohen # Jordi Sanchez # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """ This is based on Jesse Kornblum's patch to clean up the standard AS's. """ # pylint: disable=protected-access import struct from rekall import addrspace from rekall import config from rekall import obj from rekall.plugins.addrspaces import intel from rekall.plugins.addrspaces import standard config.DeclareOption("ept", group="Virtualization support", type="ArrayIntParser", help="The EPT physical address.") class AMD64PagedMemory(intel.IA32PagedMemoryPae): """Standard AMD 64-bit address space. Provides an address space for AMD64 paged memory, aka the x86_64 architecture, which is laid out similarly to Physical Address Extensions (PAE). Allows callers to map virtual address to offsets in physical memory. Create a new AMD64 address space to sit on top of the base address space and a Directory Table Base (CR3 value) of 'dtb'. Comments in this class mostly come from the Intel(R) 64 and IA-32 Architectures Software Developer's Manual Volume 3A: System Programming Guide, Part 1, revision 031, pages 4-8 to 4-15. This book is available for free at http://www.intel.com/products/processor/manuals/index.htm. Similar information is also available from Advanced Micro Devices (AMD) at http://support.amd.com/us/Processor_TechDocs/24593.pdf. """ order = 60 def describe_vtop(self, vaddr, collection=None): """Describe the resolution process of a Virtual Address. See base method for docs. """ if collection is None: collection = intel.DescriptorCollection(self.session) # Bits 51:12 are from CR3 # Bits 11:3 are bits 47:39 of the linear address pml4e_addr = ((self.dtb & 0xffffffffff000) | ((vaddr & 0xff8000000000) >> 36)) pml4e_value = self.read_pte(pml4e_addr) collection.add(intel.AddressTranslationDescriptor, object_name="pml4e", object_value=pml4e_value, object_address=pml4e_addr) if not pml4e_value & self.valid_mask: collection.add(intel.InvalidAddress, "Invalid PML4E\n") return collection # Bits 51:12 are from the PML4E # Bits 11:3 are bits 38:30 of the linear address pdpte_addr = ((pml4e_value & 0xffffffffff000) | ((vaddr & 0x7FC0000000) >> 27)) pdpte_value = self.read_pte(pdpte_addr) collection.add(intel.AddressTranslationDescriptor, object_name="pdpte", object_value=pdpte_value, object_address=pdpte_addr) if not pdpte_value & self.valid_mask: collection.add(intel.InvalidAddress, "Invalid PDPTE\n") # Large page mapping. if pdpte_value & self.page_size_mask: # Bits 51:30 are from the PDE # Bits 29:0 are from the original linear address physical_address = ((pdpte_value & 0xfffffc0000000) | (vaddr & 0x3fffffff)) collection.add(intel.CommentDescriptor, "One Gig page\n") collection.add(intel.PhysicalAddressDescriptor, address=physical_address) return collection # Bits 51:12 are from the PDPTE # Bits 11:3 are bits 29:21 of the linear address pde_addr = ((pdpte_value & 0xffffffffff000) | ((vaddr & 0x3fe00000) >> 18)) self._describe_pde(collection, pde_addr, vaddr) return collection def get_available_addresses(self, start=0): """Enumerate all available ranges. Yields tuples of (vaddr, physical address, length) for all available ranges in the virtual address space. """ # Pages that hold PDEs and PTEs are 0x1000 bytes each. # Each PDE and PTE is eight bytes. Thus there are 0x1000 / 8 = 0x200 # PDEs and PTEs we must test. for pml4e_index in range(0, 0x200): vaddr = pml4e_index << 39 next_vaddr = (pml4e_index + 1) << 39 if start >= next_vaddr: continue pml4e_addr = ((self.dtb & 0xffffffffff000) | ((vaddr & 0xff8000000000) >> 36)) pml4e_value = self.read_pte(pml4e_addr) if not pml4e_value & self.valid_mask: continue tmp1 = vaddr for pdpte_index in range(0, 0x200): vaddr = tmp1 | (pdpte_index << 30) next_vaddr = tmp1 | ((pdpte_index + 1) << 30) if start >= next_vaddr: continue # Bits 51:12 are from the PML4E # Bits 11:3 are bits 38:30 of the linear address pdpte_addr = ((pml4e_value & 0xffffffffff000) | ((vaddr & 0x7FC0000000) >> 27)) pdpte_value = self.read_pte(pdpte_addr) if not pdpte_value & self.valid_mask: continue # 1 gig page. if pdpte_value & self.page_size_mask: yield (vaddr, ((pdpte_value & 0xfffffc0000000) | (vaddr & 0x3fffffff)), 0x40000000) continue for x in self._get_available_PDEs(vaddr, pdpte_value, start): yield x def _get_pte_addr(self, vaddr, pde_value): if pde_value & self.valid_mask: return (pde_value & 0xffffffffff000) | ((vaddr & 0x1ff000) >> 9) def _get_pde_addr(self, pdpte_value, vaddr): if pdpte_value & self.valid_mask: return ((pdpte_value & 0xffffffffff000) | ((vaddr & 0x3fe00000) >> 18)) def _get_available_PDEs(self, vaddr, pdpte_value, start): tmp2 = vaddr for pde_index in range(0, 0x200): vaddr = tmp2 | (pde_index << 21) next_vaddr = tmp2 | ((pde_index + 1) << 21) if start >= next_vaddr: continue pde_addr = self._get_pde_addr(pdpte_value, vaddr) if pde_addr is None: continue pde_value = self.read_pte(pde_addr) if pde_value & self.valid_mask and pde_value & self.page_size_mask: yield (vaddr, (pde_value & 0xfffffffe00000) | (vaddr & 0x1fffff), 0x200000) continue # This reads the entire PTE table at once - On # windows where IO is extremely expensive, its # about 10 times more efficient than reading it # one value at the time - and this loop is HOT! pte_table_addr = self._get_pte_addr(vaddr, pde_value) # Invalid PTEs. if pte_table_addr is None: continue data = self.base.read(pte_table_addr, 8 * 0x200) pte_table = struct.unpack("<" + "Q" * 0x200, data) for x in self._get_available_PTEs( pte_table, vaddr, start=start): yield x def _get_available_PTEs(self, pte_table, vaddr, start=0): tmp3 = vaddr for i, pte_value in enumerate(pte_table): if not pte_value & self.valid_mask: continue vaddr = tmp3 | i << 12 next_vaddr = tmp3 | ((i + 1) << 12) if start >= next_vaddr: continue yield (vaddr, (pte_value & 0xffffffffff000) | (vaddr & 0xfff), 0x1000) def end(self): return (2 ** 64) - 1 class VTxPagedMemory(AMD64PagedMemory): """Intel VT-x address space. Provides an address space that does EPT page translation to provide access to the guest physical address space, thus allowing plugins to operate on a virtual machine running on a host operating system. This is described in the Intel(R) 64 and IA-32 Architectures Software Developer's Manual Volume 3C: System Programming Guide, Part 3, pages 28-1 to 28-12. This book is available for free at http://www.intel.com/products/processor/manuals/index.htm. This address space depends on the "ept" parameter. You can use the vmscan plugin to find valid ept values on a physical memory image. Note that support for AMD's AMD-V address space is untested at the moment. """ # Virtualization is always the last AS since it has to overlay any form of # image AS. order = standard.FileAddressSpace.order + 10 __image = True _ept = None # A page entry being present depends only on bits 2:0 for EPT translation. valid_mask = 7 def __init__(self, ept=None, **kwargs): # A dummy DTB is passed to the base class so the DTB checks on # IA32PagedMemory don't bail out. We require the DTB to never be used # for page translation outside of get_pml4e. try: super(VTxPagedMemory, self).__init__(dtb=0xFFFFFFFF, **kwargs) except TypeError: raise addrspace.ASAssertionError() # Reset the DTB, in case a plugin or AS relies on us providing one. self.dtb = None ept_list = ept or self.session.GetParameter("ept") if not isinstance(ept_list, (list, tuple)): ept_list = [ept_list] self.as_assert(ept_list, "No EPT specified") this_ept = None if isinstance(self.base, VTxPagedMemory): # Find our EPT, which will be the next one after the base one. base_idx = ept_list.index(self.base._ept) try: this_ept = ept_list[base_idx + 1] except IndexError: pass else: this_ept = ept_list[0] self.as_assert(this_ept != None, "No more EPTs specified") self._ept = this_ept self.name = "VTxPagedMemory@%#x" % self._ept def get_pml4e(self, vaddr): # PML4 for VT-x is in the EPT, not the DTB as AMD64PagedMemory does. ept_pml4e_paddr = ((self._ept & 0xffffffffff000) | ((vaddr & 0xff8000000000) >> 36)) return self.read_long_long_phys(ept_pml4e_paddr) def __str__(self): return "%s@0x%08X" % (self.__class__.__name__, self._ept) class XenParaVirtAMD64PagedMemory(AMD64PagedMemory): """XEN ParaVirtualized guest address space.""" PAGE_SIZE = 0x1000 P2M_PER_PAGE = P2M_TOP_PER_PAGE = P2M_MID_PER_PAGE = PAGE_SIZE / 8 def __init__(self, **kwargs): super(XenParaVirtAMD64PagedMemory, self).__init__(**kwargs) self.page_offset = self.session.GetParameter("page_offset") self.m2p_mapping = {} self.rebuilding_map = False if self.page_offset: self._RebuildM2PMapping() def _ReadP2M(self, offset, p2m_size): """Helper function to return p2m entries at offset. This function is used to speed up reading the p2m tree, because traversal via the Array struct is slow. Yields tuples of (index, p2m) for each p2m, up to a number of p2m_size. """ for index, mfn in zip( xrange(0, p2m_size), struct.unpack( "<" + "Q" * p2m_size, self.read(offset, 0x1000))): yield (index, mfn) def _RebuildM2PMapping(self): """Rebuilds the machine to physical mapping. A XEN ParaVirtualized kernel (the guest) maintains a special set of page tables. Each entry is to machine (host) memory instead of physical (guest) memory. XEN maintains a mapping of machine to physical and mapping of physical to machine mapping in a set of trees. We need to use the former to translate the machine addresses in the page tables, but only the later tree is available (mapped in memory) on the guest. When rekall is run against the memory of a paravirtualized Linux kernel we traverse the physical to machine mapping and invert it so we can quickly translate from machine (host) addresses to guest physical addresses. See: http://lxr.free-electrons.com/source/arch/x86/xen/p2m.c?v=3.0 for reference. """ self.session.logging.debug( "Rebuilding the machine to physical mapping...") self.rebuilding_map = True try: p2m_top_location = self.session.profile.get_constant_object( "p2m_top", "Pointer", vm=self).deref() end_value = self.session.profile.get_constant("__bss_stop", False) new_mapping = {} for p2m_top in self._ReadP2M( p2m_top_location, self.P2M_TOP_PER_PAGE): p2m_top_idx, p2m_top_entry = p2m_top self.session.report_progress( "Building m2p map %.02f%%" % ( 100 * (float(p2m_top_idx) / self.P2M_TOP_PER_PAGE))) if p2m_top_entry == end_value: continue for p2m_mid in self._ReadP2M( p2m_top_entry, self.P2M_MID_PER_PAGE): p2m_mid_idx, p2m_mid_entry = p2m_mid if p2m_mid_entry == end_value: continue for p2m in self._ReadP2M(p2m_mid_entry, self.P2M_PER_PAGE): p2m_idx, mfn = p2m pfn = (p2m_top_idx * self.P2M_MID_PER_PAGE * self.P2M_PER_PAGE + p2m_mid_idx * self.P2M_PER_PAGE + p2m_idx) new_mapping[mfn] = pfn self.m2p_mapping = new_mapping self.session.SetCache("mapping", self.m2p_mapping) finally: self.rebuilding_map = False def m2p(self, machine_address): """Translates from a machine address to a physical address. This translates host physical addresses to guest physical. Requires a machine to physical mapping to have been calculated. """ machine_address = obj.Pointer.integer_to_address(machine_address) mfn = machine_address / 0x1000 pfn = self.m2p_mapping.get(mfn) if pfn is None: return 0 return (pfn * 0x1000) | (0xFFF & machine_address) def get_pml4e(self, vaddr): return self.m2p( super(XenParaVirtAMD64PagedMemory, self).get_pml4e(vaddr)) def get_pdpte(self, vaddr, pml4e): return self.m2p( super(XenParaVirtAMD64PagedMemory, self).get_pdpte(vaddr, pml4e)) def get_pde(self, vaddr, pml4e): return self.m2p( super(XenParaVirtAMD64PagedMemory, self).get_pde(vaddr, pml4e)) def get_pte(self, vaddr, pml4e): return self.m2p( super(XenParaVirtAMD64PagedMemory, self).get_pte(vaddr, pml4e)) def vtop(self, vaddr): vaddr = obj.Pointer.integer_to_address(vaddr) if not self.session.GetParameter("mapping"): # Simple shortcut for linux. This is required for the first set # of virtual to physical resolutions while we're building the # mapping. page_offset = obj.Pointer.integer_to_address( self.profile.GetPageOffset()) if vaddr > page_offset: return self.profile.phys_addr(vaddr) # Try to update the mapping if not self.rebuilding_map: self._RebuildM2PMapping() return super(XenParaVirtAMD64PagedMemory, self).vtop(vaddr)
Ticket Nest specializes in Acorn Theatre Tickets and other Theater, Sports and Concert Tickets. Ticket Nest specializes in providing tickets for Acorn Theatre arena. Ticket Nest is an independent company and is not associated with Acorn Theatre. For Event Schedule and available tickets for Acorn Theatre please click buy button below. Ticket Nest guarantees one of the lowest prices for Acorn Theatre tickets anywhere. But we don't skimp on service and support. We know that you want the lowest price and our large volume of ticket sales justifies the lower margins. We pass on the savings to you, our valued customers. It is our strong hope that you will buy our tickets only after comparing our value of service as well as our low prices. We want to hear from you if your experience is anything less than PERFECT. We pledge to provide you cheaper Acorn Theatre. These Acorn Theatre tickets can be purchased via our secure server. The tickets will be sent via Fed-EX. The inventory for the tickets is updated as fast as our server allows. However, on rare occasions, your ticket may not be available. We will contact you and try our best to accommodate you.
from models import db, ma from models.audio import Album from models.audio.meta import WritableField, SmartCollageField from webargs import Arg smart_collage_album_association_table = db.Table( "smart_collage_albums", db.Column('album_id', db.Integer, db.ForeignKey("album.id", ondelete='cascade')), db.Column('collage_id', db.Integer, db.ForeignKey("smart_collage.id", ondelete='cascade')) ) smart_collage_smart_rules_association_table = db.Table( "smart_collage_rules", db.Column('smart_collage_id', db.Integer, db.ForeignKey("smart_collage.id", ondelete='cascade')), db.Column('smart_rule_id', db.Integer, db.ForeignKey("smart_rule.id", ondelete='cascade')) ) class SmartCollage(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) private = db.Column(db.Boolean) owner = db.relationship("User", uselist=False, backref="smart_collages") owner_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade")) albums = db.relationship("Album", secondary=smart_collage_album_association_table) rules = db.relationship("SmartRule", secondary=smart_collage_smart_rules_association_table) connector = db.Column(db.String) sort_by = db.Column(db.String) def __init__(self, owner, name, rules=None): self.owner = owner self.name = name self.albums = [] self.private = True self.rules = rules if rules is not None else [] class SmartCollageSchema(ma.Schema): id = ma.Integer() name = ma.Str() private = ma.Bool() owner = ma.Nested("UserSchema", only=["id", "username"]) albums = ma.Nested("AlbumSchema", many=True, only=["id", "title", "albumartist", "albumart", "tracks"]) writable = WritableField(attribute="owner_id") connector = ma.Str() rules = ma.Nested("SmartRuleSchema", many=True) sort_by = ma.Str() smart = SmartCollageField(attribute="id")
When looking for a new career, finding the right job starts by getting your foot in the door. Catching the attention of recruiters and hiring managers requires a strong first impression, usually in the form of a CV. Your CV serves as your professional introduction to employers, providing them with a picture of your qualifications and experience before your interview. With help from this PHP web developer CV example, learn what to include and how to format your own tailored CV for a career in the tech field. Professional web developer, certified in PHP coding, seeking a senior position on a B2B software development team. Six years’ experience in website construction, database management, coding, and software testing, and oversaw a website relaunch. Since relaunch, daily site traffic has improved by 35 percent. Successfully managed a team of web editors and coders, and thrive in leadership positions. Proficient in most coding languages across multiple platforms and operating systems. Meticulous, task-oriented, and a team player. Coordinate website relaunch, communicating between management and web development team to design, build, and test company website. Debug server errors, filing user feedback reports and improving site functionality. Collaborate with web design and IT to create user-friendly interaction and functionality. Implement backup recovery plan and security protocol to prevent information loss and breaches, and build website archive. Increase site traffic by 35 percent since relaunch in 2015. Tested coding software script, monitoring for bugs and performance issues. Organized and scheduled system-wide tests to address larger functionality inefficiencies. Debriefed development team on potential software errors, and provided user performance reviews. Conducted compatibility tests, testing software across a multitude of platforms to ensure universal compatibility. Maintained and logged error database, filing user and computer-generated feedback reports and problem alerts. Oversaw maintenance of digital information storage and database performance, securing against data loss. Coded and debugged company database, which includes financial, employee, customer, and other information. Coordinated with IT team to integrate data platform with intra-office information network. Assisted with DevOps team to explore the potential of new database development and the limitations of the project. In my free time, I enjoy getting away from the screen by playing softball. I play in an amateur league comprised of fellow web developers and software engineers. Each weekend, we organize games between competing companies. Once per year, we put together a charity fundraiser “World Series” event, which has raised over $70,000 in the last five years. What Does a PHP Web Developer Do? Before taking the next step toward finding your new career, it’s important to understand the role of a PHP web developer. Commonly, PHP web developers design and modify websites, ensuring that they are functioning as intended across multiple operating systems. They are expected to evaluate performance as well as find solutions to bugs and compatibility issues. They may also be asked to assist with content development, including multimedia content, such as audio, video, images, and more. When putting together your CV, you should demonstrate that you understand the details of the position for which you’re applying. For more help, review the PHP web developer CV example to see how the job requirements are incorporated. -Your Professional Summary should reflect both your professional aspirations and achievements as a web developer as well as your personality. Use this space to let some of your personality shine through without seeming too informal. -Do not include any extraneous information, such as political or religious beliefs. These are often inappropriate for professional settings. -Be specific in your work experience. Include metrics and other quantifiable evaluative measures of your success to help employers make a fair assessment of your experience. -You do not need to share your GPA unless you’re a recent graduate with limited work experience in the web development field. -Be concise. Ultimately, your CV should be thorough but brief. You can use sentence fragments and bullet points to highlight the important details while keeping your word count low.
#!/usr/bin/env python from __future__ import print_function import argparse import http.client from snippets import getBrowser, APICall, getNodes, getNodeGroups, getConnectionManagerGroups, getNodesInCMGroups, getPolicies, getEvents, scan from datetime import date, timedelta parser = argparse.ArgumentParser(description='') parser.add_argument('--target-url', required=True, help='URL for the UpGuard instance') parser.add_argument('--api-key', required=True, help='API key for the UpGuard instance') parser.add_argument('--secret-key', required=True, help='Secret key for the UpGuard instance') parser.add_argument('--insecure', action='store_true', help='Ignore SSL certificate checks') args = parser.parse_args() try: browser = getBrowser(target_url=args.target_url, insecure=args.insecure) token = "{}{}".format(args.api_key, args.secret_key) # Nodes nodes = getNodes(browser=browser, token=token, details=True) print("\n\nNodes\n-----") for node in nodes: print("{}\n{}\n\n".format(node["name"], node)) # Node Groups node_groups = getNodeGroups(browser=browser, token=token, details=True) print("\n\nNode Groups\n-----") for group in node_groups: print("{}\n{}\n\n".format(group["name"], group)) # CM Groups cm_groups = getConnectionManagerGroups(browser=browser, token=token) print("\n\nConnection Manager Groups\n-------------------------") for group in cm_groups: print("{}\n{}\n\n".format(group["name"], group)) # CM Groups with Nodes cm_groups = getConnectionManagerGroups(browser=browser, token=token) cm_groups_with_nodes = getNodesInCMGroups(browser=browser, token=token) print("\n\nCM Groups Node Count\n--------------------") for id, nodes in cm_groups_with_nodes.iteritems(): group_name = next((g["name"] for g in cm_groups if g["id"] == id), None) print("{}: {}".format(group_name, len(nodes))) # Policies policies = getPolicies(browser=browser, token=token, details=True) print("\n\nPolicies\n--------") for policy in policies: print("{}\n{}\n\n".format(policy["name"], policy)) # Events events = getEvents(browser=browser, token=token, view="User Logins", since=(date.today() - timedelta(1))) print("\n\nEvents\n-----") for event in events: print("{}\n{}\n\n".format(event["id"], event)) print("Total Events: {}".format(len(events))) # Scan result = scan(browser=browser, token=token, node="dev", wait=True) print("Node scanned, result:\n{}".format(str(result))) except http.client.HTTPException as h: print(h.message) finally: if browser: browser.close()
: "You're welcome" as a response to "Thank you."? What is the origin and meaning? I've read, "given freely", but where did "you're welcome" come from "given freely"? Interesting question. I'm wondering if there is a book out there about manners and associated customs.
# coding: utf-8 from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from cms.models.fields import PageField from django.db import models from django.conf import settings from filer.fields.file import FilerFileField from ckeditor_link.link_model.models import CMSFilerLinkBase class Link(CMSFilerLinkBase): pass class PublishedBase(models.Model): published = models.BooleanField(default=False) class Meta: abstract = True class ModifiedBase(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True class SEOBase(models.Model): seo_title = models.CharField( max_length=255, default='', blank=True, ) meta_description = models.CharField( max_length=255, default='', blank=True, ) class Meta: abstract = True def get_seo_title(self): if getattr(self, 'seo_title', None): return self.seo_title if getattr(self, 'name', None): return self.name if getattr(self, 'title', None): return self.title return '' def get_seo_description(self): if getattr(self, 'meta_description', None): return self.meta_description if getattr(self, 'description', None): return self.description return ''
Rania al-Baz was a TV news producer in Saudi Arabia when her husband brutally beat her – to the point where he thought she was dead. After the abuse, in which she suffered 13 fractures to her face and landed in a coma, al-Baz made the brave decision to publish photos of her now unrecognizable face. (FAYEZ NURELDINE/AFP/Getty Images) Nine years have passed since the people of Saudi Arabia were shocked by newspaper photos of the battered, swollen face of Rania Al-Baz, a well-known television newscaster. Her ghastly injuries were inflicted by her husband, who beat her nearly to death. Rania al-Baz said her husband, Mohammed al-Fallatta, beat her so hard earlier this week that he broke her nose and fractured her face in 13 places. She is recovering in hospital. Police are looking for Mr Fallatta, an unemployed singer. Reuters news agency says he faces charges of attempted murder. Is Oprah ignorant of the Middle East? Rania al Baz was beaten nearly to death, and she was courageous enough to go public. "He told me, 'I'm not coming to beat you. I am coming to kill you.' He grabbed me by the neck and flung me to the ground," she says. For six years, she had been the very popular host of Saudi television's morning show. Rania al-Baz was a TV news producer in Saudi Arabia when her husband brutally beat her – to the point where he thought she was dead. Until 2004, Rania Al-Baz appeared regularly on the television program The Kingdom this Morning, her hair covered but her face unveiled.
#MenuTitle: Compare Glyph Info # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Compares open fonts and builds a lits of differing glyph info, including Unicode values and categorisation. """ import vanilla # CONSTANTS: thingsToCompare = ( "Unicodes", "Category", "Subcategory", "Production Name", "Script", "Export Status", "Left Kerning Group", "Right Kerning Group", "Color", "Left Metrics Key", "Right Metrics Key", "Width Metrics Key", "Is Aligned", "Has Aligned Width", "Has Annotations", "Has Components", "Has Corners", "Has Custom Glyph Info", "Has Hints", "Has PostScript Hints", "Has TrueType Hints", "Has Special Layers", "Is Color Glyph", "Is Apple Color Glyph", "Is SVG Color Glyph", "Is Hangul Key Glyph", "Masters Are Compatible", "Glyph Note", ) predefinedColors = ( "red", "orange", "brown", "yellow", "lightgreen", "green", "lightblue", "blue", "purple", "pink", "lightgrey", "grey", ) missingGlyphValue = "(missing glyph)" missingValue = "–" class CompareGlyphInfo( object ): def __init__( self ): # Window 'self.w': windowWidth = 400 windowHeight = 160 windowWidthResize = 1000 # user can resize width by this value windowHeightResize = 1000 # user can resize height by this value self.w = vanilla.FloatingWindow( ( windowWidth, windowHeight ), # default window size "Compare Glyph Info", # window title minSize = ( windowWidth, windowHeight ), # minimum size (for resizing) maxSize = ( windowWidth + windowWidthResize, windowHeight + windowHeightResize ), # maximum size (for resizing) autosaveName = "com.mekkablue.CompareGlyphInfo.mainwindow" # stores last window position and size ) # UI elements: self.linePos, inset, lineHeight = 5, 6, 22 self.w.descriptionText = vanilla.TextBox( (inset, self.linePos+2, 140, 14), "Compare between fonts:", sizeStyle='small', selectable=True ) self.w.whatToCompare = vanilla.PopUpButton( (inset+140, self.linePos, -160-inset-10, 17), thingsToCompare, sizeStyle='small', callback=self.Reload ) self.w.whatToCompare.getNSPopUpButton().setToolTip_("Choose which glyph info to compare between all open fonts.") self.w.ignoreMissingGlyphs = vanilla.CheckBox( (-160-inset, self.linePos, -inset-25, 17), "Ignore missing glyphs", value=False, callback=self.Reload, sizeStyle='small' ) self.w.ignoreMissingGlyphs.getNSButton().setToolTip_("If activated, will only list glyphs that are present in ALL open fonts.") self.w.updateButton = vanilla.SquareButton( (-inset-20, self.linePos, -inset, 18), "↺", sizeStyle='small', callback=self.Reload ) self.w.updateButton.getNSButton().setToolTip_("Reload with currently opened fonts. Useful if you just opened or closed a font, or brought another font forward.") self.linePos += lineHeight self.Reload() # Open window and focus on it: self.w.open() self.w.makeKey() def getColumnHeaders(self, sender=None): # {"title":xxx, "key":xxx, "editable":False, "width":xxx} for every font headers = [ {"title":"Glyph Name", "key":"glyphName", "editable":False, "width":200, "maxWidth":400}, ] for i,thisFont in enumerate(Glyphs.fonts): if thisFont.filepath: fileName = thisFont.filepath.lastPathComponent() else: fileName = "%s (unsaved)" % thisFont.familyName columnHeader = {"title":fileName, "key":"font-%i"%i, "editable":False, "width":150, "maxWidth":300} headers.append(columnHeader) return headers def returnValue(self, value): if value: return value else: return missingValue def returnBool(self, value): if value: return "✅" return "🚫" def getInfoItemForGlyph(self, glyph): if glyph is None: return missingGlyphValue index = self.w.whatToCompare.get() if index==0: if not glyph.unicodes: return missingValue else: return ", ".join(glyph.unicodes) elif index==1: return self.returnValue( glyph.category ) elif index==2: return self.returnValue( glyph.subCategory ) elif index==3: return self.returnValue( glyph.productionName ) elif index==4: return self.returnValue( glyph.script ) elif index==5: return self.returnBool( glyph.export ) elif index==6: return self.returnValue( glyph.leftKerningGroup ) elif index==7: return self.returnValue( glyph.rightKerningGroup ) elif index==8: if glyph.color is None: return missingValue else: return predefinedColors[glyph.color] elif index==9: return self.returnValue( glyph.leftMetricsKey ) elif index==10: return self.returnValue( glyph.rightMetricsKey ) elif index==11: return self.returnValue( glyph.widthMetricsKey ) elif index==12: return self.returnBool( glyph.isAligned() ) elif index==13: return self.returnBool( glyph.hasAlignedWidth() ) elif index==14: return self.returnBool( glyph.hasAnnotations() ) elif index==15: return self.returnBool( glyph.hasComponents() ) elif index==16: return self.returnBool( glyph.hasCorners() ) elif index==17: return self.returnBool( glyph.hasCustomGlyphInfo() ) elif index==18: return self.returnBool( glyph.hasHints() ) elif index==19: return self.returnBool( glyph.hasPostScriptHints() ) elif index==20: return self.returnBool( glyph.hasTrueTypeHints() ) elif index==21: return self.returnBool( glyph.hasSpecialLayers() ) elif index==22: return self.returnBool( glyph.isColorGlyph() ) elif index==23: return self.returnBool( glyph.isAppleColorGlyph() ) elif index==24: return self.returnBool( glyph.isSVGColorGlyph() ) elif index==25: return self.returnBool( glyph.isHangulKeyGlyph() ) elif index==26: return self.returnBool( glyph.mastersCompatible ) elif index==27: return self.returnValue( glyph.note ) return "⚠️ Error" def listContent( self ): try: ignoreMissingGlyphs = self.w.ignoreMissingGlyphs.get() allNames = [] for thisFont in Glyphs.fonts: allNames.extend([g.name for g in thisFont.glyphs]) allNames = sorted(set(allNames)) displayedLines = [] for glyphName in allNames: line = {"glyphName":glyphName} checkList = [] for i, thisFont in enumerate(Glyphs.fonts): column = "font-%i"%i glyph = thisFont.glyphs[glyphName] cell = self.getInfoItemForGlyph(glyph) line[column] = cell checkList.append(cell) # check if line contains differences: countOfDistinctItems = len(set(checkList)) if checkList and countOfDistinctItems>1: if ignoreMissingGlyphs and countOfDistinctItems==2: if not all([item!=missingGlyphValue for item in checkList]): continue displayedLines.append(line) return displayedLines except Exception as e: print("listContent Error: %s\n" % e) import traceback print(traceback.format_exc()) return None def Reload( self, sender=None ): try: try: del self.w.List except: pass self.w.List = vanilla.List( ( 0, self.linePos, -0, -0 ), self.listContent(), columnDescriptions = self.getColumnHeaders(), drawVerticalLines = True, enableDelete = True, drawFocusRing = True, # selectionCallback = self.selectedAction, doubleClickCallback = self.openGlyphInFont, # editCallback = self.editAction, ) self.w.List.getNSTableView().setToolTip_("Double click to open the selected glyphs in all fonts. You can select more than one line.") except Exception as e: print("Reload Error: %s\n" % e) import traceback print(traceback.format_exc()) return None def openGlyphInFont(self, sender=None): if sender: selectedIndexes = sender.getSelection() if selectedIndexes: tabText = "" for index in selectedIndexes: item = self.w.List.get()[index] tabText += "/%s" % item["glyphName"] if tabText: for i, thisFont in enumerate(Glyphs.fonts): tab = thisFont.currentTab if not tab: tab = thisFont.newTab() tab.text = tabText tab.textCursor = 0 tab.scale = 0.15 if i>0: tab.viewPort = Glyphs.fonts[0].currentTab.viewPort CompareGlyphInfo()
On this website we recommend many designs abaout Ford F150 Wiki that we have collected from various sites home design, and of course what we recommend is the most excellent of design for Ford F150 Wiki. If you like the design on our website, please do not hesitate to visit again and get inspiration from all the houses in the design of our web design. Gallery of "Ford F150 Wiki"
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging import mock import os import shutil import tempfile import types import unittest import utils.log_parser as lparser class TestBuildLogParser(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) @mock.patch("utils.log_parser._traverse_dir_and_parse") def test_log_parser_correct(self, mock_parse): mock_parse.return_value = (200, {}) job_id = "job_id" job = "job" kernel = "kernel" json_obj = { "job": job, "kernel": kernel } status, errors = lparser.parse_build_log(job_id, json_obj, {}) self.assertEqual(200, status) self.assertDictEqual({}, errors) def test_log_parser_no_job_id(self): job_id = None job = "job" kernel = "kernel" json_obj = { "job": job, "kernel": kernel } status, errors = lparser.parse_build_log(job_id, json_obj, {}) self.assertEqual(500, status) self.assertEqual(1, len(errors.keys())) self.assertEqual([500], errors.keys()) def test_log_parser_hidden_dir(self): job_id = "job_id" job = ".job" kernel = "kernel" json_obj = { "job": job, "kernel": kernel } status, errors = lparser.parse_build_log(job_id, json_obj, {}) self.assertEqual(500, status) self.assertEqual(1, len(errors.keys())) self.assertEqual([500], errors.keys()) @mock.patch("os.path.isdir") def test_log_parser_not_dir(self, mock_isdir): mock_isdir.return_value = False job_id = "job_id" job = "job" kernel = "kernel" json_obj = { "job": job, "kernel": kernel } status, errors = lparser.parse_build_log(job_id, json_obj, {}) self.assertEqual(500, status) self.assertEqual(1, len(errors.keys())) self.assertEqual([500], errors.keys()) def test_parse_build_log(self): build_dir = None try: build_dir = tempfile.mkdtemp() log_file = os.path.join( os.path.abspath(os.path.dirname(__file__)), "assets", "build_log_0.log") status, errors, e_l, w_l, m_l = lparser._parse_log( "job", "kernel", "defconfig", log_file, build_dir) self.assertEqual(200, status) self.assertIsInstance(errors, types.ListType) self.assertIsInstance(e_l, types.ListType) self.assertIsInstance(w_l, types.ListType) self.assertIsInstance(m_l, types.ListType) self.assertEqual(0, len(errors)) self.assertEqual(9, len(e_l)) self.assertEqual(2, len(w_l)) self.assertEqual(0, len(m_l)) finally: shutil.rmtree(build_dir, ignore_errors=True) def test_parse_build_log_no_file(self): build_dir = None try: build_dir = tempfile.mkdtemp() status, errors, e_l, w_l, m_l = lparser._parse_log( "job", "kernel", "defconfig", build_dir, build_dir) self.assertEqual(500, status) self.assertIsInstance(errors, types.ListType) self.assertIsInstance(e_l, types.ListType) self.assertIsInstance(w_l, types.ListType) self.assertIsInstance(m_l, types.ListType) self.assertEqual(1, len(errors)) self.assertEqual(0, len(e_l)) self.assertEqual(0, len(w_l)) self.assertEqual(0, len(m_l)) finally: shutil.rmtree(build_dir, ignore_errors=True) @mock.patch("io.open", create=True) def test_parse_build_log_error_opening(self, mock_open): mock_open.side_effect = IOError build_dir = None try: build_dir = tempfile.mkdtemp() log_file = os.path.join( os.path.abspath(os.path.dirname(__file__)), "assets", "build_log_0.log") status, errors, e_l, w_l, m_l = lparser._parse_log( "job", "kernel", "defconfig", log_file, build_dir) self.assertEqual(500, status) self.assertIsInstance(errors, types.ListType) self.assertIsInstance(e_l, types.ListType) self.assertIsInstance(w_l, types.ListType) self.assertIsInstance(m_l, types.ListType) self.assertEqual(1, len(errors)) self.assertEqual(0, len(e_l)) self.assertEqual(0, len(w_l)) self.assertEqual(0, len(m_l)) finally: shutil.rmtree(build_dir, ignore_errors=True)
The videos in the EXERCISE PLAYLISTS will help you to go step by step through all the exercises you will need to use from before your surgery to after your Hip Replacement. This video is an OVERVIEW of the Exercise Program you will need to follow. It contains advice and suggestions about what to do, when to do it, and why these exercises are important in helping you to make a successful recovery from Hip Surgery and get the full benefits of your Hip Replacement.
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import os import sys import logging import openerp import openerp.netsvc as netsvc import openerp.addons.decimal_precision as dp from openerp.osv import fields, osv, expression, orm from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from openerp import SUPERUSER_ID, api from openerp import tools from openerp.tools.translate import _ from openerp.tools.float_utils import float_round as round from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare) _logger = logging.getLogger(__name__) class SaleOrder(orm.Model): ''' Model name: SaleOrder ''' _inherit = 'sale.order' _columns = { 'force_vector': fields.text('Force vector'), #'fast_vector': fields.boolean('Fast Vector', # help='Add fast vector for report and not the one in carrier'), #'vector_name': fields.char('Vector name'), #'vector_street': fields.char('Street'), #'vector_street2': fields.char('Street2'), #'vector_zip': fields.char('Zip', size=24), #'vector_city': fields.char('City'), #'vector_state_id': fields.many2one('res.country.state', 'State', # ondelete='restrict'), #'vector_country_id': fields.many2one('res.country', 'Country', # ondelete='restrict'), } class AccountInvoice(orm.Model): ''' Model name: AccountInvoice ''' _inherit = 'account.invoice' _columns = { 'force_vector': fields.text('Force vector'), } class StockDdt(orm.Model): ''' Model name: Stock DDT ''' _inherit = 'stock.ddt' _columns = { 'force_vector': fields.text('Force vector'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Home repair projects can add up quick, and many are seasonal issues. Without a good handyman, you're looking at a lot of planning and hard work. If you're are looking for help with your projects our affordable and licensed handymen in Milwaukee County specialize in many types of home improvement fields. If you live in or around the Milwaukee County, Wisconsin area and would like a free quote for our handyman services, then please contact us any time. Simply use the form to tell us where in Milwaukee County you are located and provide a detailed description about your handyman needs. One of our experienced handymen will get back to you with more information and a free quote for labor and materials. The Best Handyman in Milwaukee County, Wisconsin - We can replace, repair, install, clean, service just about any item in your home!
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_partition short_description: Manage BIG-IP partitions description: - Manage BIG-IP partitions. version_added: 2.5 options: name: description: - Name of the partition required: True description: description: - The description to attach to the Partition. route_domain: description: - The default Route Domain to assign to the Partition. If no route domain is specified, then the default route domain for the system (typically zero) will be used only when creating a new partition. state: description: - Whether the partition should exist or not. default: present choices: - present - absent notes: - Requires BIG-IP software version >= 12 extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = r''' - name: Create partition "foo" using the default route domain bigip_partition: name: foo password: secret server: lb.mydomain.com user: admin delegate_to: localhost - name: Create partition "bar" using a custom route domain bigip_partition: name: bar route_domain: 3 password: secret server: lb.mydomain.com user: admin delegate_to: localhost - name: Change route domain of partition "foo" bigip_partition: name: foo route_domain: 8 password: secret server: lb.mydomain.com user: admin delegate_to: localhost - name: Set a description for partition "foo" bigip_partition: name: foo description: Tenant CompanyA password: secret server: lb.mydomain.com user: admin delegate_to: localhost - name: Delete the "foo" partition bigip_partition: name: foo password: secret server: lb.mydomain.com user: admin state: absent delegate_to: localhost ''' RETURN = r''' route_domain: description: Name of the route domain associated with the partition. returned: changed and success type: int sample: 0 description: description: The description of the partition. returned: changed and success type: string sample: Example partition ''' from ansible.module_utils.basic import AnsibleModule try: from library.module_utils.network.f5.bigip import HAS_F5SDK from library.module_utils.network.f5.bigip import F5Client from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import f5_argument_spec try: from library.module_utils.network.f5.common import iControlUnexpectedHTTPError except ImportError: HAS_F5SDK = False except ImportError: from ansible.module_utils.network.f5.bigip import HAS_F5SDK from ansible.module_utils.network.f5.bigip import F5Client from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import f5_argument_spec try: from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError except ImportError: HAS_F5SDK = False class Parameters(AnsibleF5Parameters): api_map = { 'defaultRouteDomain': 'route_domain', } api_attributes = [ 'description', 'defaultRouteDomain' ] returnables = [ 'description', 'route_domain' ] updatables = [ 'description', 'route_domain' ] def to_return(self): result = {} try: for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) return result except Exception: return result @property def partition(self): # Cannot create a partition in a partition, so nullify this return None @property def route_domain(self): if self._values['route_domain'] is None: return None return int(self._values['route_domain']) class Changes(Parameters): pass class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: result = self.__default(param) return result def __default(self, param): attr1 = getattr(self.want, param) try: attr2 = getattr(self.have, param) if attr1 != attr2: return attr1 except AttributeError: return attr1 class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) self.have = None self.want = Parameters(params=self.module.params) self.changes = Changes() def _set_changed_options(self): changed = {} for key in Parameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = Parameters(params=changed) def _update_changed_options(self): diff = Difference(self.want, self.have) updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.compare(k) if change is None: continue else: changed[k] = change if changed: self.changes = Parameters(params=changed) return True return False def exec_module(self): changed = False result = dict() state = self.want.state try: if state == "present": changed = self.present() elif state == "absent": changed = self.absent() except iControlUnexpectedHTTPError as e: raise F5ModuleError(str(e)) changes = self.changes.to_return() result.update(**changes) result.update(dict(changed=changed)) return result def present(self): if self.exists(): return self.update() else: return self.create() def create(self): if self.module.check_mode: return True self.create_on_device() if not self.exists(): raise F5ModuleError("Failed to create the partition.") return True def should_update(self): result = self._update_changed_options() if result: return True return False def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.module.check_mode: return True self.update_on_device() return True def absent(self): if self.exists(): return self.remove() return False def remove(self): if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the partition.") return True def read_current_from_device(self): resource = self.client.api.tm.auth.partitions.partition.load( name=self.want.name ) result = resource.attrs return Parameters(params=result) def exists(self): result = self.client.api.tm.auth.partitions.partition.exists( name=self.want.name ) return result def update_on_device(self): params = self.want.api_params() result = self.client.api.tm.auth.partitions.partition.load( name=self.want.name ) result.modify(**params) def create_on_device(self): params = self.want.api_params() self.client.api.tm.auth.partitions.partition.create( name=self.want.name, **params ) def remove_from_device(self): result = self.client.api.tm.auth.partitions.partition.load( name=self.want.name ) if result: result.delete() class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True argument_spec = dict( name=dict(required=True), description=dict(), route_domain=dict(type='int'), state=dict( choices=['absent', 'present'], default='present' ) ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) def main(): client = None spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode ) if not HAS_F5SDK: module.fail_json(msg="The python f5-sdk module is required") try: client = F5Client(**module.params) mm = ModuleManager(module=module, client=client) results = mm.exec_module() cleanup_tokens(client) module.exit_json(**results) except F5ModuleError as ex: if client: cleanup_tokens(client) module.fail_json(msg=str(ex)) if __name__ == '__main__': main()
Anonymous. 2019. Corvus macrorhynchos Wagler, 1827 – Large-billed Crow. Birds of India Consortium (eds.). Birds of India, v. 1.75. Indian Foundation for Butterflies.
import requests from lxml import etree from cloudbot import hook from cloudbot.util import formatting # security parser = etree.XMLParser(resolve_entities=False, no_network=True) API_URL = "http://steamcommunity.com/id/{}/" ID_BASE = 76561197960265728 headers = {} class SteamError(Exception): pass def convert_id32(id_64): """ Takes a Steam ID_64 formatted ID and returns a ID_32 formatted ID :type id_64: int :return: str """ out = ["STEAM_0:"] final = id_64 - ID_BASE if final % 2 == 0: out.append("0:") else: out.append("1:") out.append(str(final // 2)) return "".join(out) def convert_id3(id_64): """ Takes a Steam ID_64 formatted ID and returns a ID_3 formatted ID :typetype id_64: int :return: str """ _id = (id_64 - ID_BASE) * 2 if _id % 2 == 0: _id += 0 else: _id += 1 actual = str(_id // 2) return "U:1:{}".format(actual) def get_data(user): """ Takes a Steam Community ID of a Steam user and returns a dict of data about that user :type user: str :return: dict """ data = {} # form the request params = {'xml': 1} # get the page try: request = requests.get(API_URL.format(user), params=params, headers=headers) request.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: raise SteamError("Could not get user info: {}".format(e)) profile = etree.fromstring(request.content, parser=parser) try: data["name"] = profile.find('steamID').text data["id_64"] = int(profile.find('steamID64').text) online_state = profile.find('stateMessage').text except AttributeError: raise SteamError("Could not get data for this user.") online_state = online_state.replace("<br/>", ": ") # will make this pretty later data["state"] = formatting.strip_html(online_state) data["id_32"] = convert_id32(data["id_64"]) data["id_3"] = convert_id3(data["id_64"]) return data @hook.on_start def set_headers(bot): """ Runs on initial plugin load and sets the HTTP headers for this plugin. """ global headers headers = { 'User-Agent': bot.user_agent } @hook.command("steamid", "sid", "steamuser", "su") def steamid(text): """steamid <username> -- gets the steam ID of <username>. Uses steamcommunity.com/id/<nickname>. """ try: data = get_data(text) except SteamError as e: return "{}".format(e) return "{name} ({state}): \x02ID64:\x02 {id_64}, \x02ID32:\x02 {id_32}, \x02ID3:\x02 {id_3}".format(**data)
Question For Canadians. Any of you ever use this product? Any of you Canadians up there in the great white North ever use this spray lubricant, penetrate? I recently sold some of my suspension, and brake parts to a Canadian, and he was mentioning this product as the thing to use. Expensive as hell, and supposedly discontinued in the USA, as it's a product that most likely works, but the EPA probably finds some fault with it, for some reason or another. Dunno. Me, i never heard of it before, and wonder if i should give it a try? It's made in Canada, so i thought i might ask, here on this forum. Guess it's even hard to find in Canada. I GOOGLED this product, and found out that California OSHA, banned this product for sale in the state. But Wikipedia doesn't say anything about using it, importing it, into the state. Probably something our big shots in government, in this state, figure something isn't good for us, living here. Pretty sure I have seen it at Home Depot in Calgary. Never used it though. I've used it before...cant say it stands out to me as being anything special?? Typical "mechanic in a can" stuff...no matter what I use I break s**t anyway lol. Aerosols seem to have dropped in price for some stuff, but others going up. I bought a case of MP Hemi Orange paint (dodge dealership)as I read on here it's near extinct. $15/can. Same supplier I bought the red MP paint...$10/can. Spin the wheel with pricing...I'd be willing to ship, but now you have to sign off "no dangerous goods" at post office. Rambling here but I didnt think the Jig is anything special. Don't know how it's marketed, advertised, sold, up there in Canada, but i was interested in this stuff, as i was recently looking at chemicals, sprays, penetrates, products, that are used in the aviation industry, that you would never hear of, or buy, at the auto parts stores, or Home Depot, Lowes. Close, that's a good one. But it's gigolo, but can be taken as GIG - O - LO, a different take on that Canadian spray. Princess auto carries it if i recall. There was a product years ago, magic wrench. That was the best stuff i ever used. Was unbolting box sides on an old gmc, and tried various sprays. The magic wrench worked the best. I have heard of Magic Wrench super penetrate. I have a can on order from a Wall Mart vendor. Haven't got it yet, to try it out. Nope. Made by jet lube. Best one so far. Do you have to be Canadian to use it??? Why can't Americans use it???? With our winters we need all the lube we can get! If I read Wiki right, it's been banned since 2013 in Cali. We need all the lube we can get! I have some, in my basement, bought from Canadian Tire. I thought I'd try it as a replacement for WD 40. Nothing special, to me. What does he use it for? There is another interesting product called Fluid Film. It's made from lanolin. Expensive. I use it often. Come to find out , this product isn't available on Amazon, by any vendors. And on ebay there is a seller that want's $40.00 a can. That's way too expensive for my piggy bank. So then, I'm under the impression that it's no better, no worse, than say WD-40. It's all over Ebay. I tell you though, I've had good success with Deep Creep. That Fluid Film is really not a penetrating lubricant. It's more along the lines of a coating as for freshly machined engine parts ant the like. It is great for that.
import argparse import random import os import setup import numpy as np parser = argparse.ArgumentParser(description='Create meta-simulation package at workdir') parser.add_argument('--netlogo', required=True, help='absolute path to netlogo directory') parser.add_argument('--workdir', required=True, help='absolute path to working directory where meta-simulation will be setup.') parser.add_argument('--threads', type=int, default=12) args = parser.parse_args() # create working directory if not os.path.isdir(args.workdir): os.makedirs(args.workdir) # create symlink to netlogo netlogo_jar = os.path.join( args.netlogo, "app/netlogo-6.0.2.jar") assert os.path.exists(netlogo_jar) os.symlink(netlogo_jar, os.path.join(args.workdir, "NetLogo.jar")) # symlink extensions extensions = ['csv', 'matrix', 'gis', 'bitmap', 'profiler'] for extension in extensions: ext_path = os.path.join( args.netlogo, "app/extensions/%s" % extension) assert os.path.exists(ext_path) os.symlink(ext_path, os.path.join(args.workdir, extension)) # create symlinks to model, argumentspace and run script this_dir = os.path.dirname(os.path.realpath(__file__)) os.symlink(os.path.join(this_dir, "ABM-Empirical-MexicoCity_V6.nlogo"), os.path.join(args.workdir, "ABM-Empirical-MexicoCity_V6.nlogo")) os.symlink(os.path.join(this_dir, "setup.nls"), os.path.join(args.workdir, "setup.nls")) os.symlink(os.path.join(this_dir,"value_functions.nls"), os.path.join(args.workdir,"value_functions.nls")) os.symlink(os.path.join(this_dir, "run.sh"), os.path.join(args.workdir, "run.sh")) os.symlink(os.path.join(this_dir, "data"), os.path.join(args.workdir, "data")) # read setup and submit templates setup_template = open('setup_template_empirical.xml').read() condor_template= open('submit_template.condor').read() # create setup XML files and condor files with open('%s/submit_all.condor' % args.workdir, 'w') as condorfile: for eficiencia_nuevainfra in setup.eficiencia_nuevainfra: for eficiencia_mantenimiento in setup.eficiencia_mantenimiento: for Lambda in setup.Lambda: for factor_subsidencia in setup.factor_subsidencia: for recursos_para_distribucion in setup.recursos_para_distribucion: for recursos_para_mantenimiento in setup.recursos_para_mantenimiento: for recursos_nuevainfrastructura in setup.recursos_nuevainfrastructura: for requerimiento_deagua in setup.requerimiento_deagua: for n_runs in setup.n_runs: run_id = "r_%s_%s_%s_%s_%s_%s_%s_%s_%s" % (eficiencia_nuevainfra, eficiencia_mantenimiento, Lambda, factor_subsidencia, recursos_para_mantenimiento, recursos_para_distribucion, recursos_nuevainfrastructura, requerimiento_deagua, n_runs) condorfile.write(condor_template.format(run_id=run_id, threads=args.threads)) with open('%s/setup_%s.xml' % (args.workdir, run_id), 'w') as setupfile: e = {"time_limit" : setup.years * 365, "eficiencia_nuevainfra": eficiencia_nuevainfra, "eficiencia_mantenimiento": eficiencia_mantenimiento, "lambda": Lambda, "escala": setup.escala, "factor_subsidencia": factor_subsidencia, "recursos_para_distribucion": recursos_para_distribucion, "recursos_para_mantenimiento": recursos_para_mantenimiento, "recursos_nuevainfrastructura": recursos_nuevainfrastructura, "ANP": setup.ANP, "requerimiento_deagua": requerimiento_deagua, "n_runs": n_runs} setupfile.write( setup_template.format(**e) )
These super cute baby and toddler shorties are made from ecologically-safe ultra-colour technology printed organic cotton knit which is GOTS certified. Its a medium weight fabric making it both cool in the summer and cosy in the winter. All seams are overlocked for extra strength and quality whilst your little one is enjoying lifes adventures.
""" VirtWhat ======== Combiner to check if the host is running on a virtual or physical machine. It uses the results of the ``DMIDecode`` and ``VirtWhat`` parsers. Prefer ``VirtWhat`` to ``DMIDecode``. Examples: >>> vw = shared[VirtWhat] >>> vw.is_virtual True >>> vw.is_physical False >>> vw.generic 'kvm' >>> vw.amended_generic 'rhev' >>> 'aws' in vw False """ from insights.core.plugins import combiner from insights.parsers.dmidecode import DMIDecode from insights.parsers.virt_what import VirtWhat as VW, BAREMETAL # Below 2 Maps are only For DMIDecode GENERIC_MAP = { 'vmware': ['VMware'], 'kvm': ['Red Hat', 'KVM'], 'xen': ['Xen', 'domU'], 'virtualpc': ['Microsoft Corporation', 'Virtual Machine'], 'virtualbox': ['innotek GmbH'], 'parallels': ['Parallels'], 'qemu': ['QEMU'], } SPECIFIC_MAP = { 'aws': ['amazon'], 'xen-hvm': ['HVM'], } OVIRT = 'ovirt' RHEV = 'rhev' @combiner([DMIDecode, VW]) class VirtWhat(object): """ A combiner for checking if this machine is virtual or physical by checking ``virt-what`` or ``dmidecode`` command. Prefer ``virt-what`` to ``dmidecode`` Attributes: is_virtual (bool): It's running in a virtual machine? is_physical (bool): It's running in a physical machine? generic (str): The type of the virtual machine. 'baremetal' if physical machine. specifics (list): List of the specific information. amended_generic (str):The type of the virtual machine. 'baremetal' if physical machine. Added to address an issue with virt_what/dmidecode when identifying 'ovirt' vs 'rhev'. Will match the generic attribute in all other cases. """ def __init__(self, dmi, vw): self.is_virtual = self.is_physical = None self.generic = '' self.specifics = [] if vw and not vw.errors: self.is_physical = vw.is_physical self.is_virtual = vw.is_virtual self.generic = vw.generic self.specifics = vw.specifics # Error occurred in ``virt-what``, try ``dmidecode`` if (vw is None or vw.errors) and dmi: sys_info = dmi.get("system_information", [{}])[0] bios_info = dmi.get("bios_information", [{}])[0] dmi_info = list(sys_info.values()) + list(bios_info.values()) if dmi_info: for dmi_v in dmi_info: if not self.generic: generic = [g for g, val in GENERIC_MAP.items() if any(v in dmi_v for v in val)] self.generic = generic[0] if generic else '' self.specifics.extend([g for g, val in SPECIFIC_MAP.items() if any(v in dmi_v for v in val)]) self.is_virtual = True self.is_physical = False if self.generic == '': self.generic = BAREMETAL self.is_virtual = False self.is_physical = True sys_info = dmi.get("system_information", [{}])[0] if dmi else None self.amended_generic = (RHEV if sys_info['product_name'].lower() == 'rhev hypervisor' else OVIRT if sys_info['product_name'].lower() == 'ovirt node' else self.generic) if sys_info else self.generic def __contains__(self, name): """bool: Is this ``name`` found in the specific list?""" return name in [self.generic] + self.specifics
I miss the life I had when my children were little. We did not have much, we lived in a house that was barely 900 square feet, but my kids had what they needed, they attended the religious school we wanted for them, took a nice vacation every year and I was able to stay home to care for them. We were super happy. I know I'm a little melancholic today (after watching all of those little ones coming to my house for candy). I've come to the realization that more is not always better. Why didn't we stay in the small house (that was paid for) with low taxes? Instead, we bought this nice house, paying double the taxes and a $250,000 loan and a $2200 mortgage payment (taxes and insurance included). I hate to say it, but we fell for the trap of keeping up with the Jones's. Thanks for listening, this site is like going for therapy. I do agree, it is nice to have a paid for house! We kept our small 900 sf house as a rental and plan to return to it when our nest is empty. We live in a big house, too ($283K owed and $1750 payment). I wish we hadn't move to this big of a house - the small one was too small, but a medium house would have been fine. The kids are still home, we have an 18 and 14 year old. If we could find a house downsize we would. But until now we cannot find a house for less than what we paid for ours that is worthy of consideration. I keep looking though. You did the right thing staying in your small home. Thanks to all who gave me their input. You sound like me. 5 years ago we had a cute little cape cod we had built for us...hardwood floors, tile in the bathroom and a beautiful kitchen and a mortgage payment of 700 per month. Now we pay 1900 a month for a big house but I swear it's not as nice. I think it's because I am so stressed living here. In the old house I stayed at home with the kids and life was very relaxed...now it's not. I would love to sell but in this economy and in my community it isn't going to happen for many years. Well, it's better learning that lesson than never learning it at all. I hope your situation improves. I am so glad i didn't take on more mortgage, and more house, than i could handle as a single woman 13 years ago. In fact, i played it so conservative and saved for so long, living in my sister's basement, that i was able to put down 45% in cash. So my mortgage is a very manageable $775 a month, plus property taxes. Still, as much as i love this house, i still consider it a money pit. I regret not having been able to sell it and move to a condo 3 years ago, but my relationship ended and i had unexpected surgery right before the real estate market began to crash, so i took the house off the market. I would still like to sell whenever the market recovers, hopefully within the next 5 years. I think i could really save a lot more money living in a condo. My property taxes are killing me, plus the many, many expenses of owning a home on one income.
import pandas as pd from django.http import HttpResponse from django.shortcuts import render from csos.models import RiverCso, RiverOutfall from events.analyzer import rainfall_graph, find_n_years, build_flooding_data from events.models import HourlyPrecip, NYearEvent from flooding.models import BasementFloodingEvent def index(request): _default_start = '07/22/2011 08:00' _default_end = '07/23/2011 06:00' return show_date(request, _default_start, _default_end) def show_date(request, start_stamp, end_stamp): ret_val = {} try: start = pd.to_datetime(start_stamp) end = pd.to_datetime(end_stamp) ret_val['start_date'] = start.strftime("%m/%d/%Y %H:%M") ret_val['end_date'] = end.strftime("%m/%d/%Y %H:%M") hourly_precip_dict = list( HourlyPrecip.objects.filter( start_time__gte=start, end_time__lte=end ).values() ) hourly_precip_df = pd.DataFrame(hourly_precip_dict) ret_val['total_rainfall'] = "%s inches" % hourly_precip_df['precip'].sum() high_intensity = find_n_years(hourly_precip_df) if high_intensity is None: ret_val['high_intensity'] = 'No' else: ret_val['high_intensity'] = "%s inches in %s hours!<br> A %s-year storm" % ( high_intensity['inches'], high_intensity['duration_hrs'], high_intensity['n']) graph_data = {'total_rainfall_data': rainfall_graph(hourly_precip_df)} csos_db = RiverCso.objects.filter(open_time__range=(start, end)).values() | RiverCso.objects.filter( close_time__range=(start, end)).values() csos_df = pd.DataFrame(list(csos_db)) csos = [] ret_val['sewage_river'] = 'None' if len(csos_df) > 0: csos_df['duration'] = (csos_df['close_time'] - csos_df['open_time']) ret_val['sewage_river'] = "%s minutes" % int(csos_df['duration'].sum().seconds / 60) river_outfall_ids = csos_df['river_outfall_id'].unique() river_outfall_ids = list(river_outfall_ids) river_outfalls = RiverOutfall.objects.filter( id__in=river_outfall_ids, lat__isnull=False ) for river_outfall in river_outfalls: csos.append({'lat': river_outfall.lat, 'lon': river_outfall.lon}) cso_map = {'cso_points': csos} graph_data['cso_map'] = cso_map flooding_df = pd.DataFrame( list(BasementFloodingEvent.objects.filter(date__gte=start).filter(date__lte=end).values())) if len(flooding_df) > 0: graph_data['flooding_data'] = build_flooding_data(flooding_df) ret_val['basement_flooding'] = flooding_df[flooding_df['unit_type'] == 'ward']['count'].sum() else: graph_data['flooding_data'] = {} ret_val['basement_flooding'] = 0 ret_val['graph_data'] = graph_data except ValueError as e: return HttpResponse("Not valid dates") ret_val['hourly_precip'] = str(hourly_precip_df.head()) return render(request, 'show_event.html', ret_val) def nyear(request, recurrence): recurrence = int(recurrence) ret_val = {'recurrence': recurrence, 'likelihood': str(int(1 / int(recurrence) * 100)) + '%'} events = [] events_db = NYearEvent.objects.filter(n=recurrence) for event in events_db: date_formatted = event.start_time.strftime("%m/%d/%Y") + "-" + event.end_time.strftime("%m/%d/%Y") duration = str(event.duration_hours) + ' hours' if event.duration_hours <= 24 else str( int(event.duration_hours / 24)) + ' days' events.append({'date_formatted': date_formatted, 'inches': "%.2f" % event.inches, 'duration_formatted': duration, 'event_url': '/date/%s/%s' % (event.start_time, event.end_time)}) ret_val['events'] = events ret_val['num_occurrences'] = len(events) return render(request, 'nyear.html', ret_val) def viz_animation(request): return render(request, 'viz.html') def basement_flooding(request): return render(request, 'flooding.html') def viz_splash(request): return render(request, 'viz-splash.html') def about(request): return render(request, 'about.html')
Did you know that Christmas was yesterday? In Köln Mr and Mrs Meurer smile at the camera. The owners of the company Lautenschläger had to wait for the German-Peruvian for over an hour since he was stuck in traffic, but their good mood could not be broken by something like that! Similarly, as they did a dozen years ago, they will also send a very big present to Peru. The Steri in the background can sterilize four operation screens at once. This equates to a doubling of our sterilization team’s capacity. All above mentioned donations in kind and the solar batteries I wrote about on Tuesday make up a six-digit sum. I am in negotiations with five further companies. With his journey through the Ruhrgebiet Dr John completes his current tour through Europe. In the past week he visited nine companies/organisations in Germany and Switzerland. Thanks be to God that he completed the 3,300km along wintry roads safely. Mr and Mrs Meurer with their Christmas present. The question remains unanswered as to whether it was for Christmas 2018 or 2019.
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #################################################################### from swig_test_utils import * import time class MyTimeEvent(fife.TimeEvent): def __init__(self, period): fife.TimeEvent.__init__(self, period) self.counter = 0 def updateEvent(self, curtime): print "testing timer event... %d, %d" % (curtime, self.counter) self.counter += 1 class TestTimer(unittest.TestCase): def setUp(self): self.engine = getEngine(True) self.timemanager = self.engine.getTimeManager() def tearDown(self): self.engine.destroy() def testEvents(self): e = MyTimeEvent(100) self.timemanager.registerEvent(e) for i in xrange(10): time.sleep(0.1) self.timemanager.update() self.timemanager.unregisterEvent(e) TEST_CLASSES = [TestTimer] if __name__ == '__main__': unittest.main()
Flowers by Osuna Floral Studio – Welcome to PWG! We are very excited to now be working with Osuna Floral Studio! Located inside Osuna Nursery, Osuna Floral Studio offers unique and personalized flowers for special occasions and lasting memories. Their experienced staff offers an array of services with a palette of design inspired by Mother Nature herself. Whether your event is an intimate affair or a grand gala, their purpose is to plan and create floral designs that exceed their client’s expectations. They offer competitive pricing with the highest standards of quality that will leave a long-lasting impression. Check out some of their impressive designs below! Their passion is to create arrangements that are not only unique, but reflect the wishes of the client. Their skills range from vintage to modern, conceptual floral design and anywhere in between. Osuna Floral Studio offers complimentary and personalized wedding and event consultations to help you plan for your special event. Feel free to bring in photo examples of flowers that inspire you and/or a color theme. They are there to make the process as smooth as possible for you! to set an appointment at (505)345-6644. ‹ PreviousSanta Fe Engagement- Check out this adorable PWG Engagement Announcement! Next ›Bridal Elegance by Darlene – November Promotion!
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange authors. # # 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. """Module containing the RequestData object that will be created for each request in the GSoC module. """ from google.appengine.ext import db from soc.logic.exceptions import NotFound from soc.views.helper.access_checker import isSet from soc.views.helper import request_data from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.organization import GSoCOrganization from soc.modules.gsoc.models.timeline import GSoCTimeline class TimelineHelper(request_data.TimelineHelper): """Helper class for the determination of the currently active period. Methods ending with "On", "Start", or "End" return a date. Methods ending with "Between" return a tuple with two dates. Methods ending with neither return a Boolean. """ def currentPeriod(self): """Return where we are currently on the timeline. """ if not self.programActive(): return 'offseason' if self.beforeOrgSignupStart(): return 'kickoff_period' if self.afterStudentSignupStart(): return 'student_signup_period' if self.afterOrgSignupStart(): return 'org_signup_period' if self.studentsAnnounced(): return 'coding_period' return 'offseason' def nextDeadline(self): """Determines the next deadline on the timeline. Returns: A two-tuple containing deadline text and the datetime object for the next deadline """ if self.beforeOrgSignupStart(): return ("Org Application Starts", self.orgSignupStart()) # we do not have deadlines for any of those programs that are not active if not self.programActive(): return ("", None) if self.orgSignup(): return ("Org Application Deadline", self.orgSignupEnd()) if request_data.isBetween(self.orgSignupEnd(), self.orgsAnnouncedOn()): return ("Accepted Orgs Announced In", self.orgsAnnouncedOn()) if self.orgsAnnounced() and self.beforeStudentSignupStart(): return ("Student Application Opens", self.studentSignupStart()) if self.studentSignup(): return ("Student Application Deadline", self.studentSignupEnd()) if request_data.isBetween(self.studentSignupEnd(), self.applicationMatchedOn()): return ("Proposal Matched Deadline", self.applicationMatchedOn()) if request_data.isBetween(self.applicationMatchedOn(), self.applicationReviewEndOn()): return ("Proposal Scoring Deadline", self.applicationReviewEndOn()) if request_data.isBetween(self.applicationReviewEndOn(), self.studentsAnnouncedOn()): return ("Accepted Students Announced", self.studentsAnnouncedOn()) return ('', None) def studentsAnnouncedOn(self): return self.timeline.accepted_students_announced_deadline def studentsAnnounced(self): return request_data.isAfter(self.studentsAnnouncedOn()) def beforeStudentsAnnounced(self): return request_data.isBefore(self.studentsAnnouncedOn()) def applicationReviewEndOn(self): return self.timeline.application_review_deadline def applicationMatchedOn(self): return self.timeline.student_application_matched_deadline def mentorSignup(self): return self.programActiveBetween() and self.orgsAnnounced() def afterFirstSurveyStart(self, surveys): """Returns True if we are past at least one survey has start date. Args: surveys: List of survey entities for which we need to determine if at least one of them have started """ first_survey_start = min([s.survey_start for s in surveys]) return request_data.isAfter(first_survey_start) class RequestData(request_data.RequestData): """Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) css_path: a part of the css to fetch the GSoC specific CSS resources program: The GSoC program entity that the request is pointing to programs: All GSoC programs. program_timeline: The GSoCTimeline entity timeline: A TimelineHelper entity is_host: is the current user a host of the program is_mentor: is the current user a mentor in the program is_student: is the current user a student in the program is_org_admin: is the current user an org admin in the program org_map: map of retrieved organizations org_admin_for: the organizations the current user is an admin for mentor_for: the organizations the current user is a mentor for student_info: the StudentInfo for the current user and program organization: the GSoCOrganization for the current url Raises: out_of_band: 404 when the program does not exist """ def __init__(self): """Constructs an empty RequestData object. """ super(RequestData, self).__init__() # module wide fields self.css_path = 'gsoc' # program wide fields self._programs = None self.program = None self.program_timeline = None self.org_app = None # user profile specific fields self.profile = None self.is_host = False self.is_mentor = False self.is_student = False self.is_org_admin = False self.org_map = {} self.mentor_for = [] self.org_admin_for = [] self.student_info = None self.organization = None @property def programs(self): """Memoizes and returns a list of all programs. """ from soc.modules.gsoc.models.program import GSoCProgram if not self._programs: self._programs = list(GSoCProgram.all()) return self._programs def getOrganization(self, org_key): """Retrieves the specified organization. """ if org_key not in self.org_map: org = db.get(org_key) self.org_map[org_key] = org return self.org_map[org_key] def orgAdminFor(self, organization): """Returns true iff the user is admin for the specified organization. Organization may either be a key or an organization instance. """ if self.is_host: return True if isinstance(organization, db.Model): organization = organization.key() return organization in [i.key() for i in self.org_admin_for] def mentorFor(self, organization): """Returns true iff the user is mentor for the specified organization. Organization may either be a key or an organization instance. """ if self.is_host: return True if isinstance(organization, db.Model): organization = organization.key() return organization in [i.key() for i in self.mentor_for] def isPossibleMentorForProposal(self, mentor_profile=None): """Checks if the user is a possible mentor for the proposal in the data. """ assert isSet(self.profile) assert isSet(self.proposal) profile = mentor_profile if mentor_profile else self.profile return profile.key() in self.proposal.possible_mentors def populate(self, redirect, request, args, kwargs): """Populates the fields in the RequestData object. Args: request: Django HTTPRequest object. args & kwargs: The args and kwargs django sends along. """ super(RequestData, self).populate(redirect, request, args, kwargs) if kwargs.get('sponsor') and kwargs.get('program'): program_key_name = "%s/%s" % (kwargs['sponsor'], kwargs['program']) program_key = db.Key.from_path('GSoCProgram', program_key_name) else: from soc.models.site import Site program_key = Site.active_program.get_value_for_datastore(self.site) program_key_name = program_key.name() import logging logging.error("No program specified") timeline_key = db.Key.from_path('GSoCTimeline', program_key_name) org_app_key_name = 'gsoc_program/%s/orgapp' % program_key_name org_app_key = db.Key.from_path('OrgAppSurvey', org_app_key_name) keys = [program_key, timeline_key, org_app_key] self.program, self.program_timeline, self.org_app = db.get(keys) if not self.program: raise NotFound("There is no program for url '%s'" % program_key_name) self.timeline = TimelineHelper(self.program_timeline, self.org_app) if kwargs.get('organization'): fields = [self.program.key().id_or_name(), kwargs.get('organization')] org_key_name = '/'.join(fields) self.organization = GSoCOrganization.get_by_key_name(org_key_name) if not self.organization: raise NotFound("There is no organization for url '%s'" % org_key_name) if self.user: key_name = '%s/%s' % (self.program.key().name(), self.user.link_id) self.profile = GSoCProfile.get_by_key_name( key_name, parent=self.user) from soc.modules.gsoc.models.program import GSoCProgram host_key = GSoCProgram.scope.get_value_for_datastore(self.program) self.is_host = host_key in self.user.host_for if self.profile: org_keys = set(self.profile.mentor_for + self.profile.org_admin_for) prop = GSoCProfile.student_info student_info_key = prop.get_value_for_datastore(self.profile) if student_info_key: self.student_info = db.get(student_info_key) self.is_student = True else: orgs = db.get(org_keys) org_map = self.org_map = dict((i.key(), i) for i in orgs) self.mentor_for = org_map.values() self.org_admin_for = [org_map[i] for i in self.profile.org_admin_for] self.is_org_admin = self.is_host or bool(self.org_admin_for) self.is_mentor = self.is_org_admin or bool(self.mentor_for) class RedirectHelper(request_data.RedirectHelper): """Helper for constructing redirects. """ def review(self, id=None, student=None): """Sets the kwargs for an url_patterns.REVIEW redirect. """ if not student: assert 'user' in self._data.kwargs student = self._data.kwargs['user'] self.id(id) self.kwargs['user'] = student return self def invite(self, role=None): """Sets args for an url_patterns.INVITE redirect. """ if not role: assert 'role' in self._data.kwargs role = self._data.kwargs['role'] self.organization() self.kwargs['role'] = role return self def orgApp(self, survey=None): """Sets kwargs for an url_patterns.SURVEY redirect for org application. """ if not survey: assert 'survey' in self._data.kwargs survey = self._data.kwargs['survey'] self.organization() self.kwargs['survey'] = survey def document(self, document): """Override this method to set GSoC specific _url_name. """ super(RedirectHelper, self).document(document) self._url_name = 'show_gsoc_document' return self def acceptedOrgs(self): """Sets the _url_name to the list all the accepted orgs. """ super(RedirectHelper, self).acceptedOrgs() self._url_name = 'gsoc_accepted_orgs' return self def allProjects(self): """Sets the _url_name to list all GSoC projects. """ self.program() self._url_name = 'gsoc_accepted_projects' return self def homepage(self): """Sets the _url_name for the homepage of the current GSOC program. """ super(RedirectHelper, self).homepage() self._url_name = 'gsoc_homepage' return self def searchpage(self): """Sets the _url_name for the searchpage of the current GSOC program. """ super(RedirectHelper, self).searchpage() self._url_name = 'search_gsoc' return self def orgHomepage(self, link_id): """Sets the _url_name for the specified org homepage """ super(RedirectHelper, self).orgHomepage(link_id) self._url_name = 'gsoc_org_home' return self def dashboard(self): """Sets the _url_name for dashboard page of the current GSOC program. """ super(RedirectHelper, self).dashboard() self._url_name = 'gsoc_dashboard' return self def events(self): """Sets the _url_name for the events page, if it is set. """ from soc.modules.gsoc.models.program import GSoCProgram key = GSoCProgram.events_page.get_value_for_datastore(self._data.program) if not key: self._clear() self._no_url = True self.program() self._url_name = 'gsoc_events' return self def request(self, request): """Sets the _url_name for a request. """ assert request self.id(request.key().id()) if request.type == 'Request': self._url_name = 'show_gsoc_request' else: self._url_name = 'gsoc_invitation' return self def comment(self, comment, full=False, secure=False): """Creates a direct link to a comment. """ review = comment.parent() self.review(review.key().id_or_name(), review.parent().link_id) url = self.urlOf('review_gsoc_proposal', full=full, secure=secure) return "%s#c%s" % (url, comment.key().id()) def project(self, id=None, student=None): """Returns the URL to the Student Project. Args: student: entity which represents the user for the student """ if not student: assert 'user' in self._data.kwargs student = self._data.kwargs['user'] self.id(id) self.kwargs['user'] = student return self def survey(self, survey=None): """Sets kwargs for an url_patterns.SURVEY redirect. Args: survey: the survey's link_id """ self.program() if not survey: assert 'survey' in self._data.kwargs survey = self._data.kwargs['survey'] self.kwargs['survey'] = survey return self def survey_record(self, survey=None, id=None, student=None): """Returns the redirector object with the arguments for survey record Args: survey: the survey's link_id """ self.program() self.project(id, student) if not survey: assert 'survey' in self._data.kwargs survey = self._data.kwargs['survey'] self.kwargs['survey'] = survey return self def grading_record(self, record): """Returns the redirector object with the arguments for grading record Args: record: the grading record entity """ self.program() project = record.parent() self.project(project.key().id(), project.parent().link_id) self.kwargs['group'] = record.grading_survey_group.key().id_or_name() self.kwargs['record'] = record.key().id() return self def editProfile(self, profile): """Returns the URL for the edit profile page for the given profile. """ self.program() self._url_name = 'edit_gsoc_profile' return self
A crossover musical. This is what public television of Israel, KAN, intends to do with singers and topics musicals during the semifinals of Eurovision 2019 that will be held in Tel Aviv next May 14 and 16. Many well-known names for eurofans Y Absolute silence about the possible performance of Madonna in the grand finale of May 18. Today they have made public in a press conference what performances will delight the attendees and viewers of Eurovision 2019. And not only the artists have been chosen for having won the Festival but also for their popularity among the fans of this musical contest. that left Cyprus skimming the victory last year. The renovated Conchita Wurst will sing in turn the theme with which Zelmerlöw won Eurovision 2015, Heroes. The explosive Eleni Foureira, who sang Fire last year it will change to a much more moved genre interpreting the theme of Ukraine 2007, Dancing Lasha Tumbai. Verka Serduchka will sing the theme that gave Israel the victory last year: Toy. Gali Atari to interpret Hallelujah, the song with which Israel won the festival for the second time in a row in 1979. Netta will release a new version of Toy and the winner of 1998, Dana International he will also be present.
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source, # Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package. import sys from functools import partial from qtpy import QtGui from qtpy.QtCore import QVariant, Qt, Signal, Slot from qtpy.QtGui import QKeySequence, QStandardItemModel from qtpy.QtWidgets import (QAction, QHeaderView, QItemEditorFactory, QMenu, QMessageBox, QStyledItemDelegate, QTableView) import mantidqt.icons from mantidqt.widgets.workspacedisplay.table.plot_type import PlotType class PreciseDoubleFactory(QItemEditorFactory): def __init__(self): QItemEditorFactory.__init__(self) def createEditor(self, user_type, parent): widget = super(PreciseDoubleFactory, self).createEditor(user_type, parent) if user_type == QVariant.Double: widget.setFrame(True) widget.setDecimals(16) widget.setRange(-sys.float_info.max, sys.float_info.max) return widget class TableWorkspaceDisplayView(QTableView): repaint_signal = Signal() def __init__(self, presenter=None, parent=None, window_flags=Qt.Window, table_model=None): super().__init__(parent) self.table_model = table_model if table_model else QStandardItemModel(parent) self.setModel(self.table_model) self.presenter = presenter self.COPY_ICON = mantidqt.icons.get_icon("mdi.content-copy") self.DELETE_ROW = mantidqt.icons.get_icon("mdi.minus-box-outline") item_delegate = QStyledItemDelegate(self) item_delegate.setItemEditorFactory(PreciseDoubleFactory()) self.setItemDelegate(item_delegate) self.setAttribute(Qt.WA_DeleteOnClose, True) self.repaint_signal.connect(self._run_repaint) header = self.horizontalHeader() header.sectionDoubleClicked.connect(self.handle_double_click) self.setWindowFlags(window_flags) def columnCount(self): return self.table_model.columnCount() def rowCount(self): return self.table_model.rowCount() def subscribe(self, presenter): """ :param presenter: A reference to the controlling presenter """ self.presenter = presenter def resizeEvent(self, event): super().resizeEvent(event) header = self.horizontalHeader() # resizes the column headers to fit the contents, # currently this overwrites any manual changes to the widths of the columns header.resizeSections(QHeaderView.ResizeToContents) # then allows the users to resize the headers manually header.setSectionResizeMode(QHeaderView.Interactive) def emit_repaint(self): self.repaint_signal.emit() @Slot() def _run_repaint(self): self.viewport().update() def handle_double_click(self, section): header = self.horizontalHeader() header.resizeSection(section, header.defaultSectionSize()) def keyPressEvent(self, event): if event.matches(QKeySequence.Copy): self.presenter.action_keypress_copy() return elif event.key() in (Qt.Key_F2, Qt.Key_Return, Qt.Key_Enter): self.edit(self.currentIndex()) return def set_context_menu_actions(self, table): """ Sets up the context menu actions for the table :type table: QTableView :param table: The table whose context menu actions will be set up. :param ws_read_function: The read function used to efficiently retrieve data directly from the workspace """ copy_action = QAction(self.COPY_ICON, "Copy", table) copy_action.triggered.connect(self.presenter.action_copy_cells) table.setContextMenuPolicy(Qt.ActionsContextMenu) table.addAction(copy_action) horizontalHeader = table.horizontalHeader() horizontalHeader.setContextMenuPolicy(Qt.CustomContextMenu) horizontalHeader.customContextMenuRequested.connect(self.custom_context_menu) verticalHeader = table.verticalHeader() verticalHeader.setContextMenuPolicy(Qt.ActionsContextMenu) verticalHeader.setSectionResizeMode(QHeaderView.Fixed) copy_spectrum_values = QAction(self.COPY_ICON, "Copy", verticalHeader) copy_spectrum_values.triggered.connect(self.presenter.action_copy_spectrum_values) delete_row = QAction(self.DELETE_ROW, "Delete Row", verticalHeader) delete_row.triggered.connect(self.presenter.action_delete_row) separator2 = self.make_separator(verticalHeader) verticalHeader.addAction(copy_spectrum_values) verticalHeader.addAction(separator2) verticalHeader.addAction(delete_row) def custom_context_menu(self, position): menu_main = QMenu() plot = QMenu("Plot...", menu_main) plot_line = QAction("Line", plot) plot_line.triggered.connect(partial(self.presenter.action_plot, PlotType.LINEAR)) plot_line_with_yerr = QAction("Line with Y Errors", plot) plot_line_with_yerr.triggered.connect( partial(self.presenter.action_plot, PlotType.LINEAR_WITH_ERR)) plot_scatter = QAction("Scatter", plot) plot_scatter.triggered.connect(partial(self.presenter.action_plot, PlotType.SCATTER)) plot_scatter_with_yerr = QAction("Scatter with Y Errors", plot) plot_scatter_with_yerr.triggered.connect( partial(self.presenter.action_plot, PlotType.SCATTER_WITH_ERR)) plot_line_and_points = QAction("Line + Symbol", plot) plot_line_and_points.triggered.connect( partial(self.presenter.action_plot, PlotType.LINE_AND_SYMBOL)) plot.addAction(plot_line) plot.addAction(plot_line_with_yerr) plot.addAction(plot_scatter) plot.addAction(plot_scatter_with_yerr) plot.addAction(plot_line_and_points) menu_main.addMenu(plot) copy_bin_values = QAction(self.COPY_ICON, "Copy", menu_main) copy_bin_values.triggered.connect(self.presenter.action_copy_bin_values) set_as_x = QAction("Set as X", menu_main) set_as_x.triggered.connect(self.presenter.action_set_as_x) set_as_y = QAction("Set as Y", menu_main) set_as_y.triggered.connect(self.presenter.action_set_as_y) set_as_none = QAction("Set as None", menu_main) set_as_none.triggered.connect(self.presenter.action_set_as_none) statistics_on_columns = QAction("Statistics on Columns", menu_main) statistics_on_columns.triggered.connect(self.presenter.action_statistics_on_columns) hide_selected = QAction("Hide Selected", menu_main) hide_selected.triggered.connect(self.presenter.action_hide_selected) show_all_columns = QAction("Show All Columns", menu_main) show_all_columns.triggered.connect(self.presenter.action_show_all_columns) sort_ascending = QAction("Sort Ascending", menu_main) sort_ascending.triggered.connect(partial(self.presenter.action_sort, True)) sort_descending = QAction("Sort Descending", menu_main) sort_descending.triggered.connect(partial(self.presenter.action_sort, False)) menu_main.addAction(copy_bin_values) menu_main.addAction(self.make_separator(menu_main)) menu_main.addAction(set_as_x) menu_main.addAction(set_as_y) marked_y_cols = self.presenter.get_columns_marked_as_y() num_y_cols = len(marked_y_cols) # If any columns are marked as Y then generate the set error menu if num_y_cols > 0: menu_set_as_y_err = QMenu("Set error for Y...") for label_index in range(num_y_cols): set_as_y_err = QAction("Y{}".format(label_index), menu_main) # This is the column index of the Y column for which a YERR column is being added. # The column index is relative to the whole table, this is necessary # so that later the data of the column marked as error can be retrieved related_y_column = marked_y_cols[label_index] # label_index here holds the index in the LABEL (multiple Y columns have labels Y0, Y1, YN...) # this is NOT the same as the column relative to the WHOLE table set_as_y_err.triggered.connect( partial(self.presenter.action_set_as_y_err, related_y_column)) menu_set_as_y_err.addAction(set_as_y_err) menu_main.addMenu(menu_set_as_y_err) menu_main.addAction(set_as_none) menu_main.addAction(self.make_separator(menu_main)) menu_main.addAction(statistics_on_columns) menu_main.addAction(self.make_separator(menu_main)) menu_main.addAction(hide_selected) menu_main.addAction(show_all_columns) menu_main.addAction(self.make_separator(menu_main)) menu_main.addAction(sort_ascending) menu_main.addAction(sort_descending) menu_main.exec_(self.mapToGlobal(position)) def make_separator(self, horizontalHeader): separator1 = QAction(horizontalHeader) separator1.setSeparator(True) return separator1 @staticmethod def copy_to_clipboard(data): """ Uses the QGuiApplication to copy to the system clipboard. :type data: str :param data: The data that will be copied to the clipboard :return: """ cb = QtGui.QGuiApplication.clipboard() cb.setText(data, mode=cb.Clipboard) def ask_confirmation(self, message, title="Mantid Workbench"): """ :param message: :return: """ reply = QMessageBox.question(self, title, message, QMessageBox.Yes, QMessageBox.No) return True if reply == QMessageBox.Yes else False def show_warning(self, message, title="Mantid Workbench"): QMessageBox.warning(self, title, message)
Every time federal taxes have been cut–without exception, as far as I know–part of the deal has been that the overall tax structure becomes more progressive. That was the case with the Reagan tax cuts of the early 1980s and the Bush tax cuts of the early 2000s. In both cases, upper-income taxpayers wound up paying a larger share of the tax burden. The result is that today, the United States has the most progressive personal tax structure of any developed country. We rely on our upper-income taxpayers to pay the bills more than anyone else. Senate Republicans would take a page from President Obama’s own fiscal commission and freeze salaries for federal civilian employees for three years. That would amount to a five-year pay freeze in total, given that a two-year policy is already in effect. The plan would also accelerate the Simpson-Bowles framework for reducing the number of government employees by 10 percent, by only allowing the hiring of one new employee for every three who leave the federal workforce. Simpson-Bowles would have mandated that the government only hire two employees for every three that departed. Republicans also incorporated means testing for a host of federal programs in their proposal, including for food stamps, unemployment benefits and Medicare. In all, the GOP plan includes roughly $230 billion in cost savings – enough, Republicans say, to pay for another year of the current 2 percentage point reduction in workers’ payroll taxes and reduce the deficit by $111 billion. Some say that the most significant aspect of the consensus in favor of extending the payroll tax holiday–which I think is likely to be enacted into law–is that Social Security has been fatally undermined by visibly decoupling contributions from benefits. Quite a few liberals have objected to the payroll tax cut on that ground. They may be right, but I doubt it. Any relationship between taxes and benefits has long since gone by the boards. Federal spending has become an unprincipled money-grab, much like when, in a parade, clowns walk down the street and throw candy into the crowd, and children scramble after it. When a compromise payroll tax bill passes Congress the result inevitably will be that our tax system has gotten a little more progressive. Which is to say, a little more unfair.
from microbit import * import random letters = ['A', 'B'] def get_letter(): return random.choice(letters) display.scroll("RAINMAN") display.scroll('Press any button to play', wait=False, loop=True) while True: if button_a.is_pressed() or button_b.is_pressed(): print("start playing") break display.clear() seq_length = 3 round = 1 pause = 500 correct = True def init(): global seq_length, round, pause, correct seq_length = 3 round = 1 pause = 500 correct = True display.clear() init() while True: # Draw seperator for y in range(0, 5): display.set_pixel(2, y, 5) # Get sequence sequence = [] for i in range(0, seq_length): # Clear previous for x in range(0, 5): if x != 2: for y in range(0, 5): display.set_pixel(x, y, 0) sleep(pause) letter = get_letter() sequence.append(letter) print(letter) if letter == 'A': for x in range(0, 2): for y in range(0, 5): display.set_pixel(x, y, 9) elif letter == 'B': for x in range(3, 5): for y in range(0, 5): display.set_pixel(x, y, 9) sleep(500) display.clear() # Await input correct = True reset = False print("ENTERED:"); for letter in sequence: while correct: entered = "" if button_a.is_pressed() or button_b.is_pressed(): if button_a.is_pressed(): while button_a.is_pressed(): continue entered = "A" else: while button_b.is_pressed(): continue entered = "B" print ("%s:%s" % (letter, entered)) if entered != letter: correct = False else: break if not correct: display.scroll("X") display.scroll("You reached level: %d" % round, wait=False, loop=True) while True: if button_a.is_pressed() or button_b.is_pressed(): init() reset = True break if reset: break round += 1 seq_length += 1
The NHS Constitution provides information about your rights as an NHS patient. The NHS Constitution has been created to protect the NHS and make sure it will always do the things it was set up to do in 1948 – to provide high-quality healthcare that’s free for everyone. No government can change the NHS Constitution without the full involvement of staff, patients and the public. It is a promise that the NHS will always be there for you. The Constitution sets out your rights as an NHS patient. These rights cover how patients access health services, the quality of care you’ll receive, the treatments and programmes available to you, confidentiality, information and your right to complain when things go wrong.
import random import time import json from datetime import datetime from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound from pynYNAB.schema import AccountTypes from pynYNAB.schema.budget import Account, Payee def rate_limited(maxpersecond): minInterval = 1.0 / float(maxpersecond) def decorate(func): lastTimeCalled = [None] def rateLimitedFunction(*args, **kargs): if lastTimeCalled[0] is not None: elapsed = time.clock() - lastTimeCalled[0] leftToWait = minInterval - elapsed if leftToWait > 0: print('rate limiting, waiting %g...' % leftToWait) time.sleep(leftToWait) ret = func(*args, **kargs) lastTimeCalled[0] = time.clock() return ret return rateLimitedFunction return decorate def get_or_create_account(client, name): accounts = {a.account_name: a for a in client.budget.be_accounts if a.account_name == name} if name in accounts: return accounts[name] account = Account( account_type=AccountTypes.Checking, account_name=name ) client.add_account(account, balance=random.randint(-10, 10), balance_date=datetime.now()) return account def get_or_create_payee(client, name): payees = {p.name: p for p in client.budget.be_payees if p.name == name} if name in payees: return payees[name] payee = Payee( name=name ) client.budget.be_payees.append(payee) client.push(1) return payee def get_one_or_create(session, model, create_method='', create_method_kwargs=None, **kwargs): try: return session.query(model).filter_by(**kwargs).one(), False except NoResultFound: kwargs.update(create_method_kwargs or {}) created = getattr(model, create_method, model)(**kwargs) try: session.add(created) session.flush() return created, True except IntegrityError: session.rollback() return session.query(model).filter_by(**kwargs).one(), True # https://stackoverflow.com/a/37757378/1685379 def pp_json(json_thing, sort=True, indents=4): def d(t): return json.dumps(t, sort_keys=sort, indent=indents) return d(json.loads(json_thing)) if type(json_thing) is str else d(json_thing)
Emil Perška (20 June 1897–May 1945) was a Croatian footballer. He was born in Zagreb and spent the majority of his career with Građanski Zagreb, with whom he won three Yugoslav championships in the 1920s. He was also a member of the Yugoslav squad at the 1920, 1924 and 1928 Olympic tournaments. Born in Zagreb in present-day Croatia, Perška was a member of the Slovak ethnic minority. Following World War I Perška was wanted by the authorities as he was accused of desertion. Perška then escaped to Vienna to avoid arrest and it was there that he signed a professional contract with Građanski in 1919 before returning to the country. He was called up for Kingdom of Yugoslavia's first international tournament, at the 1920 Olympics in Antwerp, and he appeared in the country's first ever international match on 28 August 1920, a 7–0 defeat to Czechoslovakia. After the tournament Perška had signed for Parisian side CA Sports Généraux and had a brief spell with them before returning to Građanski in the early 1920s. During the 1920s Perška helped Građanski win three Yugoslav championship titles (1923, 1926 and 1928) and was called up to the national squad for the 1924 and 1928 Olympics, although he was unused at the 1928 tournament. He was capped 14 times and scored 2 international goals before retiring in 1929. After retirement Perška worked as a journalist and sports historian. He was allegedly a fervent supporter of the Ustaše movement during World War II, and was shot by the Yugoslav Partisans in May 1945 in Zagreb (like several other notable footballers such as Građanski's Dragutin Babić and Concordia's Slavko Pavletić). This page was last modified on 3 May 2016, at 17:53.
from __future__ import absolute_import, division, print_function, unicode_literals import json import logging from amaascore.assets.utils import json_to_asset from amaascore.config import ENVIRONMENT from amaascore.core.interface import Interface from amaascore.core.amaas_model import json_handler class AssetsInterface(Interface): def __init__(self, environment=ENVIRONMENT, endpoint=None, logger=None, username=None, password=None): self.logger = logger or logging.getLogger(__name__) super(AssetsInterface, self).__init__(endpoint=endpoint, endpoint_type='assets', environment=environment, username=username, password=password) def new(self, asset): self.logger.info('New Asset - Asset Manager: %s - Asset ID: %s', asset.asset_manager_id, asset.asset_id) url = '%s/assets/%s' % (self.endpoint, asset.asset_manager_id) response = self.session.post(url, json=asset.to_interface()) if response.ok: self.logger.info('Successfully Created Asset - Asset Manager: %s - Asset ID: %s', asset.asset_manager_id, asset.asset_id) asset = json_to_asset(response.json()) return asset else: self.logger.error(response.text) response.raise_for_status() def create_many(self, assets): if not assets or not isinstance(assets, list): raise ValueError('Invalid argument. Argument must be a non-empty list.') self.logger.info('New Assets - Asset Manager: %s', assets[0].asset_manager_id) url = '%s/assets/%s' % (self.endpoint, assets[0].asset_manager_id) json_body = [asset.to_interface() for asset in assets] response = self.session.post(url, json=json_body) if response.ok: self.logger.info('Successfully Created Assets - Asset Manager: %s', assets[0].asset_manager_id) t = response.json() assets = [asset for asset in response.json()] return assets else: self.logger.error(response.text) response.raise_for_status() def amend(self, asset): self.logger.info('Amend Asset - Asset Manager: %s - Asset ID: %s', asset.asset_manager_id, asset.asset_id) url = '%s/assets/%s/%s' % (self.endpoint, asset.asset_manager_id, asset.asset_id) response = self.session.put(url, json=asset.to_interface()) if response.ok: self.logger.info('Successfully Amended Asset - Asset Manager: %s - Asset ID: %s', asset.asset_manager_id, asset.asset_id) asset = json_to_asset(response.json()) return asset else: self.logger.error(response.text) response.raise_for_status() def partial(self, asset_manager_id, asset_id, updates): self.logger.info('Partial Amend Asset - Asset Manager: %s - Asset ID: %s', asset_manager_id, asset_id) url = '%s/assets/%s/%s' % (self.endpoint, asset_manager_id, asset_id) # Setting handler ourselves so we can be sure Decimals work response = self.session.patch(url, data=json.dumps(updates, default=json_handler), headers=self.json_header) if response.ok: asset = json_to_asset(response.json()) return asset else: self.logger.error(response.text) response.raise_for_status() def retrieve(self, asset_manager_id, asset_id, version=None): self.logger.info('Retrieve Asset - Asset Manager: %s - Asset ID: %s', asset_manager_id, asset_id) url = '%s/assets/%s/%s' % (self.endpoint, asset_manager_id, asset_id) if version: url += '?version=%d' % int(version) response = self.session.get(url) if response.ok: self.logger.info('Successfully Retrieved Asset - Asset Manager: %s - Asset ID: %s', asset_manager_id, asset_id) return json_to_asset(response.json()) else: self.logger.error(response.text) response.raise_for_status() def deactivate(self, asset_manager_id, asset_id): self.logger.info('Deactivate Asset - Asset Manager: %s - Asset ID: %s', asset_manager_id, asset_id) url = '%s/assets/%s/%s' % (self.endpoint, asset_manager_id, asset_id) json = {'asset_status': 'Inactive'} response = self.session.patch(url, json=json) if response.ok: self.logger.info('Successfully Deactivated Asset - Asset Manager: %s - Asset ID: %s', asset_manager_id, asset_id) return json_to_asset(response.json()) else: self.logger.error(response.text) response.raise_for_status() def search(self, asset_manager_ids=None, asset_ids=None, asset_classes=None, asset_types=None, page_no=None, page_size=None): self.logger.info('Search for Assets - Asset Manager(s): %s', asset_manager_ids) search_params = {} # Potentially roll this into a loop through args rather than explicitly named - depends on additional validation if asset_manager_ids: search_params['asset_manager_ids'] = ','.join([str(amid) for amid in asset_manager_ids]) if asset_ids: search_params['asset_ids'] = ','.join(asset_ids) if asset_classes: search_params['asset_classes'] = ','.join(asset_classes) if asset_types: search_params['asset_types'] = ','.join(asset_types) if page_no is not None: search_params['page_no'] = page_no if page_size: search_params['page_size'] = page_size url = self.endpoint + '/assets' response = self.session.get(url, params=search_params) if response.ok: assets = [json_to_asset(json_asset) for json_asset in response.json()] self.logger.info('Returned %s Assets.', len(assets)) return assets else: self.logger.error(response.text) response.raise_for_status() def fields_search(self, asset_manager_ids=None, asset_ids=None, asset_classes=None, asset_types=None, fields=None, page_no=None, page_size=None): self.logger.info('Search for Assets - Asset Manager(s): %s', asset_manager_ids) search_params = {} if asset_manager_ids: search_params['asset_manager_ids'] = ','.join([str(amid) for amid in asset_manager_ids]) if asset_ids: search_params['asset_ids'] = ','.join(asset_ids) if asset_classes: search_params['asset_classes'] = ','.join(asset_classes) if asset_types: search_params['asset_types'] = ','.join(asset_types) if fields: search_params['fields'] = ','.join(fields) if page_no is not None: search_params['page_no'] = page_no if page_size: search_params['page_size'] = page_size url = self.endpoint + '/assets' response = self.session.get(url, params=search_params) if response.ok: asset_dicts = response.json() self.logger.info('Returned %s Assets.', len(asset_dicts)) return asset_dicts else: self.logger.error(response.text) response.raise_for_status() def assets_by_asset_manager(self, asset_manager_id): self.logger.info('Retrieve Assets By Asset Manager: %s', asset_manager_id) url = '%s/assets/%s' % (self.endpoint, asset_manager_id) response = self.session.get(url) if response.ok: assets = [json_to_asset(json_asset) for json_asset in response.json()] self.logger.info('Returned %s Assets.', len(assets)) return assets else: self.logger.error(response.text) response.raise_for_status() def clear(self, asset_manager_id): """ This method deletes all the data for an asset_manager_id. It should be used with extreme caution. In production it is almost always better to Inactivate rather than delete. """ self.logger.info('Clear Assets - Asset Manager: %s', asset_manager_id) url = '%s/clear/%s' % (self.endpoint, asset_manager_id) response = self.session.delete(url) if response.ok: count = response.json().get('count', 'Unknown') self.logger.info('Deleted %s Assets.', count) return count else: self.logger.error(response.text) response.raise_for_status()
With more than 10 years of experience in quality management and handling vehicle OEM, this U.S based business enterprise dealing in high tech innovative solutions has proved to be a benchmark for the global leaders. Their expertise in various fields such as information technology, transportation, mechanical engineering, industrial OEM (Original Equipment Manufacturing), MRO (Manufacturing and Repair Operations), distribution, manufacturing, supply, logistics and retail sectors has made them emerge as business leaders in their domain. They wanted the best and fastest custom search result for vehicle parts supplier. Our technical team followed in depth research and development that to offer a customized search from a micro to macro part of vehicle. e-Zest came out with a search engine that fetches the information regarding part details, manufacturer, description, category etc based on Apache Solr. We developed the customized search engine successfully with a database for more than 9 million vehicle parts which is growing continuously. Also, it proved as the better approach for optimization of the content, internal links and effective title tags. The premium features designed specifically for automotive e-Commerce, can get the products online fast and allows the customers to find them faster. It also helps in getting the best alternate solutions for parts with the contact details of the local sellers and map for easy access to local store locations. Apache Solr being an open source technology served as a useful tool in the big data revolution with analyzers, indexing, and advanced search features. The search engine proved as the best solution and reflected with positive escalations in client’s business with many business benefits. e-Zest delivered a comprehensive search solution and helped the client move away from manual search solution and empowered them to grow their business multiple folds in short time. e-Zest is committed to protecting your data. We have designed robust controls to safeguard your data from unauthorized collection, use and disclosure.
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## - Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## - Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## - Neither the name of the New York University nor the names of its ## contributors may be used to endorse or promote products derived from ## this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ############################################################################### """ This is a QGraphicsView for pipeline view, it also holds different types of graphics items that are only available in the pipeline view. It only handles GUI-related actions, the rest of the functionalities are implemented at somewhere else, e.g. core.vistrails QGraphicsConnectionItem QGraphicsPortItem QGraphicsConfigureItem QGraphicsModuleItem QPipelineScene QPipelineView """ from __future__ import division from PyQt4 import QtCore, QtGui from vistrails.core.configuration import get_vistrails_configuration from vistrails.core import debug from vistrails.core.data_structures.graph import GraphContainsCycles from vistrails.core.db.action import create_action from vistrails.core.system import systemType from vistrails.core.modules.module_registry import get_module_registry, \ ModuleRegistryException, MissingPackage from vistrails.core.system import get_vistrails_basic_pkg_id from vistrails.core.vistrail.location import Location from vistrails.core.vistrail.module import Module from vistrails.core.vistrail.module_function import ModuleFunction from vistrails.core.vistrail.module_param import ModuleParam from vistrails.core.vistrail.port import PortEndPoint from vistrails.core.vistrail.port_spec import PortSpec from vistrails.core.interpreter.base import AbortExecution from vistrails.core.interpreter.default import get_default_interpreter from vistrails.core.utils import VistrailsDeprecation from vistrails.gui.base_view import BaseView from vistrails.gui.controlflow_assist import QControlFlowAssistDialog from vistrails.gui.graphics_view import (QInteractiveGraphicsScene, QInteractiveGraphicsView, QGraphicsItemInterface) from vistrails.gui.module_info import QModuleInfo from vistrails.gui.module_palette import QModuleTreeWidget from vistrails.gui.modules.utils import get_widget_class from vistrails.gui.ports_pane import Parameter from vistrails.gui.theme import CurrentTheme from vistrails.gui.utils import getBuilderWindow from vistrails.gui.variable_dropbox import QDragVariableLabel import copy import math import operator import string import warnings import vistrails.api import vistrails.gui.utils ############################################################################## # 2008-06-24 cscheid # # - Profiling has shown that calling setPen and setBrush takes a longer # time than we expected. Watch out for that in the future. ############################################################################## # QAbstractGraphicsPortItem class QAbstractGraphicsPortItem(QtGui.QAbstractGraphicsShapeItem): """ QAbstractGraphicsPortItem represents a port shape drawing on top (a child) of QGraphicsModuleItem, it must be implemented by a specific qgraphicsitem type. """ def __init__(self, port, x, y, ghosted=False, parent=None, union_group=None): """ QAbstractGraphicsPortItem(port: PortSpec, x: float, y: float, ghosted: bool, union: [PortSpec], parent: QGraphicsItem) -> QAbstractGraphicsPortItem Create the shape, initialize its pen and brush accordingly """ # local lookups are faster than global lookups.. self._rect = CurrentTheme.PORT_RECT.translated(x,y) QtGui.QAbstractGraphicsShapeItem.__init__(self, parent) self.setZValue(1) self.setFlags(QtGui.QGraphicsItem.ItemIsSelectable) self.controller = None self.port = port self.union_group = union_group self.dragging = False self.tmp_connection_item = None self.vistrail_vars = {} self.removeVarActions = [] if port is not None: self._min_conns = port.min_conns self._max_conns = port.max_conns self.optional = port.optional else: self._min_conns = 0 self._max_conns = -1 self.optional = False self._connected = 0 self._selected = False self.ghosted = ghosted self.invalid = False self.setPainterState() self.updateToolTip() self.updateActions() def getRect(self): return self._rect def boundingRect(self): return self._boundingRect def computeBoundingRect(self): halfpw = self.pen().widthF() / 2 self._boundingRect = self.getRect().adjusted(-halfpw, -halfpw, halfpw, halfpw) def getPosition(self): return self.sceneBoundingRect().center() def setPainterState(self): if self._selected: self._pen_color = CurrentTheme.PORT_PEN_COLOR_SELECTED elif self.ghosted: self._pen_color = CurrentTheme.PORT_PEN_COLOR_GHOSTED # self.setPen(CurrentTheme.GHOSTED_PORT_PEN) self.setBrush(CurrentTheme.GHOSTED_PORT_BRUSH) elif self.invalid: self._pen_color = CurrentTheme.PORT_PEN_COLOR_INVALID # self.setPen(CurrentTheme.INVALID_PORT_PEN) self.setBrush(CurrentTheme.INVALID_PORT_BRUSH) elif self._max_conns >= 0 and self._connected >= self._max_conns: self._pen_color = CurrentTheme.PORT_PEN_COLOR_FULL self.setBrush(CurrentTheme.PORT_BRUSH) else: self._pen_color = CurrentTheme.PORT_PEN_COLOR_NORMAL # self.setPen(CurrentTheme.PORT_PEN) self.setBrush(CurrentTheme.PORT_BRUSH) if self.brush() == CurrentTheme.PORT_BRUSH: if self._connected > 0: self.setBrush(CurrentTheme.PORT_CONNECTED_BRUSH) elif self._connected < self._min_conns: self.setBrush(CurrentTheme.PORT_MANDATORY_BRUSH) if self._selected: self._pen_width = CurrentTheme.PORT_PEN_WIDTH_SELECTED elif self._min_conns > 0 and self._connected < self._min_conns: self._pen_width = CurrentTheme.PORT_PEN_WIDTH_MANDATORY else: self._pen_width = CurrentTheme.PORT_PEN_WIDTH_NORMAL self.setPen(CurrentTheme.PORT_PENS[(self._pen_color, self._pen_width)]) self.computeBoundingRect() def setGhosted(self, ghosted): """ setGhosted(ghosted: True) -> None Set this link to be ghosted or not """ if self.ghosted <> ghosted: self.ghosted = ghosted self.setPainterState() def setInvalid(self, invalid): if self.invalid != invalid: self.invalid = invalid self.setPainterState() def setOptional(self, optional): if self.optional != optional: self.optional = optional self.setPainterState() def setSelected(self, selected): # QtGui.QAbstractGraphicsShapeItem.setSelected(self, selected) if self._selected != selected: self._selected = selected self.setPainterState() def disconnect(self): self._connected -= 1 # print "disconnecting", self._connected, self._min_conns, self._max_conns if self._connected == 0 or self._connected+1 == self._min_conns or \ (self._max_conns >= 0 and self._connected+1 == self._max_conns): self.setPainterState() def connect(self): self._connected += 1 # print "connecting", self._connected, self._min_conns, self._max_conns if self._connected == 1 or self._connected == self._min_conns or \ (self._max_conns >= 0 and self._connected == self._max_conns): self.setPainterState() def draw(self, painter, option, widget=None): raise NotImplementedError("Must implement draw method") def paint(self, painter, option, widget=None): painter.setPen(self.pen()) painter.setBrush(self.brush()) self.draw(painter, option, widget) def addVistrailVar(self, uuid, name=None): if name is None: name = self.getVistrailVarName(uuid) self.vistrail_vars[uuid] = name if not self.controller.has_vistrail_variable_with_uuid(uuid): self.setInvalid(True) self.updateActions() self.updateToolTip() def deleteVistrailVar(self, var_uuid): del self.vistrail_vars[var_uuid] self.updateActions() self.updateToolTip() def deleteAllVistrailVars(self): self.vistrail_vars = {} self.updateActions() self.updateToolTip() def getVistrailVarName(self, uuid): if self.controller.has_vistrail_variable_with_uuid(uuid): return self.controller.get_vistrail_variable_by_uuid(uuid).name return '<missing>' def updateToolTip(self): tooltip = "" if (self.port is not None and self.port.is_valid and hasattr(self.port, 'toolTip')): tooltip = self.port.toolTip(self.union_group) for vistrail_var in self.vistrail_vars.itervalues(): tooltip += '\nConnected to vistrail var "%s"' % vistrail_var self.setToolTip(tooltip) def contextMenuEvent(self, event): if len(self.removeVarActions) > 0: menu = QtGui.QMenu() for (action, _) in self.removeVarActions: menu.addAction(action) menu.exec_(event.screenPos()) event.accept() def updateActions(self): def gen_action(var_uuid): def remove_action(): self.removeVar(var_uuid) return remove_action for (action, callback) in self.removeVarActions: action.disconnect(action, QtCore.SIGNAL("triggered()"), callback) self.removeVarActions = [] if len(self.vistrail_vars) > 1: removeAllVarsAct = \ QtGui.QAction("Disconnect all vistrail variables", self.scene()) removeAllVarsAct.setStatusTip("Disconnects all vistrail" " variables from the port") QtCore.QObject.connect(removeAllVarsAct, QtCore.SIGNAL("triggered()"), self.removeAllVars) self.removeVarActions.append((removeAllVarsAct, self.removeAllVars)) for vistrail_var_uuid in sorted(self.vistrail_vars, key=lambda x: self.getVistrailVarName(x)): vistrail_var_name = self.getVistrailVarName(vistrail_var_uuid) removeVarAction = QtGui.QAction('Disconnect vistrail var "%s"' % \ vistrail_var_name, self.scene()) removeVarAction.setStatusTip('Disconnects vistrail variable "%s"' ' from the port' % vistrail_var_name) callback = gen_action(vistrail_var_uuid) QtCore.QObject.connect(removeVarAction, QtCore.SIGNAL("triggered()"), callback) self.removeVarActions.append((removeVarAction, callback)) def removeVar(self, var_uuid): (to_delete_modules, to_delete_conns) = \ self.controller.get_disconnect_vistrail_vars( \ self.parentItem().module, self.port.name, var_uuid) for conn in to_delete_conns: self.scene().remove_connection(conn.id) for module in to_delete_modules: self.scene().remove_module(module.id) self.deleteVistrailVar(var_uuid) self.controller.disconnect_vistrail_vars(to_delete_modules, to_delete_conns) self.setInvalid(False) def removeAllVars(self): # Get all connections to vistrail variables for this port (to_delete_modules, to_delete_conns) = \ self.controller.get_disconnect_vistrail_vars( \ self.parentItem().module, self.port.name) for conn in to_delete_conns: self.scene().remove_connection(conn.id) for module in to_delete_modules: self.scene().remove_module(module.id) self.deleteAllVistrailVars() self.controller.disconnect_vistrail_vars(to_delete_modules, to_delete_conns) def mousePressEvent(self, event): """ mousePressEvent(event: QMouseEvent) -> None Prepare for dragging a connection """ if (self.controller and event.buttons() & QtCore.Qt.LeftButton and not self.scene().read_only_mode): self.dragging = True self.setSelected(True) event.accept() QtGui.QAbstractGraphicsShapeItem.mousePressEvent(self, event) def mouseReleaseEvent(self, event): """ mouseReleaseEvent(event: QMouseEvent) -> None Apply the connection """ if self.tmp_connection_item: if self.tmp_connection_item.snapPortItem is not None: self.scene().addConnectionFromTmp(self.tmp_connection_item, self.parentItem().module, self.port.type == "output") self.tmp_connection_item.disconnect(True) self.scene().removeItem(self.tmp_connection_item) self.tmp_connection_item = None self.dragging = False self.setSelected(False) QtGui.QAbstractGraphicsShapeItem.mouseReleaseEvent(self, event) def mouseMoveEvent(self, event): """ mouseMoveEvent(event: QMouseEvent) -> None Change the connection """ if self.dragging: if not self.tmp_connection_item: z_val = max(self.controller.current_pipeline.modules) + 1 self.tmp_connection_item = \ QGraphicsTmpConnItem(self, self.union_group or [self], z_val, True) self.scene().addItem(self.tmp_connection_item) self.tmp_connection_item.setCurrentPos(event.scenePos()) snapPortItem = None snapPorts = None snapModule = self.scene().findModuleUnder(event.scenePos()) converters = [] if snapModule and snapModule != self.parentItem(): if self.port.type == 'output': portMatch = self.scene().findPortMatch( [self], set(snapModule.inputPorts.values()), fixed_out_pos=event.scenePos(), allow_conversion=True, out_converters=converters) if portMatch[1] is not None: snapPortItem = portMatch[1] snapPorts = portMatch[2] elif self.port.type == 'input': portMatch = self.scene().findPortMatch( snapModule.outputPorts.values(), [self], fixed_in_pos=event.scenePos(), allow_conversion=True, out_converters=converters) if portMatch[0] is not None: snapPortItem = portMatch[0] snapPorts = portMatch[0].port # select matching ports in input union self.tmp_connection_item.setStartPort(portMatch[1], portMatch[2]) self.tmp_connection_item.setSnapPort(snapPortItem, snapPorts) if snapPortItem: tooltip = self.tmp_connection_item.snapPortItem.toolTip() if converters: tooltip = ('<strong>conversion required</strong><br/>\n' '%s' % tooltip) QtGui.QToolTip.showText(event.screenPos(), tooltip) else: QtGui.QToolTip.hideText() self.tmp_connection_item.setConverting(snapPortItem and converters) QtGui.QAbstractGraphicsShapeItem.mouseMoveEvent(self, event) def findSnappedPort(self, pos): """ findSnappedPort(pos: QPoint) -> Port Search all ports of the module under mouse cursor (if any) to find the closest matched port """ # FIXME don't hardcode input/output strings... snapModule = self.scene().findModuleUnder(pos) if snapModule and snapModule!=self.parentItem(): if self.port.type == 'output': return snapModule.getDestPort(pos, self.port) elif self.port.type == 'input': return snapModule.getSourcePort(pos, self.port) else: return None def itemChange(self, change, value): """ itemChange(change: GraphicsItemChange, value: value) -> value Do not allow port to be selected """ if change==QtGui.QGraphicsItem.ItemSelectedChange and value: return False return QtGui.QAbstractGraphicsShapeItem.itemChange(self, change, value) ############################################################################## # QGraphicsPortItem class QGraphicsPortRectItem(QAbstractGraphicsPortItem): def draw(self, painter, option, widget=None): painter.drawRect(self.getRect()) class QGraphicsPortEllipseItem(QAbstractGraphicsPortItem): def draw(self, painter, option, widget=None): painter.drawEllipse(self.getRect()) class QGraphicsPortTriangleItem(QAbstractGraphicsPortItem): def __init__(self, *args, **kwargs): if 'angle' in kwargs: angle = kwargs['angle'] del kwargs['angle'] else: angle = 0 QAbstractGraphicsPortItem.__init__(self, *args, **kwargs) angle = angle % 360 if angle not in set([0,90,180,270]): raise ValueError("Triangle item limited to angles 0,90,180,270.") rect = self.getRect() if angle == 0 or angle == 180: width = rect.width() height = width * math.sqrt(3)/2.0 if height > rect.height(): height = rect.height() width = height * 2.0/math.sqrt(3) else: height = rect.height() width = height * math.sqrt(3)/2.0 if width > rect.width(): width = rect.width() height = width * 2.0/math.sqrt(3) left_x = (rect.width() - width)/2.0 + rect.x() right_x = (rect.width() + width) / 2.0 + rect.x() mid_x = rect.width() / 2.0 + rect.x() top_y = (rect.height() - height)/2.0 + rect.y() bot_y = (rect.height() + height)/2.0 + rect.y() mid_y = rect.height() / 2.0 + rect.y() if angle == 0: self._polygon = QtGui.QPolygonF([QtCore.QPointF(left_x, bot_y), QtCore.QPointF(mid_x, top_y), QtCore.QPointF(right_x, bot_y)]) elif angle == 90: self._polygon = QtGui.QPolygonF([QtCore.QPointF(left_x, bot_y), QtCore.QPointF(left_x, top_y), QtCore.QPointF(right_x, mid_y)]) elif angle == 180: self._polygon = QtGui.QPolygonF([QtCore.QPointF(left_x, top_y), QtCore.QPointF(right_x, top_y), QtCore.QPointF(mid_x, bot_y)]) elif angle == 270: self._polygon = QtGui.QPolygonF([QtCore.QPointF(left_x, mid_y), QtCore.QPointF(right_x, top_y), QtCore.QPointF(right_x, bot_y)]) def draw(self, painter, option, widget=None): painter.drawConvexPolygon(self._polygon) class QGraphicsPortPolygonItem(QAbstractGraphicsPortItem): def __init__(self, *args, **kwargs): if 'points' in kwargs: points = kwargs['points'] del kwargs['points'] else: points = None if points is None or len(points) < 3: raise ValueError("Must have at least three points") QAbstractGraphicsPortItem.__init__(self, *args, **kwargs) rect = self.getRect() new_points = [] for p in points: if p[0] is None: x = rect.x() + rect.width() # can't do +1 (2+ is fine) elif p[0] != 0 and p[0] > 0 and p[0] < 1.0001: x = rect.x() + rect.width() * p[0] elif p[0] < 0: x = rect.x() + rect.width() + p[0] else: x = rect.x() + p[0] if p[1] is None: y = rect.y() + rect.height() elif p[1] != 0 and p[1] > 0 and p[1] < 1.0001: y = rect.y() + rect.height() * p[1] elif p[1] < 0: y = rect.y() + rect.height() + p[1] else: y = rect.y() + p[1] if x < rect.x(): x = rect.x() # can't do +1 (2+ is fine) elif x > (rect.x() + rect.width()): x = rect.x() + rect.width() if y < rect.y(): y = rect.y() elif y > (rect.y() + rect.height()): y = rect.y() + rect.height() new_points.append(QtCore.QPointF(x,y)) self._polygon = QtGui.QPolygonF(new_points) def draw(self, painter, option, widget=None): painter.drawPolygon(self._polygon) class QGraphicsPortDiamondItem(QGraphicsPortPolygonItem): def __init__(self, *args, **kwargs): kwargs['points'] = [(0, 0.5), (0.5, 0.999999), (0.999999, 0.5), (0.5, 0)] QGraphicsPortPolygonItem.__init__(self, *args, **kwargs) ################################################################################ # QGraphicsConfigureItem class QGraphicsConfigureItem(QtGui.QGraphicsPolygonItem): """ QGraphicsConfigureItem is a small triangle shape drawing on top (a child) of QGraphicsModuleItem """ def __init__(self, parent=None, scene=None): """ QGraphicsConfigureItem(parent: QGraphicsItem, scene: QGraphicsScene) -> QGraphicsConfigureItem Create the shape, initialize its pen and brush accordingly """ _pen = CurrentTheme.CONFIGURE_PEN _brush = CurrentTheme.CONFIGURE_BRUSH _shape = CurrentTheme.CONFIGURE_SHAPE QtGui.QGraphicsPolygonItem.__init__(self, _shape, parent, scene) self.setZValue(1) self.setPen(_pen) self.setBrush(_brush) self.ghosted = False self.controller = None self.moduleId = None self.is_breakpoint = False self.createActions() def setGhosted(self, ghosted): """ setGhosted(ghosted: Bool) -> None Set this link to be ghosted or not """ if ghosted <> self.ghosted: self.ghosted = ghosted if ghosted: self.setPen(CurrentTheme.GHOSTED_CONFIGURE_PEN) self.setBrush(CurrentTheme.GHOSTED_CONFIGURE_BRUSH) else: self.setPen(CurrentTheme.CONFIGURE_PEN) self.setBrush(CurrentTheme.CONFIGURE_BRUSH) def setBreakpoint(self, breakpoint): if self.is_breakpoint != breakpoint: if breakpoint: self.setBreakpointAct.setText("Remove Breakpoint") self.setBreakpointAct.setStatusTip("Remove Breakpoint") else: self.setBreakpointAct.setText("Set Breakpoint") self.setBreakpointAct.setStatusTip("Set Breakpoint") def mousePressEvent(self, event): """ mousePressEvent(event: QMouseEvent) -> None Open the context menu """ self.scene().clearSelection() self.parentItem().setSelected(True) self.ungrabMouse() self.contextMenuEvent(event) event.accept() def contextMenuEvent(self, event): """contextMenuEvent(event: QGraphicsSceneContextMenuEvent) -> None Captures context menu event. """ module = self.controller.current_pipeline.modules[self.moduleId] menu = QtGui.QMenu() menu.addAction(self.configureAct) menu.addAction(self.annotateAct) menu.addAction(self.viewDocumentationAct) menu.addAction(self.changeModuleLabelAct) menu.addAction(self.editLoopingAct) menu.addAction(self.setBreakpointAct) menu.addAction(self.setWatchedAct) menu.addAction(self.runModuleAct) menu.addAction(self.setErrorAct) if module.is_abstraction() and not module.is_latest_version(): menu.addAction(self.upgradeAbstractionAct) menu.exec_(event.screenPos()) def createActions(self): """ createActions() -> None Create actions related to context menu """ self.configureAct = QtGui.QAction("Edit &Configuration\tCtrl+E", self.scene()) self.configureAct.setStatusTip("Edit the Configure of the module") QtCore.QObject.connect(self.configureAct, QtCore.SIGNAL("triggered()"), self.configure) self.annotateAct = QtGui.QAction("&Annotate", self.scene()) self.annotateAct.setStatusTip("Annotate the module") QtCore.QObject.connect(self.annotateAct, QtCore.SIGNAL("triggered()"), self.annotate) self.viewDocumentationAct = QtGui.QAction("View &Documentation", self.scene()) self.viewDocumentationAct.setStatusTip("View module documentation") QtCore.QObject.connect(self.viewDocumentationAct, QtCore.SIGNAL("triggered()"), self.viewDocumentation) self.editLoopingAct = QtGui.QAction("Execution &Options", self.scene()) self.editLoopingAct.setStatusTip("Edit module execution options") QtCore.QObject.connect(self.editLoopingAct, QtCore.SIGNAL("triggered()"), self.editLooping) self.changeModuleLabelAct = QtGui.QAction("Set Module &Label...", self.scene()) self.changeModuleLabelAct.setStatusTip("Set or remove module label") QtCore.QObject.connect(self.changeModuleLabelAct, QtCore.SIGNAL("triggered()"), self.changeModuleLabel) self.setBreakpointAct = QtGui.QAction("Set &Breakpoint", self.scene()) self.setBreakpointAct.setStatusTip("Set Breakpoint") QtCore.QObject.connect(self.setBreakpointAct, QtCore.SIGNAL("triggered()"), self.set_breakpoint) self.setWatchedAct = QtGui.QAction("&Watch Module", self.scene()) self.setWatchedAct.setStatusTip("Watch Module") QtCore.QObject.connect(self.setWatchedAct, QtCore.SIGNAL("triggered()"), self.set_watched) self.runModuleAct = QtGui.QAction("&Run this module", self.scene()) self.runModuleAct.setStatusTip("Run this module") QtCore.QObject.connect(self.runModuleAct, QtCore.SIGNAL("triggered()"), self.run_module) self.setErrorAct = QtGui.QAction("Show &Error", self.scene()) self.setErrorAct.setStatusTip("Show Error") QtCore.QObject.connect(self.setErrorAct, QtCore.SIGNAL("triggered()"), self.set_error) self.upgradeAbstractionAct = QtGui.QAction("&Upgrade Module", self.scene()) self.upgradeAbstractionAct.setStatusTip("Upgrade the subworkflow module") QtCore.QObject.connect(self.upgradeAbstractionAct, QtCore.SIGNAL("triggered()"), self.upgradeAbstraction) def run_module(self): self.scene().parent().execute(target=self.moduleId) def set_breakpoint(self): """ set_breakpoint() -> None Sets this module as a breakpoint for execution """ if self.moduleId >= 0: self.scene().toggle_breakpoint(self.moduleId) self.setBreakpoint(not self.is_breakpoint) debug = get_default_interpreter().debugger if debug: debug.update() def set_watched(self): if self.moduleId >= 0: self.scene().toggle_watched(self.moduleId) debug = get_default_interpreter().debugger if debug: debug.update() def set_error(self): if self.moduleId >= 0: self.scene().print_error(self.moduleId) def configure(self): """ configure() -> None Open the modal configuration window """ if self.moduleId>=0: self.scene().open_configure_window(self.moduleId) def annotate(self): """ anotate() -> None Open the annotations window """ if self.moduleId>=0: self.scene().open_annotations_window(self.moduleId) def viewDocumentation(self): """ viewDocumentation() -> None Show the documentation for the module """ assert self.moduleId >= 0 self.scene().open_documentation_window(self.moduleId) def editLooping(self): """ editLooping() -> None Show the looping options for the module """ assert self.moduleId >= 0 self.scene().open_looping_window(self.moduleId) def changeModuleLabel(self): """ changeModuleLabel() -> None Show the module label configuration widget """ if self.moduleId>=0: self.scene().open_module_label_window(self.moduleId) def upgradeAbstraction(self): """ upgradeAbstraction() -> None Upgrade the abstraction to the latest version """ if self.moduleId>=0: (connections_preserved, missing_ports) = self.controller.upgrade_abstraction_module(self.moduleId, test_only=True) upgrade_fail_prompt = getattr(get_vistrails_configuration(), 'upgradeModuleFailPrompt', True) do_upgrade = True if not connections_preserved and upgrade_fail_prompt: ports_msg = '\n'.join([" - %s port '%s'" % (p[0].capitalize(), p[1]) for p in missing_ports]) r = QtGui.QMessageBox.question(getBuilderWindow(), 'Modify Pipeline', 'Upgrading this module will change the pipeline because the following ports no longer exist in the upgraded module:\n\n' + ports_msg + '\n\nIf you proceed, function calls or connections to these ports will no longer exist and the pipeline may not execute properly.\n\n' 'Are you sure you want to proceed?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) do_upgrade = (r==QtGui.QMessageBox.Yes) if do_upgrade: self.controller.upgrade_abstraction_module(self.moduleId) self.scene().setupScene(self.controller.current_pipeline) self.controller.invalidate_version_tree() class QGraphicsTmpConnItem(QtGui.QGraphicsLineItem): def __init__(self, startPortItem, startPorts, zValue=1, alwaysDraw=False, parent=None): QtGui.QGraphicsLineItem.__init__(self, parent) self.startPortItem = startPortItem self.startPorts = startPorts self.setPen(CurrentTheme.CONNECTION_SELECTED_PEN) self.setZValue(zValue) self.snapPortItem = None self.snapPort = None self.alwaysDraw = alwaysDraw self.currentPos = None def updateLine(self): if self.startPortItem is not None: if self.snapPortItem is not None: self.prepareGeometryChange() self.setLine(QtCore.QLineF(self.startPortItem.getPosition(), self.snapPortItem.getPosition())) return elif self.alwaysDraw and self.currentPos is not None: self.prepareGeometryChange() self.setLine(QtCore.QLineF(self.startPortItem.getPosition(), self.currentPos)) return self.disconnect() def setStartPort(self, portItem, ports=None): self.startPortItem = portItem self.startPorts = ports self.updateLine() def setSnapPort(self, portItem, ports=None): self.snapPortItem = portItem self.snapPorts = ports self.updateLine() def setCurrentPos(self, pos): self.currentPos = pos self.updateLine() def disconnect(self, override=False): if (not self.alwaysDraw or override) and self.startPortItem: self.startPortItem.setSelected(False) if self.snapPortItem: self.snapPortItem.setSelected(False) def hide(self): self.disconnect(True) QtGui.QGraphicsLineItem.hide(self) def setConverting(self, converting): if converting: self.setPen(CurrentTheme.CONNECTION_SELECTED_CONVERTING_PEN) else: self.setPen(CurrentTheme.CONNECTION_SELECTED_PEN) ############################################################################## # QGraphicsConnectionItem class QGraphicsConnectionItem(QGraphicsItemInterface, QtGui.QGraphicsPathItem): """ QGraphicsConnectionItem is a connection shape connecting two port items """ def __init__(self, srcPortItem, dstPortItem, srcModule, dstModule, connection, parent=None): """ QGraphicsConnectionItem( srcPortItem, dstPortItem: QAbstractGraphicsPortItem srcModule, dstModule: QGraphicsModuleItem connection: core.vistrail.connection.Connection parent: QGraphicsItem ) -> QGraphicsConnectionItem Create the shape, initialize its pen and brush accordingly """ self.srcPortItem = srcPortItem self.dstPortItem = dstPortItem path = self.create_path(srcPortItem.getPosition(), dstPortItem.getPosition()) QtGui.QGraphicsPathItem.__init__(self, path, parent) self.setFlags(QtGui.QGraphicsItem.ItemIsSelectable) # Bump it slightly higher than the highest module self.setZValue(max(srcModule.id, dstModule.id) + 0.1) self.connectionPen = CurrentTheme.CONNECTION_PEN self.connectingModules = (srcModule, dstModule) self.ghosted = False self.connection = connection self.id = connection.id # Keep a flag for changing selection state during module selection self.useSelectionRules = True def setGhosted(self, ghosted): """ setGhosted(ghosted: True) -> None Set this link to be ghosted or not """ self.ghosted = ghosted if ghosted: self.connectionPen = CurrentTheme.GHOSTED_CONNECTION_PEN else: self.connectionPen = CurrentTheme.CONNECTION_PEN def set_custom_brush(self, brush): self.connectionPen = QtGui.QPen(CurrentTheme.CONNECTION_PEN) self.connectionPen.setBrush(brush) def paint(self, painter, option, widget=None): """ paint(painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget) -> None Peform actual painting of the connection """ if self.isSelected(): painter.setPen(CurrentTheme.CONNECTION_SELECTED_PEN) else: painter.setPen(self.connectionPen) painter.drawPath(self.path()) def setupConnection(self, startPos=None, endPos=None): path = self.create_path(startPos or self.startPos, endPos or self.endPos) self.setPath(path) def create_path(self, startPos, endPos): self.startPos = startPos self.endPos = endPos dx = abs(self.endPos.x() - self.startPos.x()) dy = (self.startPos.y() - self.endPos.y()) # This is reasonably ugly logic to get reasonably nice # curves. Here goes: we use a cubic bezier p0,p1,p2,p3, where: # p0 is the source port center # p3 is the destination port center # p1 is a control point displaced vertically from p0 # p2 is a control point displaced vertically from p3 # We want most curves to be "straight": they shouldn't bend # much. However, we want "inverted" connections (connections # that go against the natural up-down flow) to bend a little # as they go out of the ports. So the logic is: # As dy/dx -> oo, we want the control point displacement to go # to max(dy/2, m) (m is described below) # As dy/dx -> 0, we want the control point displacement to go # to m # As dy/dx -> -oo, we want the control point displacement to go # to max(-dy/2, m) # On points away from infinity, we want some smooth transition. # I'm using f(x) = 2/pi arctan (x) as the mapping, since: # f(-oo) = -1 # f(0) = 0 # f(oo) = 1 # m is the monotonicity breakdown point: this is the minimum # displacement when dy/dx is low m = float(CurrentTheme.MODULE_LABEL_MARGIN[0]) * 3.0 # positive_d and negative_d are the displacements when dy/dx is # large positive and large negative positive_d = max(m/3.0, dy / 2.0) negative_d = max(m/3.0, -dy / 4.0) if dx == 0.0: v = 0.0 else: w = math.atan(dy/dx) * (2 / math.pi) if w < 0: w = -w v = w * negative_d + (1.0 - w) * m else: v = w * positive_d + (1.0 - w) * m displacement = QtCore.QPointF(0.0, v) self._control_1 = startPos + displacement # !!! MAC OS X BUG !!! # the difference between startPos.y and control_1.y cannot be # equal to the difference between control_2.y and endPos.y self._control_2 = self.endPos - displacement + QtCore.QPointF(0.0, 1e-11) # self._control_2 = endPos - displacement # draw multiple connections depending on list depth def diff(i, depth): return QtCore.QPointF((5.0 + 10.0*i)/depth - 5.0, 0.0) srcParent = self.srcPortItem.parentItem() startDepth = srcParent.module.list_depth + 1 if srcParent else 1 dstParent = self.dstPortItem.parentItem() endDepth = dstParent.module.list_depth + 1 if dstParent else 1 starts = [diff(i, startDepth) for i in xrange(startDepth)] ends = [diff(i, endDepth) for i in xrange(endDepth)] first = True for start in starts: for end in ends: if first: path = QtGui.QPainterPath(self.startPos + start) first = False else: path.moveTo(self.startPos + start) path.cubicTo(self._control_1, self._control_2, self.endPos + end) return path def itemChange(self, change, value): """ itemChange(change: GraphicsItemChange, value: value) -> value If modules are selected, only allow connections between selected modules """ # Selection rules to be used only when a module isn't forcing # the update if (change==QtGui.QGraphicsItem.ItemSelectedChange and self.useSelectionRules): # Check for a selected module selectedItems = self.scene().selectedItems() selectedModules = False for item in selectedItems: if isinstance(item, QGraphicsModuleItem): selectedModules = True break if selectedModules: # Don't allow a connection between selected # modules to be deselected if (self.connectingModules[0].isSelected() and self.connectingModules[1].isSelected()): if not value: return True # Don't allow a connection to be selected if # it is not between selected modules else: if value: return False self.useSelectionRules = True return QtGui.QGraphicsPathItem.itemChange(self, change, value) ############################################################################## # QGraphicsModuleItem class QGraphicsModuleItem(QGraphicsItemInterface, QtGui.QGraphicsItem): """ QGraphicsModuleItem knows how to draw a Vistrail Module into the pipeline view. It is usually a rectangular shape with a bold text in the center. It also has its input/output port shapes as its children. Another remark is that connections are also children of module shapes. Each connection belongs to its source module ('output port' end of the connection) """ def __init__(self, parent=None, scene=None): """ QGraphicsModuleItem(parent: QGraphicsItem, scene: QGraphicsScene) -> QGraphicsModuleItem Create the shape, initialize its pen and brush accordingly """ QtGui.QGraphicsItem.__init__(self, parent, scene) self.paddedRect = QtCore.QRectF() if QtCore.QT_VERSION >= 0x40600: #Qt 4.6 specific flags self.setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemSendsGeometryChanges) else: self.setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable) self.setAcceptHoverEvents(True) self.setFlag(self.ItemIsFocusable) self.setZValue(0) self.labelFont = CurrentTheme.MODULE_FONT self.labelFontMetric = CurrentTheme.MODULE_FONT_METRIC self.descFont = CurrentTheme.MODULE_DESC_FONT self.descFontMetric = CurrentTheme.MODULE_DESC_FONT_METRIC self.modulePen = CurrentTheme.MODULE_PEN self.moduleBrush = CurrentTheme.MODULE_BRUSH self.labelPen = CurrentTheme.MODULE_LABEL_PEN self.customBrush = None self.statusBrush = None self.labelRect = QtCore.QRectF() self.descRect = QtCore.QRectF() self.abstRect = QtCore.QRectF() self.editRect = QtCore.QRectF() self.id = -1 self.label = '' self.description = '' self.inputPorts = {} self.outputPorts = {} self.union_ports = {} self.to_union = {} self.port_groups = [] self.controller = None self.module = None self.ghosted = False self.invalid = False self._module_shape = None self._original_module_shape = None self.errorTrace = None self.is_breakpoint = False self._needs_state_updated = True self.progress = 0.0 self.progressBrush = CurrentTheme.SUCCESS_MODULE_BRUSH self.connectionItems = {} self._cur_function_names = set() self.function_overview = '' self.show_widgets = get_vistrails_configuration( ).check('showInlineParameterWidgets') self.function_widgets = [] self.functions_widget = None self.edit_rect = QtCore.QRectF(0.0, 0.0, 0.0, 0.0) self.handlePositionChanges = True def moduleHasChanged(self, core_module): def module_text_has_changed(m1, m2): m1_has = '__desc__' in m1.db_annotations_key_index if m1_has != ('__desc__' in m2.db_annotations_key_index): return True if (m1_has and # m2_has, since m1_has and previous condition m1.db_annotations_key_index['__desc__'].value.strip()!= m2.db_annotations_key_index['__desc__'].value.strip()): return True return False # def module_functions_have_changed(m1, m2): # f1_names = set(f.name for f in m1.functions) # f2_names = set(f.name for f in m2.functions) # return (len(f1_names ^ f2_names) > 0) if not self.invalid and self.show_widgets != get_vistrails_configuration( ).check('showInlineParameterWidgets') and \ core_module.editable_input_ports: return True elif self.scenePos().x() != core_module.center.x or \ -self.scenePos().y() != core_module.center.y: return True elif module_text_has_changed(self.module, core_module): return True # elif module_functions_have_changed(self.module, core_module): # return True else: # check for changed edit widgets if not self.invalid and core_module.editable_input_ports != \ self.module.editable_input_ports: # shape has changed so we need to recreate the module return True # check for deleted edit widgets if self.functions_have_been_deleted(core_module): return True # Check for changed ports # _db_name because this shows up in the profile. cip = sorted([x.key_no_id() for x in self.inputPorts]) cop = sorted([x.key_no_id() for x in self.outputPorts]) d = PortEndPoint.Destination s = PortEndPoint.Source ipv = core_module.visible_input_ports opv = core_module.visible_output_ports new_ip = [] new_op = [] try: new_ip = sorted([x.key_no_id() for x in core_module.destinationPorts() if (not x.optional or x._db_name in ipv)]) new_op = sorted([x.key_no_id() for x in core_module.sourcePorts() if (not x.optional or x._db_name in opv)]) except ModuleRegistryException, e: debug.critical("MODULE REGISTRY EXCEPTION: %s" % e) if cip <> new_ip or cop <> new_op: return True return False def functions_have_been_deleted(self, core_module): # check if a visible function has been deleted if self.invalid: return set() before = self._cur_function_names after = set(f.name for f in core_module.functions) if self.invalid: return before - after else: return (before - after) & core_module.editable_input_ports def moduleFunctionsHaveChanged(self, core_module): m2 = core_module f2_names = set(f.name for f in m2.functions) return (len(self._cur_function_names ^ f2_names) > 0) def update_function_ports(self, core_module=None): if core_module is None: core_module = self.module added_functions = set(f.name for f in self.module.functions) deleted_functions = set() self._cur_function_names = copy.copy(added_functions) else: before_names = self._cur_function_names after_names = set(f.name for f in core_module.functions) added_functions = after_names - before_names deleted_functions = before_names - after_names self._cur_function_names = copy.copy(after_names) if len(deleted_functions) > 0: for function_name in deleted_functions: try: r_spec = self.module.get_port_spec(function_name, 'input') f_spec = PortSpec(id=-1, name=function_name, type=PortSpec.port_type_map['input'], sigstring=r_spec.sigstring) item = self.getInputPortItem(f_spec) if item is not None: item.disconnect() except Exception: pass if len(added_functions) > 0: for function in core_module.functions: if function.name not in added_functions: continue added_functions.remove(function.name) f_spec = PortSpec(id=-1, name=function.name, type=PortSpec.port_type_map['input'], sigstring=function.sigstring) item = self.getInputPortItem(f_spec) if item is not None: item.connect() self.module = core_module def update_function_values(self, core_module): """ Updates widget values if they have changed """ for function_widget in self.function_widgets: for f in core_module.functions: if f.name == function_widget.function.name: value = [p.strValue for p in f.params] if function_widget.getContents() != value: function_widget.setContents(value) continue def setProgress(self, progress): self.progress = progress def computeBoundingRect(self): """ computeBoundingRect() -> None Adjust the module size according to contents """ width = 0 height = CurrentTheme.MODULE_LABEL_MARGIN[1] # for each rect: Add height, adjust min width, # set pos to distance to top middle corner, to be adjusted when # paddedRect is known labelRect = self.labelFontMetric.boundingRect(self.label) labelRect.moveTo(-labelRect.width()//2, height) height += labelRect.height() padding = labelRect.adjusted(-CurrentTheme.MODULE_LABEL_MARGIN[0], 0, CurrentTheme.MODULE_LABEL_MARGIN[2], 0) width = max(width, padding.width()) if self.description: self.description = '(' + self.description + ')' descRect = self.descFontMetric.boundingRect(self.description) descRect.moveTo(-descRect.width()//2, height) height += descRect.height() padding = descRect.adjusted(-CurrentTheme.MODULE_LABEL_MARGIN[0], 0, CurrentTheme.MODULE_LABEL_MARGIN[2], 0) width = max(width, padding.width()) if self.edit_rect.height(): height += CurrentTheme.MODULE_EDIT_MARGIN[1] # top margin editRect = self.edit_rect editRect.moveTo(-editRect.width()//2, height) height += editRect.height() padding = editRect.adjusted(-CurrentTheme.MODULE_EDIT_MARGIN[0], 0, CurrentTheme.MODULE_EDIT_MARGIN[2], 0) width = max(width, padding.width()) height += CurrentTheme.MODULE_EDIT_MARGIN[3] # bottom edit margin height += CurrentTheme.MODULE_LABEL_MARGIN[3] # bottom margin # move to final position self.paddedRect = QtCore.QRectF(-width/2, -height/2, width, height) labelRect.translate(0, -height//2) self.labelRect = labelRect if self.description: descRect.translate(0, -height//2) self.descRect = descRect if self.edit_rect.height(): editRect.translate(0, -height//2) self.editRect = editRect self.abstRect = QtCore.QRectF( self.paddedRect.left(), -self.paddedRect.top()-CurrentTheme.MODULE_LABEL_MARGIN[3], CurrentTheme.MODULE_LABEL_MARGIN[0], CurrentTheme.MODULE_LABEL_MARGIN[3]) def boundingRect(self): """ boundingRect() -> QRectF Returns the bounding box of the module """ try: r = self.paddedRect.adjusted(-2, -2, 2, 2) except Exception: r = QtCore.QRectF() return r def setPainterState(self, is_selected=None): if is_selected is None: is_selected = self.isSelected() if is_selected: self.modulePen = CurrentTheme.MODULE_SELECTED_PEN self.labelPen = CurrentTheme.MODULE_LABEL_SELECTED_PEN elif self.is_breakpoint: self.modulePen = CurrentTheme.BREAKPOINT_MODULE_PEN self.labelPen = CurrentTheme.BREAKPOINT_MODULE_LABEL_PEN elif self.ghosted: self.modulePen = CurrentTheme.GHOSTED_MODULE_PEN self.labelPen = CurrentTheme.GHOSTED_MODULE_LABEL_PEN # do not show as invalid in search mode elif self.invalid and not (self.controller and self.controller.search): self.modulePen = CurrentTheme.INVALID_MODULE_PEN self.labelPen = CurrentTheme.INVALID_MODULE_LABEL_PEN else: self.labelPen = CurrentTheme.MODULE_LABEL_PEN if self.module is not None and self.module.is_abstraction(): self.modulePen = CurrentTheme.ABSTRACTION_PEN elif self.module is not None and self.module.is_group(): self.modulePen = CurrentTheme.GROUP_PEN else: self.modulePen = CurrentTheme.MODULE_PEN if self.statusBrush: self.moduleBrush = self.statusBrush elif self.customBrush: self.moduleBrush = self.customBrush elif self.is_breakpoint: self.moduleBrush = CurrentTheme.BREAKPOINT_MODULE_BRUSH elif self.ghosted: self.moduleBrush = CurrentTheme.GHOSTED_MODULE_BRUSH # do not show as invalid in search mode elif self.invalid and not (self.controller and self.controller.search): self.moduleBrush = CurrentTheme.INVALID_MODULE_BRUSH else: self.moduleBrush = CurrentTheme.MODULE_BRUSH def setGhosted(self, ghosted): """ setGhosted(ghosted: True) -> None Set this link to be ghosted or not """ if self.ghosted != ghosted: self.ghosted = ghosted for port in self.inputPorts.itervalues(): port.setGhosted(ghosted) for port in self.outputPorts.itervalues(): port.setGhosted(ghosted) self._needs_state_updated = True # if ghosted: # self.modulePen = CurrentTheme.GHOSTED_MODULE_PEN # self.moduleBrush = CurrentTheme.GHOSTED_MODULE_BRUSH # self.labelPen = CurrentTheme.GHOSTED_MODULE_LABEL_PEN # else: # self.modulePen = CurrentTheme.MODULE_PEN # self.moduleBrush = CurrentTheme.MODULE_BRUSH # self.labelPen = CurrentTheme.MODULE_LABEL_PEN def setInvalid(self, invalid): if self.invalid != invalid: self.invalid = invalid for port in self.inputPorts.itervalues(): port.setInvalid(invalid) for port in self.outputPorts.itervalues(): port.setInvalid(invalid) self._needs_state_updated = True def setBreakpoint(self, breakpoint): if self.is_breakpoint != breakpoint: self.is_breakpoint = breakpoint if breakpoint: self._original_module_shape = self._module_shape self.set_module_shape(self.create_shape_from_fringe( CurrentTheme.BREAKPOINT_FRINGE)) else: self._module_shape = self._original_module_shape self._needs_state_updated = True # if breakpoint: # self.modulePen = CurrentTheme.BREAKPOINT_MODULE_PEN # self.moduleBrush = CurrentTheme.BREAKPOINT_MODULE_BRUSH # self.labelPen = CurrentTheme.BREAKPOINT_MODULE_LABEL_PEN def set_module_shape(self, module_shape=None): self._module_shape = module_shape if self._module_shape is not None: self.paddedRect = self._module_shape.boundingRect() def set_custom_brush(self, brush): self.customBrush = brush self._needs_state_updated = True def paint(self, painter, option, widget=None): """ paint(painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget) -> None Peform actual painting of the module """ if self.progress>0.0: width = (self.progress-1.0)*self.paddedRect.width() progressRect = self.paddedRect.adjusted(0, 0, width, 0) if self._needs_state_updated: self.setPainterState() self._needs_state_updated = False # draw module shape painter.setBrush(self.moduleBrush) painter.setPen(self.modulePen) if self._module_shape: painter.drawPolygon(self._module_shape) if self.progress>0.0: painter.setClipRect(progressRect) painter.setBrush(self.progressBrush) painter.drawPolygon(self._module_shape) painter.setClipping(False) painter.drawPolyline(self._module_shape) else: painter.fillRect(self.paddedRect, painter.brush()) if self.progress>0.0: painter.fillRect(progressRect, self.progressBrush) painter.setBrush(QtCore.Qt.NoBrush) painter.drawRect(self.paddedRect) # draw module labels painter.setPen(self.labelPen) painter.setFont(self.labelFont) painter.drawText(self.labelRect.adjusted(-10,-10,10,10), QtCore.Qt.AlignCenter, self.label) if self.module.is_abstraction() and not self.module.is_latest_version(): painter.drawText(self.abstRect, QtCore.Qt.AlignCenter, '!') if self.descRect: painter.setFont(self.descFont) painter.drawText(self.descRect.adjusted(-10,-10,10,10), QtCore.Qt.AlignCenter, self.description) def paintToPixmap(self, scale_x, scale_y): bounding_rect = self.paddedRect.adjusted(-6,-6,6,6) center_x = (bounding_rect.width() / 2.0) #* m.m11() center_y = (bounding_rect.height() / 2.0) #* m.m22() pixmap = QtGui.QPixmap(int(bounding_rect.width() * scale_x), int(bounding_rect.height() * scale_y)) pixmap.fill(QtGui.QColor(255,255,255,0)) painter = QtGui.QPainter(pixmap) painter.setOpacity(0.5) painter.scale(scale_x, scale_y) painter.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform) painter.translate(center_x, center_y) self.paint(painter, QtGui.QStyleOptionGraphicsItem()) for port in self.inputPorts.itervalues(): m = port.matrix() painter.save() painter.translate(m.dx(), m.dy()) port.paint(painter, QtGui.QStyleOptionGraphicsItem()) painter.restore() for port in self.outputPorts.itervalues(): m = port.matrix() painter.save() painter.translate(m.dx(), m.dy()) port.paint(painter, QtGui.QStyleOptionGraphicsItem()) painter.restore() painter.end() return pixmap def adjustWidthToMin(self, minWidth): """ adjustWidthToContain(minWidth: int) -> None Resize the module width to at least be minWidth """ if minWidth>self.paddedRect.width(): diff = minWidth - self.paddedRect.width() + 1 self.paddedRect.adjust(-diff/2, 0, diff/2, 0) def setupModule(self, module, read_only=False): """ setupModule(module: Module) -> None Set up the item to reflect the info in 'module' """ # Update module info and visual self.id = module.id self.setZValue(float(self.id)) self.module = module self.union_ports = module.unionPorts() if module.is_valid else {} # reverse map self.to_union = dict((p.name, self.union_ports[union]) for union, p_list in self.union_ports.items() for p in p_list) self.center = copy.copy(module.center) if '__desc__' in module.db_annotations_key_index: self.label = module.get_annotation_by_key('__desc__').value.strip() self.description = module.label else: self.label = module.label self.description = '' # Show inline edit widgets if get_vistrails_configuration().check('showInlineParameterWidgets') and \ module.is_valid and not read_only and module.editable_input_ports: self.functions_widget = QGraphicsFunctionsWidget(self.module, self, module.editable_input_ports == set(['value'])) set_lod(0.5, self.functions_widget) self.functions_widget.function_changed.connect(self.function_changed) self.function_widgets = self.functions_widget.function_widgets self.edit_rect = self.functions_widget.boundingRect() self.setToolTip(self.description) self.computeBoundingRect() self.setPos(module.center.x, -module.center.y) # Check to see which ports will be shown on the screen # setupModule is in a hotpath, performance-wise, which is the # reason for the strange ._db_name lookup - we're # avoiding property calls inputPorts = [] self.inputPorts = {} visibleOptionalInputPorts = [] self.optionalInputPorts = [] outputPorts = [] self.outputPorts = {} visibleOptionalOutputPorts = [] self.optionalOutputPorts = [] error = None if module.is_valid: try: for p in module.destinationPorts(): if not p.optional: inputPorts.append(p) elif p.name in module.visible_input_ports: # add all in union if one is marked as visible for up in self.to_union.get(p.name, [p]): if up not in visibleOptionalInputPorts: visibleOptionalInputPorts.append(up) else: # Make sure it was not added with union if p.name not in visibleOptionalInputPorts: self.optionalInputPorts.append(p) inputPorts += visibleOptionalInputPorts for p in module.sourcePorts(): if not p.optional: outputPorts.append(p) elif p.name in module.visible_output_ports: visibleOptionalOutputPorts.append(p) else: self.optionalOutputPorts.append(p) outputPorts += visibleOptionalOutputPorts except ModuleRegistryException, e: error = e # group unions while keeping order pos_to_name = {} name_to_ports = {} for port_spec in inputPorts: name = port_spec.union or port_spec.name if name not in pos_to_name.itervalues(): pos = (max(pos_to_name) + 1) if pos_to_name else 0 pos_to_name[pos] = name name_to_ports[name] = [] name_to_ports[name].append(port_spec) self.port_groups = [name_to_ports[name] for _, name in sorted(pos_to_name.iteritems())] # Local dictionary lookups are faster than global ones.. t = CurrentTheme (mpm0, mpm1, mpm2, mpm3) = t.MODULE_PORT_MARGIN # Adjust the width to fit all ports maxPortCount = max(len(self.port_groups), len(outputPorts)) minWidth = (mpm0 + t.PORT_WIDTH*maxPortCount + t.MODULE_PORT_SPACE*(maxPortCount-1) + mpm2 + t.MODULE_PORT_PADDED_SPACE) self.adjustWidthToMin(minWidth) self.nextInputPortPos = [self.paddedRect.x() + mpm0, self.paddedRect.y() + mpm1] self.nextOutputPortPos = [self.paddedRect.right() - \ t.PORT_WIDTH - mpm2, self.paddedRect.bottom() - \ t.PORT_HEIGHT - mpm3] # Update input ports [x, y] = self.nextInputPortPos for ports in self.port_groups: item = self.createPortItem(ports[0], x, y, ports if len(ports)>1 else []) for port in ports: self.inputPorts[port] = item x += t.PORT_WIDTH + t.MODULE_PORT_SPACE self.nextInputPortPos = [x,y] # Update output ports [x, y] = self.nextOutputPortPos for port in reversed(outputPorts): self.outputPorts[port] = self.createPortItem(port, x, y) x -= t.PORT_WIDTH + t.MODULE_PORT_SPACE self.nextOutputPortPos = [x, y] # Add a configure button y = self.paddedRect.y() + mpm1 x = (self.paddedRect.right() - t.CONFIGURE_WIDTH - mpm2) self.createConfigureItem(x, y) if module.is_valid: try: # update module color and shape descriptor = module.module_descriptor # c = registry.get_module_color(module.package, module.name, # module.namespace) c = descriptor.module_color() if c: ic = [int(cl*255) for cl in c] b = QtGui.QBrush(QtGui.QColor(ic[0], ic[1], ic[2])) self.set_custom_brush(b) # fringe = registry.get_module_fringe(module.package, # module.name, # module.namespace) fringe = descriptor.module_fringe() if fringe: self.set_module_shape(self.create_shape_from_fringe(fringe)) except ModuleRegistryException, e: error = e if self.functions_widget: self.functions_widget.setPos(self.editRect.topLeft()) self.update_function_ports() else: self.setInvalid(True) def function_changed(self, name, values): """ Called when a function value has changed by the inline edit widget """ controller = self.scene().controller module = controller.current_pipeline.modules[self.module.id] controller.update_function(module, name, values) if self.moduleFunctionsHaveChanged(module): self.update_function_ports(module) if self.isSelected(): from vistrails.gui.vistrails_window import _app module = controller.current_pipeline.modules[self.module.id] _app.notify('module_changed', module) def create_shape_from_fringe(self, fringe): left_fringe, right_fringe = fringe if left_fringe[0] != (0.0, 0.0): left_fringe = [(0.0, 0.0)] + left_fringe if left_fringe[-1] != (0.0, 1.0): left_fringe = left_fringe + [(0.0, 1.0)] if right_fringe[0] != (0.0, 0.0): right_fringe = [(0.0, 0.0)] + right_fringe if right_fringe[-1] != (0.0, 1.0): right_fringe = right_fringe + [(0.0, 1.0)] P = QtCore.QPointF module_shape = QtGui.QPolygonF() height = self.paddedRect.height() # right side of shape for (px, py) in right_fringe: p = P(px, -py) p *= height p += self.paddedRect.bottomRight() module_shape.append(p) # left side of shape for (px, py) in reversed(left_fringe): p = P(px, -py) p *= height p += self.paddedRect.bottomLeft() module_shape.append(p) # close polygon module_shape.append(module_shape[0]) return module_shape def createPortItem(self, port, x, y, union_group=None): """ createPortItem(port: Port, x: int, y: int) -> QGraphicsPortItem Create a item from the port spec """ # pts = [(0,2),(0,-2), (2,None), (-2,None), # (None,-2), (None,2), (-2,0), (2,0)] # pts = [(0,0.2), (0, 0.8), (0.2, None), (0.8, None), # (None, 0.8), (None, 0.2), (0.8,0), (0.2, 0)] # portShape = QGraphicsPortPolygonItem(x, y, self.ghosted, self, # port.optional, port.min_conns, # port.max_conns, points=pts) # portShape = QGraphicsPortTriangleItem(x, y, self.ghosted, self, # port.optional, port.min_conns, # port.max_conns, angle=0) # portShape = QGraphicsPortDiamondItem(x, y, self.ghosted, self, # port.optional, port.min_conns, # port.max_conns) if not union_group and port.union and port.union in self.union_ports: union_group = self.union_ports[port.union] port_klass = QGraphicsPortRectItem kwargs = {} if union_group: kwargs['union_group'] = union_group shape = port.shape() if shape is not None: if isinstance(shape, basestring): if shape.startswith("triangle"): port_klass = QGraphicsPortTriangleItem try: kwargs['angle'] = int(shape[8:]) except ValueError: kwargs['angle'] = 0 elif shape == "diamond": port_klass = QGraphicsPortDiamondItem elif shape == "circle" or shape == "ellipse": port_klass = QGraphicsPortEllipseItem else: try: iter(shape) except TypeError: pass else: port_klass = QGraphicsPortPolygonItem kwargs['points'] = shape portShape = port_klass(port, x, y, self.ghosted, self, **kwargs) # portShape = QGraphicsPortRectItem(port, x, y, self.ghosted, self) portShape.controller = self.controller portShape.port = port # do not show as invalid in search mode if not port.is_valid and not (self.controller and self.controller.search): portShape.setInvalid(True) return portShape def createConfigureItem(self, x, y): """ createConfigureItem(x: int, y: int) -> QGraphicsConfigureItem Create a item from the configure spec """ if self.module.is_valid: configureShape = QGraphicsConfigureItem(self, self.scene()) configureShape.controller = self.controller configureShape.moduleId = self.id configureShape.setGhosted(self.ghosted) configureShape.setBreakpoint(self.module.is_breakpoint) configureShape.translate(x, y) return configureShape return None def getPortItem(self, port, port_dict=None): # print 'looking for port', port.name, port.type, port_type registry = get_module_registry() # if we haven't validated pipeline, don't try to use the registry if self.module.is_valid: # check enabled ports for (p, item) in port_dict.iteritems(): if registry.port_and_port_spec_match(port, p): return item # FIXME Raise Error! # else not available for some reason, just draw port and raise error? # can also decide to use Variant/Module types # or use types from the signature # port_descs = port.descriptors() # first, check if we've already added the port for (p, item) in port_dict.iteritems(): if (PortSpec.port_type_map.inverse[port.type] == p.type and port.name == p.name and port.sigstring == p.sigstring): return item return None def buildPortItem(self, port, port_dict, optional_ports, visible_ports, next_pos, next_op, default_sig): """buildPortItem(port: Port, port_dict: {PortSpec: QGraphicsPortItem}, optional_ports: [PortSpec], visible_ports: set(string), next_pos: [float, float], next_op: operator (operator.add, operator.sub), default_sig: str ) -> QPointF Return the scene position of a port matched 'port' in port_dict """ registry = get_module_registry() # check optional ports if self.module.is_valid: for p in optional_ports: if registry.port_and_port_spec_match(port, p): item = self.createPortItem(p, *next_pos) for union_port in self.to_union.get(port.name, [port]): visible_ports.add(union_port.name) port_dict[union_port] = item next_pos[0] = next_op(next_pos[0], (CurrentTheme.PORT_WIDTH + CurrentTheme.MODULE_PORT_SPACE)) return item if not port.signature or port.signature == '()': # or len(port_descs) == 0: sigstring = default_sig else: sigstring = port.signature port_type = PortSpec.port_type_map.inverse[port.type] names = [] for sig in sigstring[1:-1].split(','): k = sig.split(':', 2) if len(k) < 2: names.append(k[0]) else: names.append(k[1]) short_sigstring = '(' + ','.join(names) + ')' tooltip = "%s port %s\n%s" % (port_type.capitalize(), port.name, short_sigstring) new_spec = PortSpec(id=-1, name=port.name, type=port_type, sigstring=sigstring, tooltip=tooltip, optional=True) item = self.createPortItem(new_spec, *next_pos) # do not show as invalid in search mode if not (self.controller and self.controller.search): item.setInvalid(True) port_dict[new_spec] = item next_pos[0] = next_op(next_pos[0], (CurrentTheme.PORT_WIDTH + CurrentTheme.MODULE_PORT_SPACE)) return item def getInputPortItem(self, port, do_create=False): item = self.getPortItem(port, self.inputPorts) if not item and do_create: item = self.buildPortItem(port, self.inputPorts, self.optionalInputPorts, self.module.visible_input_ports, self.nextInputPortPos, operator.add, '(%s:Variant)' % \ get_vistrails_basic_pkg_id()) return item def getOutputPortItem(self, port, do_create=False): item = self.getPortItem(port, self.outputPorts) if not item and do_create: item = self.buildPortItem(port, self.outputPorts, self.optionalOutputPorts, self.module.visible_output_ports, self.nextOutputPortPos, operator.sub, '(%s:Module)' % \ get_vistrails_basic_pkg_id()) return item def addConnectionItem(self, item): self.connectionItems[item.connection.id] = item def removeConnectionItem(self, item): if item.connectingModules[0].id == self.module.id: if item.srcPortItem is not None: item.srcPortItem.disconnect() if item.connectingModules[1].id == self.module.id: if item.dstPortItem is not None: item.dstPortItem.disconnect() del self.connectionItems[item.connection.id] # returns a dictionary of (id, connection) key-value pairs! def dependingConnectionItems(self): return self.connectionItems # this is a generator that yields (connection, is_source [bool]) pairs def dependingConnectionItemsWithDir(self): for item in self.connectionItems.itervalues(): if item.connectingModules[0].id == self.id: yield (item, False) else: yield (item, True) def keyPressEvent(self, event): """ keyPressEvent(event: QKeyEvent) -> None Capture 'Del', 'Backspace' for deleting modules. Ctrl+C, Ctrl+V, Ctrl+A for copy, paste and select all """ if (self.scene().controller and event.key() in [QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete]): if not self.scene().read_only_mode: self.scene().delete_selected_items() else: QtGui.QGraphicsItem.keyPressEvent(self, event) def mouseReleaseEvent(self, event): super(QGraphicsModuleItem, self).mouseReleaseEvent(event) if not self.controller.changed and self.controller.has_move_actions(): self.controller.set_changed(True) def hoverEnterEvent(self, event): if QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier: scene = self.scene() if scene.function_tooltip: scene.removeItem(scene.function_tooltip) module = scene.controller.current_pipeline.modules[self.module.id] if module.functions: function_overview = [] for f in module.functions: if len(f.params)>1: params = ', '.join([p.strValue for p in f.params]) elif len(f.params)>0: params = f.params[0].strValue else: params = '' if len(params)>100: params = params[:97] + '...' function_template = "<b>%s(</b>%s<b>)</b>" function_overview.append(function_template % (f.name, params)) template = '<html><p style="background:#FFFFFF;">%s</p></html>' self.function_overview = template % '<br/>'.join(function_overview) else: self.function_overview = '' scene.function_tooltip = QtGui.QGraphicsTextItem() pos = self.paddedRect.bottomLeft()+self.pos() scene.function_tooltip.setPos(pos) scene.function_tooltip.setAcceptHoverEvents(False) scene.addItem(scene.function_tooltip) scene.function_tooltip.setHtml(self.function_overview) scene.function_tooltip.setZValue(1000000) return QtGui.QGraphicsItem.hoverEnterEvent(self, event) def hoverLeaveEvent(self, event): if self.scene().function_tooltip: self.scene().removeItem(self.scene().function_tooltip) self.scene().function_tooltip = None return QtGui.QGraphicsItem.hoverLeaveEvent(self, event) def itemChange(self, change, value): """ itemChange(change: GraphicsItemChange, value: value) -> value Capture move event to also move the connections. Also unselect any connections between unselected modules """ # Move connections with modules if change==QtGui.QGraphicsItem.ItemPositionChange and \ self.handlePositionChanges: oldPos = self.pos() newPos = value dis = newPos - oldPos for connectionItem, s in self.dependingConnectionItemsWithDir(): # If both modules are selected, both of them will # trigger itemChange events. # If we just add 'dis' to both connection endpoints, we'll # end up moving each endpoint twice. # But we also don't want to call setupConnection twice on these # connections, so we ignore one of the endpoint dependencies and # perform the change on the other one (srcModule, dstModule) = connectionItem.connectingModules start_s = srcModule.isSelected() end_s = dstModule.isSelected() if start_s and end_s and s: continue start = connectionItem.startPos end = connectionItem.endPos if start_s: start += dis if end_s: end += dis connectionItem.prepareGeometryChange() connectionItem.setupConnection(start, end) # Do not allow lone connections to be selected with modules. # Also autoselect connections between selected modules. Thus the # selection is always the subgraph elif change==QtGui.QGraphicsItem.ItemSelectedHasChanged: # Unselect any connections between modules that are not selected for item in self.scene().selectedItems(): if isinstance(item,QGraphicsConnectionItem): (srcModule, dstModule) = item.connectingModules if (not srcModule.isSelected() or not dstModule.isSelected()): item.useSelectionRules = False item.setSelected(False) # Handle connections from self for item in self.dependingConnectionItems().itervalues(): # Select any connections between self and other selected modules (srcModule, dstModule) = item.connectingModules if value: if (srcModule==self and dstModule.isSelected() or dstModule==self and srcModule.isSelected()): # Because we are setting a state variable in the # connection, do not make the change unless it is # actually going to be performed if not item.isSelected(): item.useSelectionRules = False item.setSelected(True) # Unselect any connections between self and other modules else: if item.isSelected(): item.useSelectionRules = False item.setSelected(False) # Capture only selected modules + or - self for selection signal selectedItems = [m for m in self.scene().selectedItems() if isinstance(m, QGraphicsModuleItem)] #print "selectedItems", selectedItems selectedId = -1 if len(selectedItems)==1: selectedId = selectedItems[0].id self.scene().emit(QtCore.SIGNAL('moduleSelected'), selectedId, selectedItems) self._needs_state_updated = True return QtGui.QGraphicsItem.itemChange(self, change, value) def choose_converter(converters, parent=None): """Chooses a converter among a list. """ if len(converters) == 1: return converters[0] class ConverterItem(QtGui.QListWidgetItem): def __init__(self, converter): QtGui.QListWidgetItem.__init__(self, converter.name) self.converter = converter dialog = QtGui.QDialog(parent) dialog.setWindowTitle("Automatic conversion") layout = QtGui.QVBoxLayout() label = QtGui.QLabel( "You are connecting two incompatible ports, however there are " "matching Converter modules. Please choose which Converter should " "be inserted on this connection:") label.setWordWrap(True) layout.addWidget(label) list_widget = QtGui.QListWidget() list_widget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) for converter in sorted(converters, key=lambda c: c.name): list_widget.addItem(ConverterItem(converter)) layout.addWidget(list_widget) buttons = QtGui.QDialogButtonBox( QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal) QtCore.QObject.connect(buttons, QtCore.SIGNAL('accepted()'), dialog, QtCore.SLOT('accept()')) QtCore.QObject.connect(buttons, QtCore.SIGNAL('rejected()'), dialog, QtCore.SLOT('reject()')) layout.addWidget(buttons) ok = buttons.button(QtGui.QDialogButtonBox.Ok) ok.setEnabled(False) QtCore.QObject.connect( list_widget, QtCore.SIGNAL('itemSelectionChanged()'), lambda: ok.setEnabled(True)) dialog.setLayout(layout) if dialog.exec_() == QtGui.QDialog.Accepted: return list_widget.selectedItems()[0].converter else: return None class StacktracePopup(QtGui.QDialog): def __init__(self, errorTrace='', parent=None): QtGui.QDialog.__init__(self, parent) self.resize(700, 400) self.setWindowTitle('Module Error') layout = QtGui.QVBoxLayout() self.setLayout(layout) text = QtGui.QTextEdit('') text.insertPlainText(errorTrace) text.setReadOnly(True) text.setLineWrapMode(QtGui.QTextEdit.NoWrap) layout.addWidget(text) close = QtGui.QPushButton('Close', self) close.setFixedWidth(100) layout.addWidget(close) self.connect(close, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('close()')) ############################################################################## # QPipelineScene class QPipelineScene(QInteractiveGraphicsScene): """ QPipelineScene inherits from QInteractiveGraphicsScene to keep track of the pipeline scenes, i.e. modules, connections, selection """ def __init__(self, parent=None): """ QPipelineScene(parent: QWidget) -> QPipelineScene Initialize the graphics scene with no shapes """ QInteractiveGraphicsScene.__init__(self, parent) self.setBackgroundBrush(CurrentTheme.PIPELINE_VIEW_BACKGROUND_BRUSH) self.setSceneRect(QtCore.QRectF(-5000, -5000, 10000, 10000)) self.controller = None self.modules = {} self.connections = {} self.noUpdate = False self.installEventFilter(self) self.pipeline_tab = None # These are the IDs currently present in the scene, used to update it # faster when switching pipelines via setupScene() self._old_module_ids = set() self._old_connection_ids = set() self._var_selected_port = None self.read_only_mode = False self.current_pipeline = None self.current_version = -1 self.skip_update = False self.function_tooltip = None self.tmp_module_item = None self.tmp_input_conn = None self.tmp_output_conn = None def _get_pipeline(self): warnings.warn("Use of deprecated field 'pipeline' replaced by " "'current_pipeline'", category=VistrailsDeprecation) return self.current_pipeline pipeline = property(_get_pipeline) def addModule(self, module, moduleBrush=None): """ addModule(module: Module, moduleBrush: QBrush) -> QGraphicsModuleItem Add a module to the scene """ moduleItem = QGraphicsModuleItem(None) if self.controller and self.controller.search: moduleQuery = (self.controller.current_version, module) matched = self.controller.search.matchModule(*moduleQuery) moduleItem.setGhosted(not matched) moduleItem.controller = self.controller moduleItem.setupModule(module, self.read_only_mode) moduleItem.setBreakpoint(module.is_breakpoint) if moduleBrush: moduleItem.set_custom_brush(moduleBrush) self.addItem(moduleItem) self.modules[module.id] = moduleItem self._old_module_ids.add(module.id) # Hide vistrail variable modules if module.is_vistrail_var(): moduleItem.hide() return moduleItem def addConnection(self, connection, connectionBrush=None): """ addConnection(connection: Connection) -> QGraphicsConnectionItem Add a connection to the scene """ srcModule = self.modules[connection.source.moduleId] dstModule = self.modules[connection.destination.moduleId] srcPortItem = srcModule.getOutputPortItem(connection.source, True) dstPortItem = dstModule.getInputPortItem(connection.destination, True) connectionItem = QGraphicsConnectionItem(srcPortItem, dstPortItem, srcModule, dstModule, connection) srcPortItem.connect() dstPortItem.connect() connectionItem.id = connection.id connectionItem.connection = connection if connectionBrush: connectionItem.set_custom_brush(connectionBrush) self.addItem(connectionItem) self.connections[connection.id] = connectionItem self._old_connection_ids.add(connection.id) srcModule.addConnectionItem(connectionItem) dstModule.addConnectionItem(connectionItem) if srcModule.module.is_vistrail_var(): connectionItem.hide() var_uuid = srcModule.module.get_vistrail_var() dstPortItem.addVistrailVar(var_uuid) self.update_connections([srcModule.id, dstModule.id]) return connectionItem def selected_subgraph(self): """Returns the subgraph containing the selected modules and its mutual connections. """ items = self.selectedItems() modules = [x.id for x in items if isinstance(x, QGraphicsModuleItem)] return self.controller.current_pipeline.graph.subgraph(modules) # def contextMenuEvent(self, event): # selectedItems = self.selectedItems() # if len(selectedItems) == 0: # return QInteractiveGraphicsScene.contextMenuEvent(self, event) # else: # self._context_menu.exec_(event.screenPos()) def clear(self): """ clear() -> None Clear the whole scene """ self.modules = {} self.connections = {} self._old_module_ids = set() self._old_connection_ids = set() self.unselect_all() self.clearItems() def remove_module(self, m_id): """remove_module(m_id): None Removes module from scene, updating appropriate data structures. """ core_module = self.modules[m_id].module if not core_module.has_annotation_with_key('__vistrail_var__'): self.removeItem(self.modules[m_id]) del self.modules[m_id] self._old_module_ids.remove(m_id) def remove_connection(self, c_id): """remove_connection(c_id): None Removes connection from scene, updating appropriate data structures. """ # if c_id in self.connections: connItem = self.connections[c_id] (srcModule, dstModule) = connItem.connectingModules srcModule.removeConnectionItem(connItem) dstModule.removeConnectionItem(connItem) if not srcModule.module.has_annotation_with_key('__vistrail_var__'): self.removeItem(self.connections[c_id]) del self.connections[c_id] self._old_connection_ids.remove(c_id) self.update_connections([srcModule.id, dstModule.id]) def recreate_module(self, pipeline, m_id): """recreate_module(pipeline, m_id): None Recreates a module on the scene.""" selected = self.modules[m_id].isSelected() depending_connections = \ [c_id for c_id in self.modules[m_id].dependingConnectionItems()] # when configuring a python source, maybe connections were deleted # but are not in the current pipeline. So we need to check the depending # connections of the module just before the configure. for c_id in depending_connections: self.remove_connection(c_id) self.remove_module(m_id) self.addModule(pipeline.modules[m_id]) for c_id in depending_connections: # only add back those connections that are in the pipeline if c_id in pipeline.connections: self.addConnection(pipeline.connections[c_id]) if selected: self.modules[m_id].setSelected(True) def update_module_functions(self, pipeline, m_id): """ Used by ports_pane to update modules """ module = pipeline.modules[m_id] if self.modules[m_id].functions_have_been_deleted(module): self.recreate_module(pipeline, m_id) return self.modules[m_id].update_function_values(module) if self.modules[m_id].moduleFunctionsHaveChanged(module): self.modules[m_id].update_function_ports(module) def setupScene(self, pipeline): """ setupScene(pipeline: Pipeline) -> None Construct the scene to view a pipeline """ old_pipeline = self.current_pipeline self.current_pipeline = pipeline if self.noUpdate: return if (pipeline is None or (old_pipeline and not old_pipeline.is_valid) or (pipeline and not pipeline.is_valid)): # clear things self.clear() if not pipeline: return needReset = len(self.items())==0 try: self.skip_update = True new_modules = set(pipeline.modules) modules_to_be_added = new_modules - self._old_module_ids modules_to_be_deleted = self._old_module_ids - new_modules common_modules = new_modules.intersection(self._old_module_ids) new_connections = set(pipeline.connections) connections_to_be_added = new_connections - self._old_connection_ids connections_to_be_deleted = self._old_connection_ids - new_connections common_connections = new_connections.intersection(self._old_connection_ids) # Check if connections to be added require # optional ports in modules to be visible # check all connections because the visible flag # may have been cleared for c_id in new_connections: connection = pipeline.connections[c_id] smid = connection.source.moduleId s = connection.source.spec if s and s.optional: smm = pipeline.modules[smid] smm.visible_output_ports.add(s.name) dmid = connection.destination.moduleId d = connection.destination.spec if d and d.optional: dmm = pipeline.modules[dmid] dmm.visible_input_ports.add(d.name) # remove old connection shapes for c_id in connections_to_be_deleted: self.remove_connection(c_id) # remove old module shapes for m_id in modules_to_be_deleted: self.remove_module(m_id) selected_modules = [] # create new module shapes for m_id in modules_to_be_added: self.addModule(pipeline.modules[m_id]) if self.modules[m_id].isSelected(): selected_modules.append(m_id) moved = set() # Update common modules for m_id in common_modules: tm_item = self.modules[m_id] nm = pipeline.modules[m_id] if tm_item.moduleHasChanged(nm): self.recreate_module(pipeline, m_id) tm_item = self.modules[m_id] elif tm_item.moduleFunctionsHaveChanged(nm): tm_item.update_function_ports(pipeline.modules[m_id]) tm_item.update_function_values(pipeline.modules[m_id]) if tm_item.isSelected(): selected_modules.append(m_id) if self.controller and self.controller.search: moduleQuery = (self.controller.current_version, nm) matched = \ self.controller.search.matchModule(*moduleQuery) tm_item.setGhosted(not matched) else: tm_item.setGhosted(False) tm_item.setBreakpoint(nm.is_breakpoint) # create new connection shapes for c_id in connections_to_be_added: self.addConnection(pipeline.connections[c_id]) # Update common connections for c_id in common_connections: connection = pipeline.connections[c_id] pip_c = self.connections[c_id] pip_c.connectingModules = (self.modules[connection.source.moduleId], self.modules[connection.destination.moduleId]) (srcModule, dstModule) = pip_c.connectingModules self._old_module_ids = new_modules self._old_connection_ids = new_connections self.unselect_all() self.reset_module_colors() for m_id in selected_modules: self.modules[m_id].setSelected(True) except ModuleRegistryException, e: debug.print_exc() views = self.views() assert len(views) > 0 debug.critical("Missing package/module", ("Package '%s' is missing (or module '%s' is not present " + "in that package)") % (e._identifier, e._name)) self.clear() self.controller.change_selected_version(0) finally: self.skip_update = False self.update_connections() if needReset and len(self.items())>0: self.fitToAllViews() def findModuleUnder(self, pos): """ findModuleUnder(pos: QPoint) -> QGraphicsItem Search all items under pos and return the top-most module item if any """ for item in self.items(pos): if isinstance(item, QGraphicsModuleItem): return item return None def findModulesNear(self, pos, where_mult): rect = QtCore.QRectF(pos.x()-50+25*where_mult, (pos.y()-50) + 50*where_mult, 100, 100) ### code to display target rectangle # # if where_mult < 0: # if not hasattr(self, 'tmp_rect'): # self.tmp_rect = QtGui.QGraphicsRectItem(rect) # self.tmp_rect.setPen(QtGui.QColor("red")) # self.addItem(self.tmp_rect) # else: # self.tmp_rect.setRect(rect) # else: # if not hasattr(self, 'tmp_rect2'): # self.tmp_rect2 = QtGui.QGraphicsRectItem(rect) # self.tmp_rect2.setPen(QtGui.QColor("red")) # self.addItem(self.tmp_rect2) # else: # self.tmp_rect2.setRect(rect) closest_item = None min_dis = None for item in self.items(rect): if isinstance(item, QGraphicsModuleItem) and item.isVisible(): vector = item.scenePos() - pos dis = vector.x() * vector.x() + vector.y() * vector.y() if min_dis is None or dis < min_dis: min_dis = dis closest_item = item return closest_item def findPortsNear(self, pos, where_mult): width = self.tmp_module_item.paddedRect.width() + 50 rect = QtCore.QRectF(pos.x()-width/2+25*where_mult, pos.y()-50 + 50*where_mult, width, 100) ### code to display target rectangle # # rect = QtCore.QRectF(pos.x()-50+25*where_mult, # (pos.y()-50) + 50*where_mult, # 100, 100) # if where_mult < 0: # if not hasattr(self, 'tmp_rect'): # self.tmp_rect = QtGui.QGraphicsRectItem(rect) # self.tmp_rect.setPen(QtGui.QColor("red")) # self.addItem(self.tmp_rect) # else: # self.tmp_rect.setRect(rect) # else: # if not hasattr(self, 'tmp_rect2'): # self.tmp_rect2 = QtGui.QGraphicsRectItem(rect) # self.tmp_rect2.setPen(QtGui.QColor("red")) # self.addItem(self.tmp_rect2) # else: # self.tmp_rect2.setRect(rect) # if not hasattr(self, 'tmp_rect'): # self.tmp_rect = QtGui.QGraphicsRectItem(rect) # self.tmp_rect.setPen(QtGui.QColor("red")) # self.addItem(self.tmp_rect) # else: # self.tmp_rect.setRect(rect) near_ports = [] for item in self.items(rect): if isinstance(item, QAbstractGraphicsPortItem) and item.isVisible(): near_ports.append(item) return near_ports def findPortMatch(self, output_ports, input_ports, x_trans=0, fixed_out_pos=None, fixed_in_pos=None, allow_conversion=False, out_converters=None): """findPortMatch(output_ports: list(QAbstractGraphicsPortItem), input_ports: list(QAbstractGraphicsPortItem), x_trans: int, fixed_out_pos: QPointF | None, fixed_in_pos: QPointF | None, ) -> tuple(QAbstractGraphicsPortItem, QAbstractGraphicsPortItem) findPortMatch returns a port from output_ports and a port from input_ports where the ports are compatible and the distance between these ports is minimal with respect to compatible ports If allow_conversion is True, we also search for ports that are not directly matched but can be connected if a Converter module is used. In this case, we extend the optional 'out_converters' list with the possible Converters' ModuleDescriptors. """ reg = get_module_registry() result = (None, None, None) min_dis = None selected_convs = None for o_item in output_ports: if o_item.invalid: continue for i_item in input_ports: if i_item.invalid: continue # Check all union types # add all matches to iports # check without converters first for iport in i_item.union_group or [i_item.port]: if reg.ports_can_connect(o_item.port, iport): if fixed_out_pos is not None: out_pos = fixed_out_pos else: out_pos = o_item.getPosition() if fixed_in_pos is not None: in_pos = fixed_in_pos else: in_pos = i_item.getPosition() vector = (out_pos - in_pos) dis = (vector.x()-x_trans)*(vector.x()-x_trans) + \ vector.y()*vector.y() if (result[0] is not None and result[0] == o_item and result[1] == i_item): # additional match in same union result[2].append(iport) elif result[1] is None or dis < min_dis: min_dis = dis result = (o_item, i_item, [iport]) if result[0] == o_item and result[1] == i_item: continue convs = [] # this selects only the first match in a union for iport in i_item.union_group or [i_item.port]: if reg.ports_can_connect(o_item.port, iport, allow_conversion=True, out_converters=convs): if fixed_out_pos is not None: out_pos = fixed_out_pos else: out_pos = o_item.getPosition() if fixed_in_pos is not None: in_pos = fixed_in_pos else: in_pos = i_item.getPosition() vector = (out_pos - in_pos) dis = (vector.x()-x_trans)*(vector.x()-x_trans) + \ vector.y()*vector.y() if result[0] is None or dis < min_dis: min_dis = dis result = (o_item, i_item, [iport]) selected_convs = convs if selected_convs and out_converters is not None: out_converters.extend(selected_convs) return result def updateTmpConnection(self, pos, tmp_connection_item, tmp_module_ports, where_mult, order_f): near_ports = self.findPortsNear(pos, where_mult) if len(near_ports) > 0: (src_item, dst_item, dst_ports) = \ self.findPortMatch(*order_f([near_ports,tmp_module_ports]), x_trans=-50) if src_item is not None: if tmp_connection_item is None: tmp_connection_item = QGraphicsTmpConnItem(dst_item, dst_ports, 1000) self.addItem(tmp_connection_item) # We are assuming the first view is the real pipeline view v = self.views()[0] tmp_connection_item.setStartPort(dst_item, dst_ports) tmp_connection_item.setSnapPort(src_item) dst_type_str = ' or '.join([('List of ' * dst_port.depth + dst_port.short_sigstring) for dst_port in dst_ports]) tooltip = "%s %s\n -> %s %s" % (src_item.port.name, 'List of ' * src_item.port.depth + src_item.port.short_sigstring, dst_port.union or dst_port.name, dst_type_str) QtGui.QToolTip.showText(v.mapToGlobal( v.mapFromScene((dst_item.getPosition() + src_item.getPosition())/2.0)), tooltip) tmp_connection_item.show() return tmp_connection_item if tmp_connection_item is not None: tmp_connection_item.hide() QtGui.QToolTip.hideText() return tmp_connection_item def updateTmpInputConnection(self, pos): self.tmp_input_conn = \ self.updateTmpConnection(pos, self.tmp_input_conn, set(self.tmp_module_item.inputPorts.values()), -1, lambda x: x) def updateTmpOutputConnection(self, pos): self.tmp_output_conn = \ self.updateTmpConnection(pos, self.tmp_output_conn, set(self.tmp_module_item.outputPorts.values()), 1, reversed) def dragEnterEvent(self, event): """ dragEnterEvent(event: QDragEnterEvent) -> None Set to accept drops from the module palette """ if (self.controller and ( isinstance(event.source(), QModuleTreeWidget) or isinstance(event.source(), QDragVariableLabel))): data = event.mimeData() if not self.read_only_mode: if hasattr(data, 'items'): if self.tmp_module_item and \ get_vistrails_configuration().check('autoConnect'): self.tmp_module_item.setPos(event.scenePos()) self.updateTmpInputConnection(event.scenePos()) self.updateTmpOutputConnection(event.scenePos()) event.accept() return elif hasattr(data, 'variableData'): event.accept() return # Ignore if not accepted and returned by this point event.ignore() def dragMoveEvent(self, event): """ dragMoveEvent(event: QDragMoveEvent) -> None Set to accept drag move event from the module palette """ if (self.controller and ( isinstance(event.source(), QModuleTreeWidget) or isinstance(event.source(), QDragVariableLabel))): data = event.mimeData() if hasattr(data, 'items') and not self.read_only_mode: if self.tmp_module_item and \ get_vistrails_configuration().check('autoConnect'): self.tmp_module_item.setPos(event.scenePos()) self.updateTmpInputConnection(event.scenePos()) self.updateTmpOutputConnection(event.scenePos()) event.accept() return elif hasattr(data, 'variableData'): # Find nearest suitable port snapModule = self.findModuleUnder(event.scenePos()) nearest_port = None if snapModule is not None: tmp_port = QAbstractGraphicsPortItem(None, 0, 0) tmp_port.port = data.variableData[0] (_, nearest_port, iport) = \ self.findPortMatch([tmp_port], set(snapModule.inputPorts.values()), fixed_out_pos=event.scenePos()) del tmp_port # Unhighlight previous nearest port if self._var_selected_port is not None: self._var_selected_port.setSelected(False) self._var_selected_port = nearest_port # Highlight new nearest port if nearest_port is not None: nearest_port.setSelected(True) QtGui.QToolTip.showText(event.screenPos(), nearest_port.toolTip()) event.accept() return else: QtGui.QToolTip.hideText() # Ignore if not accepted and returned by this point if not systemType in ['Darwin']: # Workaround: On a Mac, dropEvent isn't called if dragMoveEvent is ignored event.ignore() def dragLeaveEvent(self, event): if (self.controller and isinstance(event.source(), QModuleTreeWidget)): if self.tmp_output_conn: self.tmp_output_conn.disconnect(True) self.removeItem(self.tmp_output_conn) self.tmp_output_conn = None if self.tmp_input_conn: self.tmp_input_conn.disconnect(True) self.removeItem(self.tmp_input_conn) self.tmp_input_conn = None elif isinstance(event.source(), QDragVariableLabel): data = event.mimeData() if hasattr(data, 'variableData'): if self._var_selected_port is not None: self._var_selected_port.setPen(CurrentTheme.PORT_PEN) self._var_selected_port = None event.accept() def unselect_all(self): self.clearSelection() if self.pipeline_tab: self.pipeline_tab.moduleSelected(-1) def createConnectionFromTmp(self, tmp_connection_item, module, start_is_src=False): def select_type(ports): selected_port_spec = [None] def add_selector(ps): def triggered(*args, **kwargs): selected_port_spec[0] = ps return triggered menu = QtGui.QMenu(self.parent()) for port_spec in ports: type_name = port_spec.type_name() label = 'Select destination port type: ' + type_name act = QtGui.QAction(label, self.parent()) act.setStatusTip(label) act.triggered.connect(add_selector(port_spec)) menu.addAction(act) menu.exec_(QtGui.QCursor.pos()) return selected_port_spec[0] if start_is_src: src_port_item = tmp_connection_item.startPortItem dst_port_item = tmp_connection_item.snapPortItem if len(tmp_connection_item.snapPorts) > 1: dst_port = select_type(tmp_connection_item.snapPorts) if not dst_port: return else: dst_port = tmp_connection_item.snapPorts[0] else: src_port_item = tmp_connection_item.snapPortItem dst_port_item = tmp_connection_item.startPortItem if len(tmp_connection_item.startPorts) > 1: dst_port = select_type(tmp_connection_item.startPorts) if not dst_port: return else: dst_port = tmp_connection_item.startPorts[0] if src_port_item.parentItem().id < 0 or start_is_src: src_module_id = module.id dst_module_id = dst_port_item.parentItem().id else: src_module_id = src_port_item.parentItem().id dst_module_id = module.id graph = copy.copy(self.controller.current_pipeline.graph) graph.add_edge(src_module_id, dst_module_id) try: graph.dfs(raise_if_cyclic=True) except GraphContainsCycles: return False reg = get_module_registry() if reg.ports_can_connect(src_port_item.port, dst_port): # Direct connection conn = self.controller.add_connection(src_module_id, src_port_item.port, dst_module_id, dst_port) self.addConnection(conn) else: # Add a converter module converters = reg.get_converters(src_port_item.port.descriptors(), dst_port.descriptors()) converter = choose_converter(converters) if converter is None: return src_pos = src_port_item.getPosition() dst_pos = dst_port_item.getPosition() mod_x = (src_pos.x() + dst_pos.x())/2.0 mod_y = (src_pos.y() + dst_pos.y())/2.0 mod = self.controller.create_module_from_descriptor( converter, x=mod_x, y=-mod_y) conn1 = self.controller.create_connection( self.controller.current_pipeline.modules[src_module_id], src_port_item.port, mod, 'in_value') conn2 = self.controller.create_connection( mod, 'out_value', self.controller.current_pipeline.modules[dst_module_id], dst_port) operations = [('add', mod), ('add', conn1), ('add', conn2)] action = create_action(operations) self.controller.add_new_action(action) self.controller.perform_action(action) graphics_mod = self.addModule(mod) graphics_mod.update() self.addConnection(conn1) self.addConnection(conn2) return True def addConnectionFromTmp(self, tmp_connection_item, module, start_is_src): result = self.createConnectionFromTmp(tmp_connection_item, module, start_is_src) self.reset_module_colors() self._old_connection_ids = \ set(self.controller.current_pipeline.connections) self._old_module_ids = set(self.controller.current_pipeline.modules) return result def add_module_event(self, event, data): """Adds a new module from a drop event""" item = data.items[0] self.controller.reset_pipeline_view = False self.noUpdate = True internal_version = -1L reg = get_module_registry() if reg.is_abstraction(item.descriptor): internal_version = item.descriptor.module.internal_version adder = self.controller.add_module_from_descriptor module = adder(item.descriptor, event.scenePos().x(), -event.scenePos().y(), internal_version) self.reset_module_colors() graphics_item = self.addModule(module) graphics_item.update() if get_vistrails_configuration().check('autoConnect'): if self.tmp_output_conn is not None: if self.tmp_output_conn.isVisible(): self.createConnectionFromTmp(self.tmp_output_conn, module) self.tmp_output_conn.disconnect() self.removeItem(self.tmp_output_conn) self.tmp_output_conn = None if self.tmp_input_conn is not None: if self.tmp_input_conn.isVisible(): self.createConnectionFromTmp(self.tmp_input_conn, module) self.tmp_input_conn.disconnect() self.removeItem(self.tmp_input_conn) self.tmp_input_conn = None self.unselect_all() # Change selection graphics_item.setSelected(True) # controller changed pipeline: update ids self._old_connection_ids = \ set(self.controller.current_pipeline.connections) self._old_module_ids = set(self.controller.current_pipeline.modules) # We are assuming the first view is the real pipeline view self.views()[0].setFocus() self.noUpdate = False def add_tmp_module(self, desc): self.noUpdate = True self.tmp_module_item = QGraphicsModuleItem(None) module = Module(id=-1, name=desc.name, package=desc.identifier, location=Location(id=-1,x=0.0,y=0.0), namespace=desc.namespace, ) module.is_valid = True self.tmp_module_item.setupModule(module, True) self.addItem(self.tmp_module_item) self.tmp_module_item.hide() self.tmp_module_item.update() self.noUpdate = False return self.tmp_module_item def update_connections(self, modules=None): if self.skip_update: return if (self.controller.current_pipeline and self.controller.current_pipeline.is_valid): try: depths = \ self.controller.current_pipeline.mark_list_depth(modules) except GraphContainsCycles: # Pipeline is invalid, we don't really care that the depths are # not right pass else: for module_id, list_depth in depths: if module_id in self.modules: self.modules[module_id].module.list_depth = list_depth for c in self.connections.itervalues(): c.setupConnection() def delete_tmp_module(self): if self.tmp_module_item is not None: self.removeItem(self.tmp_module_item) self.tmp_module_item = None def dropEvent(self, event): """ dropEvent(event: QDragMoveEvent) -> None Accept drop event to add a new module """ if (self.controller and ( isinstance(event.source(), QModuleTreeWidget) or isinstance(event.source(), QDragVariableLabel))): data = event.mimeData() if hasattr(data, 'items') and not self.read_only_mode and \ self.controller.current_pipeline == self.current_pipeline: assert len(data.items) == 1 self.add_module_event(event, data) event.accept() return elif hasattr(data, 'variableData'): if self._var_selected_port is not None: # Unhighlight selected port and get var data self._var_selected_port.setSelected(False) output_portspec = data.variableData[0] var_uuid = data.variableData[1] var_name = data.variableData[2] descriptor = output_portspec.descriptors()[0] input_module = self._var_selected_port.parentItem().module #input_portspec = self._var_selected_port.port input_port = self._var_selected_port.port.name m_pos_x = event.scenePos().x() m_pos_y = -event.scenePos().y() (new_conn, new_module) = \ self.controller.connect_vistrail_var(descriptor, var_uuid, input_module, input_port, m_pos_x, m_pos_y) if new_module is not None: self.addModule(new_module) if new_conn is not None: self.addConnection(new_conn) else: msg = 'Vistrail Variable "%s" is already connected' \ ' to this port.' % var_name QtGui.QMessageBox.information(None, "Already Connected", msg) event.accept() return # Ignore if not accepted and returned by this point event.ignore() def delete_selected_items(self): selectedItems = self.selectedItems() if len(selectedItems)>0: modules = [] module_ids = [] connection_ids = [] for it in selectedItems: if isinstance(it, QGraphicsModuleItem): modules.append(it) module_ids.append(it.id) elif isinstance(it, QGraphicsConnectionItem): connection_ids.append(it.id) if len(modules)>0: # add connected vistrail variables vvms, vvcs = \ self.controller.get_connected_vistrail_vars(module_ids, True) for vvm in vvms: if vvm not in module_ids: modules.append(self.modules[vvm]) module_ids.append(vvm) for vvc in vvcs: if vvc not in connection_ids: connection_ids.append(vvc) self.noUpdate = True dep_connection_ids = set() for m in modules: dep_connection_ids.update( m.dependingConnectionItems().iterkeys()) # remove_connection updates the dependency list on the # other side of connections, cannot use removeItem try: skip_update = True for c_id in dep_connection_ids: self.remove_connection(c_id) for m_id in module_ids: self.remove_module(m_id) self.controller.delete_module_list(module_ids) finally: self.skip_update = False self.update_connections() self.updateSceneBoundingRect() self.reset_module_colors() self.update() self.noUpdate = False # Notify that no module is selected self.emit(QtCore.SIGNAL('moduleSelected'), -1, selectedItems) # Current pipeline changed, so we need to change the # _old_*_ids. However, remove_module takes care of # module ids, and the for loop above takes care of # connection ids. So we don't need to call anything. else: try: self.skip_update = False for c_id in connection_ids: self.remove_connection(c_id) self.controller.reset_pipeline_view = False self.controller.delete_connection_list(connection_ids) self.reset_module_colors() self.controller.reset_pipeline_view = True finally: self.skip_update = False self.update_connections() # Current pipeline changed, so we need to change the # _old_connection_ids. However, remove_connection # above takes care of connection ids, so we don't need # to call anything. def keyPressEvent(self, event): """ keyPressEvent(event: QKeyEvent) -> None Capture 'Del', 'Backspace' for deleting modules. Ctrl+C, Ctrl+V, Ctrl+A for copy, paste and select all """ if (not self.focusItem() and self.controller and event.key() in [QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete]): if not self.read_only_mode: self.delete_selected_items() else: QInteractiveGraphicsScene.keyPressEvent(self, event) # super(QPipelineScene, self).keyPressEvent(event) def get_selected_module_ids(self): module_ids = [] for item in self.selectedItems(): if isinstance(item, QGraphicsModuleItem): module_ids.append(item.module.id) return module_ids def get_selected_item_ids(self, dangling=False): """get_selected_item_ids( self, dangling: bool) -> (module_ids : list, connection_ids : list) returns the list of selected modules and the connections between them. If dangling is true, it includes connections for which only one end point is selected, otherwise it only includes connectiosn where both end points are selected """ selectedItems = self.selectedItems() if len(selectedItems) <= 0: return None connection_ids = {} module_ids = {} for item in selectedItems: if isinstance(item, QGraphicsModuleItem): module_ids[item.module.id] = 1 # Add connected vistrail variables vvms, vvcs = \ self.controller.get_connected_vistrail_vars(module_ids) for vvm in vvms: module_ids[vvm] = 1 for vvc in vvcs: connection_ids[vvc] = 1 for item in selectedItems: if isinstance(item, QGraphicsModuleItem): for connItem in item.dependingConnectionItems().itervalues(): conn = connItem.connection if not conn.id in connection_ids: source_exists = conn.sourceId in module_ids dest_exists = conn.destinationId in module_ids if source_exists and dest_exists: connection_ids[conn.id] = 1 elif dangling and (source_exists or dest_exists): connection_ids[conn.id] = 1 return (module_ids.keys(), connection_ids.keys()) def group(self): items = self.get_selected_item_ids(True) if items is not None: # self.clear() self.controller.create_group(items[0], items[1]) self.setupScene(self.controller.current_pipeline) def ungroup(self): items = self.get_selected_item_ids(True) if items is not None: # self.clear() self.controller.ungroup_set(items[0]) self.setupScene(self.controller.current_pipeline) def layout(self): if len(self.items()) <= 0: return def _func(module): rect = self.modules[module.shortname].boundingRect() return (rect.width(), rect.height()) selected = [self.modules[i].module for i in self.get_selected_module_ids()] self.controller.layout_modules(selected, module_size_func=_func) def makeAbstraction(self): items = self.get_selected_item_ids(True) if items is not None: # self.clear() self.controller.create_abstraction_with_prompt(items[0], items[1]) self.setupScene(self.controller.current_pipeline) def convertToAbstraction(self): items = self.get_selected_item_ids(False) if items is not None: # self.clear() self.controller.create_abstractions_from_groups(items[0]) self.setupScene(self.controller.current_pipeline) def importAbstraction(self): items = self.get_selected_item_ids(False) if items is not None: self.controller.import_abstractions(items[0]) def exportAbstraction(self): items = self.get_selected_item_ids(False) if items is not None: self.controller.export_abstractions(items[0]) def copySelection(self): """ copySelection() -> None Copy the current selected modules into clipboard """ items = self.get_selected_item_ids(False) if items is not None: cb = QtGui.QApplication.clipboard() text = self.controller.copy_modules_and_connections(items[0],items[1]) cb.setText(text) def pasteFromClipboard(self, center): """ pasteFromClipboard(center: (float, float)) -> None Paste modules/connections from the clipboard into this pipeline view """ if self.controller and not self.read_only_mode: cb = QtGui.QApplication.clipboard() text = cb.text() if text=='' or not text.startswith("<workflow"): return ids = self.controller.paste_modules_and_connections(text, center) self.setupScene(self.controller.current_pipeline) self.reset_module_colors() if len(ids) > 0: self.unselect_all() for moduleId in ids: self.modules[moduleId].setSelected(True) def event(self, e): """ event(e: QEvent) -> None Process the set module color events """ if e.type()==QModuleStatusEvent.TYPE: if e.moduleId>=0: item = self.modules.get(e.moduleId, None) if not item: return True item.setToolTip(e.toolTip) item.errorTrace = e.errorTrace statusMap = { 0: CurrentTheme.SUCCESS_MODULE_BRUSH, 1: CurrentTheme.ERROR_MODULE_BRUSH, 2: CurrentTheme.NOT_EXECUTED_MODULE_BRUSH, 3: CurrentTheme.ACTIVE_MODULE_BRUSH, 4: CurrentTheme.COMPUTING_MODULE_BRUSH, 6: CurrentTheme.PERSISTENT_MODULE_BRUSH, 7: CurrentTheme.SUSPENDED_MODULE_BRUSH, } item.setProgress(e.progress) if item.statusBrush is not None and e.status == 3: # do not update, already in cache pass elif e.status in statusMap: item.statusBrush = statusMap[e.status] else: item.statusBrush = None item._needs_state_updated = True item.update() return True return QInteractiveGraphicsScene.event(self, e) def selectAll(self): """ selectAll() -> None Select all module items in the scene """ for item in self.items(): if isinstance(item, QGraphicsModuleItem) or \ isinstance(item, QGraphicsConnectionItem): item.setSelected(True) def open_configure_window(self, id): """ open_configure_window(int) -> None Open the modal configuration window for module with given id """ from vistrails.gui.vistrails_window import _app _app.configure_module() def perform_configure_done_actions(self, module_id): if self.controller: self.reset_module_colors() self.flushMoveActions() self.recreate_module(self.controller.current_pipeline, module_id) def open_documentation_window(self, id): """ open_documentation_window(int) -> None Opens the modal module documentation window for module with given id """ from vistrails.gui.vistrails_window import _app _app.show_documentation() def open_looping_window(self, id): """ open_looping_window(int) -> None Opens the modal module looping options window for module with given id """ from vistrails.gui.vistrails_window import _app _app.show_looping_options() def toggle_breakpoint(self, id): """ toggle_breakpoint(int) -> None Toggles the breakpoint attribute for the module with given id """ if self.controller: module = self.controller.current_pipeline.modules[id] module.toggle_breakpoint() self.recreate_module(self.controller.current_pipeline, id) def toggle_watched(self, id): if self.controller: module = self.controller.current_pipeline.modules[id] module.toggle_watched() def print_error(self, id): toolTip = str(self.modules[id].toolTip()) errorTrace = self.modules[id].errorTrace if not toolTip and not errorTrace: return text = toolTip if errorTrace and errorTrace.strip() != 'None': text += '\n\n' + errorTrace sp = StacktracePopup(text) sp.exec_() def open_annotations_window(self, id): """ open_annotations_window(int) -> None Opens the modal annotations window for module with given id """ if self.controller: from vistrails.gui.module_info import QModuleInfo module_info = QModuleInfo.instance() module_info.show_annotations() def open_module_label_window(self, id): """ open_module_label_window(int) -> None Opens the modal module label window for setting module label """ if self.controller: module = self.controller.current_pipeline.modules[id] if module.has_annotation_with_key('__desc__'): currentLabel = module.get_annotation_by_key('__desc__').value.strip() else: currentLabel = '' (text, ok) = QtGui.QInputDialog.getText(None, 'Set Module Label', 'Enter the module label', QtGui.QLineEdit.Normal, currentLabel) if ok: if not text: if module.has_annotation_with_key('__desc__'): self.controller.delete_annotation('__desc__', id) self.recreate_module(self.controller.current_pipeline, id) else: self.controller.add_annotation(('__desc__', str(text)), id) self.recreate_module(self.controller.current_pipeline, id) ########################################################################## # Execution reporting API def check_progress_canceled(self): """Checks if the user have canceled the execution and takes appropriate action """ p = self.controller.progress if p.wasCanceled(): if p._progress_canceled: # It has already been confirmed in a progress update p._progress_canceled = False raise AbortExecution("Execution aborted by user") r = QtGui.QMessageBox.question(self.parent(), 'Execution Paused', 'Are you sure you want to abort the execution?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if r == QtGui.QMessageBox.Yes: raise AbortExecution("Execution aborted by user") else: p.goOn() def set_module_success(self, moduleId): """ set_module_success(moduleId: int) -> None Post an event to the scene (self) for updating the module color """ QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 0, '')) QtCore.QCoreApplication.processEvents() def set_module_error(self, moduleId, error, errorTrace=None): """ set_module_error(moduleId: int, error: str) -> None Post an event to the scene (self) for updating the module color """ QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 1, error, errorTrace=errorTrace)) QtCore.QCoreApplication.processEvents() def set_module_not_executed(self, moduleId): """ set_module_not_executed(moduleId: int) -> None Post an event to the scene (self) for updating the module color """ QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 2, '')) QtCore.QCoreApplication.processEvents() def set_module_active(self, moduleId): """ set_module_active(moduleId: int) -> None Post an event to the scene (self) for updating the module color """ QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 3, '')) QtCore.QCoreApplication.processEvents() def set_module_computing(self, moduleId): """ set_module_computing(moduleId: int) -> None Post an event to the scene (self) for updating the module color """ p = self.controller.progress if p is not None: self.check_progress_canceled() pipeline = self.controller.current_pipeline try: module = pipeline.get_module_by_id(moduleId) except KeyError: # Module does not exist in pipeline return p.setLabelText(module.name) QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 4, '')) QtCore.QCoreApplication.processEvents() def set_module_progress(self, moduleId, progress=0.0): """ set_module_computing(moduleId: int, progress: float) -> None Post an event to the scene (self) for updating the module color """ p = self.controller.progress if p is not None: try: self.check_progress_canceled() except AbortExecution: p._progress_canceled = True raise status = '%d%% Completed' % int(progress*100) QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 5, status, progress)) QtCore.QCoreApplication.processEvents() def set_module_persistent(self, moduleId): QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 6, '')) QtCore.QCoreApplication.processEvents() def set_module_suspended(self, moduleId, error): """ set_module_suspended(moduleId: int, error: str/instance) -> None Post an event to the scene (self) for updating the module color """ status = "Module is suspended, reason: %s" % error QtGui.QApplication.postEvent(self, QModuleStatusEvent(moduleId, 7, status)) QtCore.QCoreApplication.processEvents() def set_execution_progress(self, progress): p = self.controller.progress if p is not None: p.setValue(int(progress * 100)) def reset_module_colors(self): for module in self.modules.itervalues(): module.statusBrush = None module._needs_state_updated = True def hasMoveActions(self): controller = self.controller for (mId, item) in self.modules.iteritems(): module = controller.current_pipeline.modules[mId] (dx,dy) = (item.scenePos().x(), -item.scenePos().y()) if (dx != module.center.x or dy != module.center.y): return True return False def flushMoveActions(self): """ flushMoveActions() -> None Update all move actions into vistrail """ controller = self.controller moves = [] for (mId, item) in self.modules.iteritems(): module = controller.current_pipeline.modules[mId] (dx,dy) = (item.scenePos().x(), -item.scenePos().y()) if (dx != module.center.x or dy != module.center.y): moves.append((mId, dx, dy)) if len(moves)>0: controller.quiet = True controller.move_module_list(moves) controller.quiet = False return True return False def set_read_only_mode(self, on): """set_read_only_mode(on: bool) -> None This will prevent user to add/remove modules and connections.""" self.read_only_mode = on class QGraphicsFunctionsWidget(QtGui.QGraphicsWidget): """ GraphicsWidget containing all editable functions """ function_changed = QtCore.pyqtSignal(str, list) def __init__(self, module, parent=None, constant=None): QtGui.QGraphicsWidget.__init__(self, parent) self.function_widgets = [] height = 0 width = 0 for port_spec in module.destinationPorts(): if port_spec.name in module.editable_input_ports: # create default dummies params = [] for psi in port_spec.items: param = ModuleParam(type=psi.descriptor.name, identifier=psi.descriptor.identifier, namespace=psi.descriptor.namespace) params.append(param) function = ModuleFunction(name=port_spec.name, parameters=params) for f in module.functions: if f.name == port_spec.name: function = f for psi, param in zip(port_spec.port_spec_items, function.params): param.port_spec_item = psi function_widget = QGraphicsFunctionWidget(function, self, constant) function_widget.setPos(0, height) function_widget.function_changed.connect(self.function_changed) self.function_widgets.append(function_widget) height += function_widget.boundingRect().height() width = max(width,function_widget.boundingRect().width()) # center widgets for function_widget in self.function_widgets: for widget, w in function_widget.widths: widget.moveBy((width-w)/2, 0.0) self.bounds = QtCore.QRectF(0,0,width,height) def boundingRect(self): return self.bounds class QGraphicsFunctionWidget(QtGui.QGraphicsWidget): """ GraphicsWidget containing an editable function """ function_changed = QtCore.pyqtSignal(str, list) def __init__(self, function, parent=None, constant=None): QtGui.QGraphicsWidget.__init__(self, parent) self.function = function self.param_widgets = [] self.widths = [] # (widget, width) self.bounds = None width = 0 height = 0 SCALE = 3.0/4 # make QWidgets a bit smaller than normal MAX_WIDTH = 150 if not constant: # add name label name = self.function.name bounds = CurrentTheme.MODULE_EDIT_FONT_METRIC.boundingRect editRect = bounds(name) if editRect.width()>MAX_WIDTH: while bounds(name + '...').width() > MAX_WIDTH: name = name[:-1] name += '...' editRect = bounds(name) width = max(width, editRect.width()) fname = QtGui.QGraphicsSimpleTextItem(name, self) fname.setFont(CurrentTheme.MODULE_EDIT_FONT) fname.setPos(-1, -1) names = [] sigstring = function.sigstring for sig in sigstring[1:-1].split(','): k = sig.split(':', 2) if len(k) < 2: names.append(k[0]) else: names.append(k[1]) short_sigstring = '(' + ','.join(names) + ')' tooltip = function.name + short_sigstring fname.setToolTip(tooltip) #height += bounds(name).height() height += 11 # hardcoded because fontmetric can give wrong value for i in xrange(len(function.parameters)): param = function.parameters[i] # check psi = param.port_spec_item if psi.entry_type is not None: # !!only pull off the prefix!! options follow in camelcase prefix_end = len(psi.entry_type.lstrip(string.lowercase)) if prefix_end == 0: entry_type = psi.entry_type else: entry_type = psi.entry_type[:-prefix_end] else: entry_type = None Widget = get_widget_class(psi.descriptor, entry_type) if hasattr(Widget, 'GraphicsItem') and Widget.GraphicsItem: param_widget = Widget.GraphicsItem(param, self) # resize to MAX_WIDTH rect = param_widget.boundingRect() param_widget.setZValue(self.zValue()+0.2) scale = max(rect.width(), rect.height()) if scale>MAX_WIDTH: param_widget.setScale(MAX_WIDTH/scale) rect.setSize(rect.size()*MAX_WIDTH/scale) bg = QtGui.QGraphicsRectItem(rect, self) # TODO COLOR bg.setBrush(QtGui.QBrush(QtGui.QColor('#FFFFFF'))) bg.setZValue(-1) bg.setPos(0, height) def get_focusable(widget): return lambda e:widget.setFocus() or widget.mousePressEvent(e) bg.mousePressEvent = get_focusable(param_widget) param_widget.setPos(0, height) self.widths.append((param_widget,rect.width())) else: param_widget = Widget(param) param_widget.setAutoFillBackground(False) param_widget.setAttribute(QtCore.Qt.WA_NoSystemBackground, True) param_widget.setMaximumSize(MAX_WIDTH/SCALE, MAX_WIDTH/SCALE) param_widget.setWindowFlags(QtCore.Qt.BypassGraphicsProxyWidget) proxy = QtGui.QGraphicsProxyWidget(self) proxy.setWidget(param_widget) proxy.setScale(SCALE) rect = param_widget.geometry() rect.setSize(rect.size()*SCALE)# uninitialized bounds need to be scaled rect.moveTo(0.0,0.0) proxy.setPos(0, height) self.widths.append((proxy,rect.width())) width = max(width, rect.width()) rect.setHeight(rect.height()+2) # space between parameters height += rect.height() param_widget.contentsChanged.connect(self.param_changed) self.param_widgets.append(param_widget) self.bounds = QtCore.QRectF(0.0, 0.0, width, height) def param_changed(self, values): # get values from all parameters values = [p.contents() for p in self.param_widgets] self.function_changed.emit(self.function.name, values) def setContents(self, values): for pw, value in zip(self.param_widgets, values): pw.setContents(value, silent=True) def getContents(self): return [pw.contents() for pw in self.param_widgets] def boundingRect(self): return self.bounds def set_lod(limit, item, draw=None): """Sets the limit of level of detail used when painting items. """ # This function replaces the paint() methods of the given item and its # children. The new version doesn't actually draw any of the items if the # level of detail OF THE TOP ITEM (which is the only one checked) is under # the threshold # Only the top-level item is checked, because children might have different # scales paint_orig = item.paint # store reference to original paint method top_item = draw is None if draw is None: draw = [True] # Overrides paint() on that item def paint_with_lod_check(painter, option, widget): if top_item: draw[0] = option.levelOfDetailFromTransform( painter.worldTransform()) > limit if draw[0]: return paint_orig(painter, option, widget) item.paint = paint_with_lod_check # Recursively process children for i in item.childItems(): set_lod(limit, i, draw) class QModuleStatusEvent(QtCore.QEvent): """ QModuleStatusEvent is trying to handle thread-safe real-time module updates in the scene through post-event """ TYPE = QtCore.QEvent.Type(QtCore.QEvent.User) def __init__(self, moduleId, status, toolTip, progress=0.0, errorTrace=None): """ QModuleStatusEvent(type: int) -> None Initialize the specific event with the module status. Status 0 for success, 1 for error and 2 for not execute, 3 for active, and 4 for computing """ QtCore.QEvent.__init__(self, QModuleStatusEvent.TYPE) self.moduleId = moduleId self.status = status self.toolTip = toolTip self.progress = progress self.errorTrace = errorTrace class QPipelineView(QInteractiveGraphicsView, BaseView): """ QPipelineView inherits from QInteractiveGraphicsView that will handle drawing of module, connection shapes and selecting mechanism. """ def __init__(self, parent=None): """ QPipelineView(parent: QWidget) -> QPipelineView Initialize the graphics view and its properties """ QInteractiveGraphicsView.__init__(self, parent) BaseView.__init__(self) self.setScene(QPipelineScene(self)) self.set_title('Pipeline') self.controller = None self.detachable = True self._view_fitted = False def set_default_layout(self): from vistrails.gui.module_palette import QModulePalette from vistrails.gui.module_info import QModuleInfo self.set_palette_layout( {QtCore.Qt.LeftDockWidgetArea: QModulePalette, QtCore.Qt.RightDockWidgetArea: QModuleInfo, }) def set_action_links(self): # FIXME execute should be tied to a pipleine_changed signal... self.action_links = \ {'copy': ('module_changed', self.has_selected_modules), 'paste': ('clipboard_changed', self.clipboard_non_empty), 'layout': ('pipeline_changed', self.pipeline_non_empty), 'group': ('module_changed', self.has_selected_modules), 'ungroup': ('module_changed', self.has_selected_groups), 'showGroup': ('module_changed', self.has_selected_group), 'makeAbstraction': ('module_changed', self.has_selected_modules), 'execute': ('pipeline_changed', self.pipeline_non_empty), 'configureModule': ('module_changed', self.has_selected_module), 'documentModule': ('module_changed', self.has_selected_module), 'makeAbstraction': ('module_changed', self.has_selected_modules), 'convertToAbstraction': ('module_changed', self.has_selected_group), 'editAbstraction': ('module_changed', self.has_selected_abs), 'importAbstraction': ('module_changed', self.has_selected_abs), 'exportAbstraction': ('module_changed', self.has_selected_abs), 'publishWeb' : ('pipeline_changed', self.check_publish_db), 'publishPaper' : ('pipeline_changed', self.pipeline_non_empty), 'controlFlowAssist': ('pipeline_changed', self.pipeline_non_empty), 'redo': ('version_changed', self.can_redo), 'undo': ('version_changed', self.can_undo), } def can_redo(self, versionId): return self.controller and self.controller.can_redo() def can_undo(self, versionId): return self.controller and self.controller.can_undo() def set_action_defaults(self): self.action_defaults.update( { 'execute': [('setEnabled', True, self.set_execute_action), ('setIcon', False, CurrentTheme.EXECUTE_PIPELINE_ICON), ('setToolTip', False, 'Execute the current pipeline')], }) def set_execute_action(self): if self.controller: return self.pipeline_non_empty(self.controller.current_pipeline) return False def execute(self, target=None): try: if target is not None: self.controller.execute_user_workflow( sinks=[target], reason="Execute specific module") else: self.controller.execute_user_workflow() except Exception, e: debug.unexpected_exception(e) debug.critical("Error executing workflow: %s" % debug.format_exception(e)) else: from vistrails.gui.vistrails_window import _app _app.notify('execution_updated') def publish_to_web(self): from vistrails.gui.publishing import QVersionEmbed panel = QVersionEmbed.instance() panel.switchType('Wiki') panel.set_visible(True) def publish_to_paper(self): from vistrails.gui.publishing import QVersionEmbed panel = QVersionEmbed.instance() panel.switchType('Latex') panel.set_visible(True) def check_publish_db(self, pipeline): loc = self.controller.locator result = False if hasattr(loc,'host'): result = True return result and self.pipeline_non_empty(pipeline) def has_selected_modules(self, module, only_one=False): module_ids_len = len(self.scene().get_selected_module_ids()) #print ' module_ids_len:', module_ids_len if only_one and module_ids_len != 1: return False return module_ids_len > 0 def has_selected_module(self, module): # 'calling has_selected_module' return self.has_selected_modules(module, True) def has_selected_groups(self, module, only_one=False): module_ids = self.scene().get_selected_module_ids() if len(module_ids) <= 0: return False if only_one and len(module_ids) != 1: return False for m_id in module_ids: if not self.scene().current_pipeline.modules[m_id].is_group(): return False return True def has_selected_group(self, module): return self.has_selected_groups(True) def has_selected_abs(self, module): module_ids = self.scene().get_selected_module_ids() if len(module_ids) != 1: return False for m_id in module_ids: if not self.scene().current_pipeline.modules[m_id].is_abstraction(): return False return True def clipboard_non_empty(self): clipboard = QtGui.QApplication.clipboard() clipboard_text = clipboard.text() return bool(clipboard_text) #and \ # str(clipboard_text).startswith("<workflow") def pipeline_non_empty(self, pipeline): return pipeline is not None and len(pipeline.modules) > 0 def pasteFromClipboard(self): center = self.mapToScene(self.width()/2.0, self.height()/2.0) self.scene().pasteFromClipboard((center.x(), -center.y())) def setQueryEnabled(self, on): QInteractiveGraphicsView.setQueryEnabled(self, on) if not self.scene().noUpdate and self.scene().controller: self.scene().setupScene(self.scene().controller.current_pipeline) def setReadOnlyMode(self, on): self.scene().set_read_only_mode(on) def set_title(self, title): BaseView.set_title(self, title) self.setWindowTitle(title) def set_controller(self, controller): oldController = self.controller if oldController != controller: #if oldController is not None: # self.disconnect(oldController, # QtCore.SIGNAL('versionWasChanged'), # self.version_changed) # is this needed. It causes errors in api tests #oldController.current_pipeline_view = None self.controller = controller self.scene().controller = controller # self.connect(controller, # QtCore.SIGNAL('versionWasChanged'), # self.version_changed) # self.module_info.set_controller(controller) # self.moduleConfig.controller = controller # controller.current_pipeline_view = self.scene() def set_to_current(self): QModuleInfo.instance().setReadOnly(self.scene().read_only_mode) self.controller.set_pipeline_view(self) def get_long_title(self): pip_name = self.controller.get_pipeline_name() vt_name = self.controller.name self.long_title = "Pipeline %s from %s" % (pip_name,vt_name) return self.long_title def get_controller(self): return self.controller def version_changed(self): self._view_fitted = False self.scene().setupScene(self.controller.current_pipeline) def run_control_flow_assist(self): currentScene = self.scene() if currentScene.controller: selected_items = currentScene.get_selected_item_ids(True) if selected_items is None: selected_items = ([],[]) selected_module_ids = selected_items[0] selected_connection_ids = selected_items[1] if len(selected_module_ids) > 0: try: dialog = QControlFlowAssistDialog( self, selected_module_ids, selected_connection_ids, currentScene) except MissingPackage: debug.critical("The controlflow package is not available") else: dialog.exec_() else: QtGui.QMessageBox.warning( self, 'No modules selected', 'You must select at least one module to use the ' 'Control Flow Assistant') def done_configure(self, mid): self.scene().perform_configure_done_actions(mid) def paintModuleToPixmap(self, module_item): m = self.matrix() return module_item.paintToPixmap(m.m11(), m.m22()) def viewSelected(self): if not self._view_fitted and self.isVisible(): # We only do this once after a version_changed() call self.zoomToFit() self._view_fitted = True ################################################################################ # Testing class TestPipelineView(vistrails.gui.utils.TestVisTrailsGUI): def test_quick_change_version_with_ports(self): import vistrails.core.system filename = (vistrails.core.system.vistrails_root_directory() + '/tests/resources/triangle_count.vt') view = vistrails.api.open_vistrail_from_file(filename) vistrails.api.select_version(-1, view.controller) vistrails.api.select_version('count + area', view.controller) vistrails.api.select_version('writing to file', view.controller) def test_change_version_with_common_connections(self): import vistrails.core.system filename = (vistrails.core.system.vistrails_root_directory() + '/tests/resources/terminator.vt') view = vistrails.api.open_vistrail_from_file(filename) vistrails.api.select_version('Image Slices HW', view.controller) vistrails.api.select_version('Combined Rendering HW', view.controller) def test_switch_mode(self): vistrails.api.switch_to_pipeline_view() vistrails.api.switch_to_history_view() vistrails.api.switch_to_query_view() vistrails.api.switch_to_pipeline_view() vistrails.api.switch_to_history_view() vistrails.api.switch_to_query_view() def test_group(self): vistrails.api.new_vistrail() basic_pkg = get_vistrails_basic_pkg_id() m1 = vistrails.api.add_module(0, 0, basic_pkg, 'File', '') m2 = vistrails.api.add_module(0, -100, basic_pkg, 'File', '') m3 = vistrails.api.add_module(0, -100, basic_pkg, 'File', '') r = vistrails.api.get_module_registry() src = r.get_port_spec(basic_pkg, 'File', None, 'value_as_string', 'output') dst = r.get_port_spec(basic_pkg, 'File', None, 'name', 'input') # src = r.module_source_ports(True, basic_pkg, 'File', '')[1] # assert src.name == 'value_as_string' # dst = r.module_destination_ports(True, basic_pkg, 'File', '')[1] # assert dst.name == 'name' vistrails.api.add_connection(m1.id, src, m2.id, dst) vistrails.api.add_connection(m2.id, src, m3.id, dst) vistrails.api.create_group([0, 1, 2], [0, 1])
There are so many emotions engulfed inside you and there is so little you can do about it. Every time you look at something or see someone, certain set of thoughts come into your mind. They can (thoughts) can be short lived or long lived. You never really share them or at times you don't really have anyone to share with. Often they die out or get buried deep inside your mind. However, for some like us, from whom emotions and thoughts have very high regards in our life, and we cherish them by our writing. For me, it was very important to make my thoughts and opinions reached to someone. And hence started my The World Through My View, later renamed as Pseudofiction. Tortured by the Indian education system, burned by the intense medical studies, my life in my double room apartment in Janakpuri was distorted. Never really cared to learn things, all I did was just sit back and imagine things. And then came up the idea, let me preserve whatever I have in my mind. Broadband revolution just reached me, Blogger just impressed me and on 21st December 2012, I posted my first experience of the city, Locked at Uttam Nagar: My First Experience in Delhi. It was very ironic that the city I love so much today did not give me that good an experience in the eary days. I used to miss home and it was a little difficult for me to adjust here, for reasons well explained in my very first post. The response was good, as I slowing started to gain readership I decided to market my blog. With no intentions of becoming a college celebrity or a social network sensation (done by many these days), I started my Blogging game. Pesudofiction landed up me with Barefoot, with whom I am working currently. It gave me an opportunity to meet International football star Drogba, a dinner with Minisha Lamba and also helped me get into Tehelka. Today, its a important day for me, two years back I started this blog and on the very exact day, I crossed 50000 views. The love and response is awesome. 50K pageviews for a personal blog is a little too much to ask, but fortunately, I did achieve this.
''''''''''''''''''''''''' imports ''''''''''''''''''''''''''' # Built ins import tkinter import threading SCREEN_MEMORY_MAP = 16384 ''''''''''''''''''''''''' screen ''''''''''''''''''''''''''' class Screen(): ''' 16 bit screen with a 512 x 256 pixels display. Specifications hardcoded for simplicity. Data stored using a 256 x 512 array to help with tkinter draw speed (In lieu of using a 1 x 8192 array which more closely resembles RAM). ''' def __init__( self, main_memory ): self.main_memory = main_memory self.N = 16 self.nRegisters = 8192 # Screen dimensions --- self.width = 512 self.height = 256 self.registersPerRow = self.width // self.N # Pixel array --- self.pixels = [ [0] * self.width for _ in range( self.height ) ] # Initialize tkinter --- self.refreshRate = 100 # ms self.root = None self.img = None threading.Thread( target = self._initTkinter, name = 'screen_thread' ).start() def update( self ): # Get screen data from Hack's main memory --- self.readRAM() # Format pixel array to tkinter string --- data = [ '{' + ''.join( map( str, row ) ) + '} ' for row in self.pixels ] data = ''.join( data ) data = data.replace( '0', 'white ' ).replace( '1', 'black ' ) # Update tkinter --- self._updateTkinterImg( data ) def readRAM( self ): # Get screen data from Hack's main memory for address in range( self.nRegisters ): data = self.main_memory.read( SCREEN_MEMORY_MAP + address ) self.write( data, address ) def write( self, x, address ): # Psuedo N bit RAM interface --- # Maps RAM access style to pixel array access style row = address // self.registersPerRow col_0 = address % self.registersPerRow * self.N for col, bit in zip( range( col_0, col_0 + self.N ), range( 0, self.N ) ): self.pixels[row][col] = x[bit] # Tkinter --- def _initTkinter( self ): self.root = tkinter.Tk() self.root.wm_title('Hack') self.root.iconbitmap('favicon.ico') self.root.bind( '<Escape>', self._quitTkinter ) self.img = tkinter.PhotoImage( width = self.width, height = self.height ) label = tkinter.Label(self.root) label.pack() label.config( image = self.img ) self.update() self.root.mainloop() def _updateTkinterImg( self, data ): self.img.put( data, to = (0, 0, self.width, self.height) ) self.root.after( self.refreshRate, self.update ) # set timer def _quitTkinter( self, ev = None ): self.root.quit() screen = Screen() v = '1' * 16 screen.write( v, 0 * 32 + 10 ) screen.write( v, 1 * 32 + 10 ) screen.write( v, 2 * 32 + 10 ) screen.write( v, 3 * 32 + 10 ) screen.write( v, 4 * 32 + 10 )
Valentine’s Day is right around the corner, so it’s time to start planning the perfect way to celebrate the occasion! Don’t fall into the pattern of a typical romantic dinner date; instead think outside the box and switch things up! From staying home for dinner to catching a comedy show, there are plenty of things to do that will make for a memorable Valentine’s Day! Dancing is a great Valentine’s Day date night idea, and yes we are talking about real dancing! There are plenty of classes out there to take and it’s a great way to enjoy each other’s company! Find a salsa class or any class that interests you and spend the night with each other picking up a new hobby! Instead of going out for dinner for Valentine’s Day, stay in to enjoy a dinner and a movie at home! You have the freedom to make the night whatever you want with this date night idea! From cooking or ordering out to all the different movie selections to choose from, you have the ability to perfectly plan the best Valentine’s Day date night for you and your partner! Nothing is better than laughing the night away with your significant other and the best way to do that is to catch a comedy in show! Check if your favorite comedian is doing a show in town or go to a local comedy club and enjoy the variety of jokes while spending time with each other throughout the night! Great as an everyday date and Valentine’s date, going to the movies is a excellent option to spend the special day with your significant other. There will definitely be plenty of romantic movies to check out, but when deciding what to watch, keep all the different genres in mind before choosing! Many museums hold special events after-hours, especially when it comes to Valentine’s Day! Instead of a typical V-Day date, opt for a night at the museum, which is bound to be a quite and romantic night. Nothing brings people together more than cheering on their favorite sports team! If you and your significant other love sports and have a competitive side, then buying tickets to a local sporting event is a great Valentine’s Day date idea! You could even spice things up and take a bet on who the winning team will be to see who will buy dinner that night! Nothing is more romantic and relaxing than having a spa day with your partner. Whether you go for a couples massage or decide to take the day off and spend the whole day relaxing, this is a great non-traditional way to spend Valentine’s Day! There is a reason many rom-coms always show couples ice-skating! You’ll get to hold on to your partner while skating the night away. Afterwards, enjoy a nice cup of hot cocoa to keep you warm during the winter weather! Looking for a new home to move into? Then, check out Judd Builders! With over 50 years of experience we build many wonderful planned communities that fit the needs of the modern homebuyer. From the popular The Reserve at Glen Loch to the spectacular views at Brookshire, there is bound to be a community that is the perfect fit for you and you family! If you have any questions, feel free to contact us! We’d love to hear from you!
from dcos import cmds import pytest @pytest.fixture def args(): return { 'cmd-a': True, 'cmd-b': True, 'cmd-c': False, 'arg-1': 'arg-1', 'arg-2': 'arg-2', 'arg-0': 'arg-0', } def test_single_cmd(args): commands = [ cmds.Command( hierarchy=['cmd-a', 'cmd-b'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=function), ] assert cmds.execute(commands, args) == 1 def test_multiple_cmd(args): commands = [ cmds.Command( hierarchy=['cmd-c'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=pytest.fail), cmds.Command( hierarchy=['cmd-a', 'cmd-b'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=function), ] assert cmds.execute(commands, args) == 1 def test_no_matching_cmd(args): commands = [ cmds.Command( hierarchy=['cmd-c'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=pytest.fail), ] with pytest.raises(Exception): cmds.execute(commands, args) def test_similar_cmds(args): commands = [ cmds.Command( hierarchy=['cmd-a', 'cmd-b'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=function), cmds.Command( hierarchy=['cmd-a'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=pytest.fail), ] assert cmds.execute(commands, args) == 1 def test_missing_cmd(args): commands = [ cmds.Command( hierarchy=['cmd-d'], arg_keys=['arg-0', 'arg-1', 'arg-2'], function=pytest.fail), ] with pytest.raises(KeyError): returncode, err = cmds.execute(commands, args) def test_missing_arg(args): commands = [ cmds.Command( hierarchy=['cmd-a'], arg_keys=['arg-3'], function=pytest.fail), ] with pytest.raises(KeyError): returncode, err = cmds.execute(commands, args) def function(*args): for i in range(len(args)): assert args[i] == 'arg-{}'.format(i) return 1
David, who attended Dale Chihuly's Pilchuck Glass School, developed a unique style of cutting crystal based on his observations of crystal, ice and light. Due to its opalescent, mesmerizing nature and popularity, Del Mar Gifts has trouble keeping LeightWorks Jewelry in stock! ​Artdivas is a mother/daughter company dedicated to both original artistic expression and the highest quality reproduction. Our dynamic and diverse styles reflect our varied interests from ocean waves to western art. Roy Kerckhoffs is an award-winning artist who has had his work recognized throughout California for his unique style of hand colored photographs. Roy is mostly known for coastal themes and ghost towns. He uses high-contrast black and white photographs and hand colors them with an oil-based paint on photo paper or with acrylics on canvas. Since 2002, Point of View Photography has been a provider of unique local photographic images produced as high quality notecards, boxed notecard sets, gift enclosure cards, acrylic magnets, acrylic keychains and matted enlargements.
from distutils.core import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name='moira-client', version='2.4', description='Client for Moira - Alerting system based on Graphite data', keywords='moira monitoring client metrics alerting', long_description=""" Moira is a real-time alerting tool, based on Graphite data. moira-client is a python client for Moira API. Key features: - create, update, delete, manage triggers - create, delete, update subscriptions - manage tags, patterns, notifications, events, contacts """, author = 'Alexander Lukyanchenko', author_email = 'al.lukyanchenko@gmail.com', packages=[ 'moira_client', 'moira_client.models' ], classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Topic :: System :: Monitoring', "License :: OSI Approved :: MIT License" ], url='https://github.com/moira-alert/python-moira-client', install_requires=required )
This summer is going by so quickly! In Michigan the 4 th of July can be cold, hot, rainy, sunny or any other combination. Being a Michigander requires the ability to carry copious amounts of clothing in our vehicle so we can change when the weather does. It’s a day spent eating burgers, hot dogs, and brats—running around with sparklers and possibly even attending a parade. The day is wrapped up with the explosion of color and light in the sky, followed by ooh’s and aah’s. Going to a parade on 4 th of July is interesting because you usually see classic cars, fire trucks, the local politicians throwing candy, Boy Scouts, people on horseback, etc. I remember sitting at the Dorr 4 th of July parade every year and trying to keep three little kids from jumping in front of the beautiful classic cars for a tootsie roll that was just out of their reach. Watching the excitement on their faces as the fire trucks and police vehicles rolled past. Americans have a deep love for their vehicles. Whether it is the vehicle that gets you to work and your children to their activities every day or the classic vehicle that sits in the garage and is taken out for a road trip several times a year and maintained in pristine condition. It may be the 4x4 truck that you have invested a lot of time and money in— modifying it into your dream vehicle. It may be your imported vehicle that you’ve had tuned and well cared for that makes you smile every time you turn the key. Americans history can be observed through the vehicles and forms of transportation that have been a part of our lives. It also shows the evolution of our country. Wagon trains traveling west were driven by a different type of horsepower. Train tracks being laid to transport goods and people. Trucks lightening the load for farmers. Vehicles have changed the way we live and work and as technology advances, they will continue to do so. Whatever you are doing for Independence Day, take a moment to appreciate this great country we live in, the people that have fought and died for our freedom and the fact that we can celebrate how we choose to that day. Happy Fourth of July from all of us at Arie Nol Auto Center!
__author__ = 'dcristian' import threading import utils import prctl from main.logger_helper import L from main import thread_pool import psutil import os from common import Constant class P: query_count = None query_cumulative_time_miliseconds = None min_query_time_miliseconds = None max_query_time_miliseconds = None log_file = None def add_query(start_time, query_details=None): elapsed = int((utils.get_base_location_now_date() - start_time).total_seconds()*1000) if not P.query_count: P.query_count = 0 P.query_cumulative_time_miliseconds = 0 P.max_query_time_miliseconds = elapsed P.min_query_time_miliseconds = elapsed if P.max_query_time_miliseconds < elapsed: P.max_query_time_miliseconds = elapsed L.l.debug("Longest query details:{}".format(str(query_details)[:50])) L.l.debug("Count={} avg={} min={} max={}".format( P.query_count, P.query_cumulative_time_miliseconds / P.query_count, P.min_query_time_miliseconds, P.max_query_time_miliseconds)) if P.min_query_time_miliseconds > elapsed: P.min_query_time_miliseconds = elapsed P.query_count += 1 P.query_cumulative_time_miliseconds += elapsed L.l.debug("Count={} avg={} min={} max={}".format(P.query_count, P.query_cumulative_time_miliseconds / P.query_count, P.min_query_time_miliseconds, P.max_query_time_miliseconds)) return elapsed # https://stackoverflow.com/questions/34361035/python-thread-name-doesnt-show-up-on-ps-or-htop def _thread_for_ident(ident): return threading._active.get(ident) def _save_threads_cpu_percent(p, interval=0.1): total_percent = p.cpu_percent(interval) total_time = sum(p.cpu_times()) list = [] with open(P.log_file, "w") as log: total = 0 for t in p.threads(): load = round(total_percent * ((t.system_time + t.user_time)/total_time), 2) total += load th = _thread_for_ident(t.id) if th is None: tname = "None" else: tname = th.name log.write("{} % \t {} \t\t\t\t {}\n".format(load, tname, t)) log.write("Total={} %\n".format(total)) def _cpu_profiling(): # p = psutil.Process(os.getpid()) # mem = p.get_memory_info()[0] / float(2 ** 20) # treads_list = p.threads() _save_threads_cpu_percent(p) # li = get_threads_cpu_percent(p) # with open(P.log_file, "w") as log: #log.write(mem) #log.write("PID={}\n".format(os.getpid())) #log.write("Threads: {}\n".format(li)) def thread_run(): prctl.set_name("performance") threading.current_thread().name = "performance" # _cpu_profiling() prctl.set_name("idle_performance") threading.current_thread().name = "idle_performance" def init(log_file): P.log_file = log_file thread_pool.add_interval_callable(thread_run, run_interval_second=5)
At Linden Primary School, we acknowledge that starting school is an important step for every child and parent. This should be prepared for and looked forward to as an exciting positive experience. We aim to effect a smooth and enjoyable transition from children’s home and pre-school experiences to the learning environment of a school. We provide a secure stimulating environment within which young children can grow in confidence and independence. Through a broad and balanced curriculum, intellectual, emotional, physical, spiritual, moral, social and cultural development can be fostered. In line with the principles for Early Years education, outlined in the DfEE document ‘Early Learning Goals’, we acknowledge that children are entitled to a curriculum provision which ‘supports and extends knowledge, understanding, skills and confidence’ and enables them to ‘overcome any disadvantage’. Learning is promoted in the Nursery and Reception Class through a structured early years curriculum enabling children to build on what they already know, and explore their environment through first-hand experiences. Through teacher-led activities, self directed tasks and play opportunities, children will be encouraged to develop their communication skills, giving them the confidence to meet the challenges of new and varied learning experiences. Children progress at their own pace, aspiring to high but achievable learning expectations, ensuring that they experience the satisfaction of success and become valued members of the class community, developing a strong self-image and high self esteem. With these aims in mind, we trust that the children will enjoy their first year at school and be provided with a firm foundation on which to base future learning, enabling them to develop into responsible and caring individuals.
# -*- encoding: utf-8 -*- from functools import wraps from .utils import NULL from .exceptions import DelimiterError """ This module contains decorators used to handle the whitespace between tokens, when parsing. """ def ignore(string): """ A whitespace handler that ignores the whitespace between tokens. This means that it doesn't matter if there is whitespace or not - any whitespace is stripped from the input string before the next token is parsed. """ if string and string[0] == NULL: string = string[1:] return string.lstrip() def ignore_specific(whitespace): """ A whitespace handler that ignores certain whitespace between tokens. This means that it doesn't matter if there is whitespace or not - the chosen whitespace is stripped from the input string before the next token is parsed. """ def handler(string): if string and string[0] == NULL: string = string[1:] return string.lstrip(whitespace) return handler def require(whitespace, ignore=False): """ A factory for whitespace handlers that require a given whitespace 'phrase' between tokens. If the required whitespace is not present an exception is raised. Use the 'ignore' parameter to ignore any additional whitespace above that which is required. This function generates a handler function for make_handler. Returns a function. """ n = len(whitespace) def handler(string): if string and string[0] == NULL: return string[1:] elif string[:n] != whitespace: raise DelimiterError('"%s..." not delimited' % string[:50]) return string[n:].lstrip() if ignore else string[n:] return handler
Giggs IT Solutions Pvt Ltd L. - Mobile based development both in IOS and Android environment. - Microsoft Technologies: Visual Studio .Net 2003, 2005, 2008, C#, VB.Net, ADO.Net, ASP.Net 1.1, 2.0, 3.0, 3.5. - Industry Types: E-commerce, Social Community, Job Sites, Health & Fitness, Travel & Tourism, Corporate, AJAX based, Real Estate, Service Portals, Educational. - Payment Gateways: Paypal pro & IPN, Authrized.net, Protx, Google Checkout, WorldPay, Payex, SecurePay, Google Checkout, EBS. - Internet Marketing: Link Building, Search Engine Optimization, Content Syndication, Pay per Click, Social Media Marketing, Social Network Marketing.
import pygame class Tile: def __init__(self, image, solid = False): self.sprite = image self.solid = solid class MovableCharacter: def move(self,speed = 2): direction = self.current_direction if direction == Direction.UP: self.yOffset -= speed elif direction == Direction.RIGHT: self.xOffset += speed elif direction == Direction.DOWN: self.yOffset += speed elif direction == Direction.LEFT: self.xOffset -= speed if ((direction == Direction.UP or direction == Direction.DOWN) and (self.yOffset % 50 == 0)) or ((direction == Direction.LEFT or direction == Direction.RIGHT) and (self.xOffset % 50 == 0)): if(self.yOffset < 0): self.gridY -= 1 elif(self.yOffset > 0): self.gridY += 1 self.yOffset = 0; if(self.xOffset < 0): self.gridX -= 1 elif(self.xOffset > 0): self.gridX += 1 self.xOffset = 0; self.moving = False; def change_direction(self, direction, override_opt = False): # Optimization if not override_opt and self.current_direction == direction: return self.current_direction = direction name = self.directional_sprites[direction] self.sprite = self.load_function(name) def __init__(self, name, load_function,list_of_bots, directional_sprites,x=0,y=0, gold=0): # for now this is just hard coded # placeholder sprite's justgonna be one of the directional sprites self.moving = False self.load_function = load_function self.directional_sprites = directional_sprites self.gridX = x self.gridY = y self.xOffset = 0 self.yOffset = 0 self.name = name self.gold = gold self.current_direction = Direction.UP self.list_of_bots = list_of_bots class MainPlayer(MovableCharacter): pass class EnemyPlayer(MovableCharacter): def move(self,speed = 2): pass # for now.. but implement ai class Direction: UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class Element: NONE = 0 FIRE = 1 EARTH = 2 WATER = 3 AIR = 4 #Z- renamed these for code readability, feel free to call them anything in game class GenericBot: def __init__(self, name, sprite, speed=10, health=100,mana=100,element=Element.NONE,spell_xp=dict(),list_of_spells=[],queue_of_code_blocks = list(),pOwned = False): self.queue_of_code_blocks = queue_of_code_blocks self.name = name self.sprite = sprite self.baseSpeed = speed self.speed = speed self.maxHealth = health self.health = health self.maxMana = mana self.mana = mana self.element = element self.spell_xp = spell_xp self.list_of_spells = list_of_spells self.pOwned = pOwned #Boolean, 'player owned': self.location = None #Gets set once battle begins # Let's you change what the string representation of this class is def __repr__(self): return "Health: {} Mana: {} Speed: {}".format(str(self.health), str(self.mana), str(self.speed)) class Spells: def __init__(self, name, mana_cost=25, attack_power=5,multiplier=dict(),accuracy=0.5): self.name = name self.mana_cost = mana_cost self.attack_power = attack_power self.multiplier = multiplier self.accuracy = accuracy class CodeBlock(object): def __init__(self): self.font = pygame.font.SysFont("comicsansms", 24) # Renders the Block to the screen. Should return the total height of the block. def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): raise NotImplementedError # Gets the screen height of the block def getRenderHeight(self): raise NotImplementedError # Gets the count of arrow positions within this block (typically only the one after it) def getArrowCount(self): return 1 # Gets the total block count within this block (typically just the one) def getBlockCount(self): return 1 # Executes the Block, taking into consideration whether or not this is a calc-mana-cost-only dry run. Should return mana spent in total, or a tuple of (mana total, flag saying 'had hit an End Turn block'). def execute(self, ownerBot, opponentBot, callback, dryRun = False): pass # Inserts a new Block somewhere in the listing. True if successful, false if failed; block containers should implement something other than "always fail" def insert(self, blockToInsert, arrowIndex): return False # Removes the Block at the specific index inside this Block. True if successful, false if failed; block containers should implement something other than "always fail" def remove(self, index): return False # Fetch the Block at a given index. def fetch(self, index): if(index == 0): return self else: return None # Comment Block. Does nothing, handy for in-code notes. class CommentBlock(CodeBlock): def __init__(self): super(CommentBlock, self).__init__() self.comment = ""; self.cwidth, self.cheight = self.font.size("# ") self.fontRender = self.font.render("# ", 0, (0, 0, 0), (190, 255, 190)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (190, 255, 190), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): return 0 # Comment blocks do nothing def setComment(self, newComment): self.comment = newComment self.cwidth, self.cheight = self.font.size("# " + self.comment) self.fontRender = self.font.render("# " + self.comment, 0, (0, 0, 0), (190, 255, 190)) # Say Block. Causes the Golem to say a bit of text. class SayBlock(CodeBlock): def __init__(self): super(SayBlock, self).__init__() self.message = ""; self.cwidth, self.cheight = self.font.size("Say \"\"") self.fontRender = self.font.render("Say \"\"", 0, (0, 0, 0), (205, 205, 205)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (205, 205, 205), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): callback(ownerBot.name + " says: " + self.message) def setMessage(self, newMessage): self.message = newMessage self.cwidth, self.cheight = self.font.size("Say \"" + self.message + "\"") self.fontRender = self.font.render("Say \"" + self.message + "\"", 0, (0, 0, 0), (205, 205, 205)) # While Block. Performs a task while a condition remains true. class WhileBlock(CodeBlock): def __init__(self): super(WhileBlock, self).__init__() self.blocks = [] _, self.cheight = self.font.size("WAAA") self.fontRender = self.font.render("Do Forever", 0, (0, 0, 0), (255, 255, 190)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + 196 + 26, yOffset), (xOffset + 196 + 26, yOffset + 6), (xOffset + 196 + 16, yOffset + 1)]) pygame.draw.rect(surface, (255, 255, 190), (xOffset, yOffset + 1, 196, self.cheight + 6)) heightsum = self.cheight + 8 selCount = 1 for block in self.blocks: heightsum += block.render(surface, xOffset + 8, yOffset + heightsum, selIndex - selCount, mode) if(mode == 0): selCount += block.getArrowCount() else: selCount += block.getBlockCount() if(mode == 0 and selIndex == selCount): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + heightsum + 1), (xOffset - 10, yOffset + 6 + heightsum), (xOffset - 10, yOffset + heightsum), (xOffset + 196 + 26, yOffset + heightsum), (xOffset + 196 + 26, yOffset + 6 + heightsum), (xOffset + 196 + 16, yOffset + heightsum + 1)]) pygame.draw.rect(surface, (255, 255, 190), (xOffset, yOffset + 1 + heightsum, 196, self.cheight + 6)) pygame.draw.rect(surface, (255, 255, 190), (xOffset, yOffset + 1, 6, heightsum + self.cheight + 8 - 2)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, 196, heightsum + self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, 196, heightsum + self.cheight + 6), 2) return heightsum + self.cheight + 8 def getArrowCount(self): rtn = 2 for block in self.blocks: rtn += block.getArrowCount() return rtn def getBlockCount(self): rtn = 1 for block in self.blocks: rtn += block.getBlockCount() return rtn def getRenderHeight(self): heightsum = self.cheight + 8 for block in self.blocks: heightsum += self.trueBlocks[i].getRenderHeight() return heightsum + self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): for block in self.blocks: block.execute(ownerBot,opponentBot, callback) def insert(self, blockToInsert, arrowIndex): if(arrowIndex == 0): # Insert before current block return False # Should have been handled by calling function elif(arrowIndex == 1): # Insert before rest of list self.blocks = [blockToInsert] + self.blocks return True elif(arrowIndex == self.getArrowCount() - 1): # Insert at end of list self.blocks.append(blockToInsert) return True else: # Insert into middle of list currArrowIndex = arrowIndex - 1; for i in range(0, len(self.blocks)): if(currArrowIndex == 0): self.blocks.insert(i, blockToInsert) return True elif(self.blocks[i].insert(blockToInsert, currArrowIndex)): return True else: currArrowIndex -= self.blocks[i].getArrowCount() return False def remove(self, index): if(index == 0): # Remove current block return False # Should have been handled by calling function else: currIndex = index - 1; for i in range(0, len(self.blocks)): if(currIndex == 0): del self.blocks[i] return True elif(self.blocks[i].remove(currIndex)): return True else: currIndex -= self.blocks[i].getBlockCount() return False def fetch(self, index): if(index == 0): return self else: currIndex = index - 1; for i in range(0, len(self.blocks)): if(currIndex == 0): return self.blocks[i] rtn = self.blocks[i].fetch(currIndex) if(rtn != None): return rtn currIndex -= self.blocks[i].getBlockCount() return None # For Block. Performs a task on each Golem being faced. Do not implement, only doing 1v1 battles atm. #class ForBlock(CodeBlock): # def __init__(self): # pass # def render(self, surface, xOffset = 0, yOffset = 0): # return 0 # def execute(self, ownerBot, opponentBot, dryRun = False): # return 0 # End Turn Block. Immediately stops the Golem's execution, and ends their turn. class EndTurnBlock(CodeBlock): def __init__(self): super(EndTurnBlock, self).__init__() self.cwidth, self.cheight = self.font.size("End my Turn") self.fontRender = self.font.render("End my Turn", 0, (0, 0, 0), (255, 64, 64)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (255, 64, 64), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): return (0, True) # Branch Block, Mana. Allows for some decision making based on how much Mana a Golem has in reserve. class IfManaBlock(CodeBlock): def __init__(self): super(IfManaBlock, self).__init__() self.mthresh = 0 self.trueBlocks = [] self.falseBlocks = [] self.cwidth, self.cheight = self.font.size("If I have more than 999999 Mana") self.fontRender = self.font.render("If I have more than 0 Mana", 0, (0, 0, 0), (128, 205, 255)) self.elseRender = self.font.render("Otherwise", 0, (0, 0, 0), (128, 205, 255)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (128, 205, 255), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) heightsum = self.cheight + 8 selCount = 1 for i in range(0, len(self.trueBlocks)): heightsum += self.trueBlocks[i].render(surface, xOffset + 8, yOffset + heightsum, selIndex - selCount, mode) if(mode == 0): selCount += self.trueBlocks[i].getArrowCount() else: selCount += self.trueBlocks[i].getBlockCount() if(mode == 0 and selIndex == selCount): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + heightsum + 1), (xOffset - 10, yOffset + 6 + heightsum), (xOffset - 10, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + 6 + heightsum), (xOffset + self.cwidth + 16, yOffset + heightsum + 1)]) if(mode == 0): selCount += 1 pygame.draw.rect(surface, (128, 205, 255), (xOffset, yOffset + 1 + heightsum, self.cwidth + 16, self.cheight + 6)) secondBlitHeight = heightsum heightsum += self.cheight + 8 for i in range(0, len(self.falseBlocks)): heightsum += self.falseBlocks[i].render(surface, xOffset + 8, yOffset + heightsum, selIndex - selCount, mode) if(mode == 0): selCount += self.falseBlocks[i].getArrowCount() else: selCount += self.falseBlocks[i].getBlockCount() if(mode == 0 and selIndex == selCount): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + heightsum + 1), (xOffset - 10, yOffset + 6 + heightsum), (xOffset - 10, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + 6 + heightsum), (xOffset + self.cwidth + 16, yOffset + heightsum + 1)]) pygame.draw.rect(surface, (128, 205, 255), (xOffset, yOffset + 1 + heightsum, self.cwidth + 16, self.cheight + 6)) pygame.draw.rect(surface, (128, 205, 255), (xOffset, yOffset + 1, 6, heightsum + self.cheight + 8 - 2)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) surface.blit(self.elseRender, (xOffset + 4, yOffset + secondBlitHeight + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, heightsum + self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, heightsum + self.cheight + 6), 2) return heightsum + self.cheight + 8 def getArrowCount(self): rtn = 3 for block in self.trueBlocks: rtn += block.getArrowCount() for block in self.falseBlocks: rtn += block.getArrowCount() return rtn def getBlockCount(self): rtn = 1 for block in self.trueBlocks: rtn += block.getBlockCount() for block in self.falseBlocks: rtn += block.getBlockCount() return rtn def getRenderHeight(self): heightsum = self.cheight + 8 for i in range(0, len(self.trueBlocks)): heightsum += trueBlocks[i].getRenderHeight() heightsum += self.cheight + 8 for i in range(0, len(self.falseBlocks)): heightsum += falseBlocks[i].getRenderHeight() return heightsum + self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): if ownerBot.mana > self.mthresh: for t_block in self.trueBlocks: t_block.execute(ownerBot, opponentBot,callback) else: for f_block in self.falseBlocks: f_block.execute(ownerBot, opponentBot,callback) def insert(self, blockToInsert, arrowIndex): if(arrowIndex == 0): # Insert before current block return False # Should have been handled by calling function else: # Insert into middle of list currArrowIndex = arrowIndex - 1; for i in range(0, len(self.trueBlocks)): if(currArrowIndex == 0): self.trueBlocks.insert(i, blockToInsert) return True elif(self.trueBlocks[i].insert(blockToInsert, currArrowIndex)): return True else: currArrowIndex -= self.trueBlocks[i].getArrowCount() if(currArrowIndex == 0): # Insert at end of TrueBlocks self.trueBlocks.append(blockToInsert) return True currArrowIndex -= 1 for i in range(0, len(self.falseBlocks)): if(currArrowIndex == 0): self.falseBlocks.insert(i, blockToInsert) return True elif(self.falseBlocks[i].insert(blockToInsert, currArrowIndex)): return True else: currArrowIndex -= self.falseBlocks[i].getArrowCount() if(currArrowIndex == 0): # Insert at end of FalseBlocks self.falseBlocks.append(blockToInsert) return True return False def remove(self, index): if(index == 0): # Remove current block return False # Should have been handled by calling function else: currIndex = index - 1; for i in range(0, len(self.trueBlocks)): if(currIndex == 0): del self.trueBlocks[i] return True elif(self.trueBlocks[i].remove(currIndex)): return True else: currIndex -= self.trueBlocks[i].getBlockCount() for i in range(0, len(self.falseBlocks)): if(currIndex == 0): del self.falseBlocks[i] return True elif(self.falseBlocks[i].remove(currIndex)): return True else: currIndex -= self.falseBlocks[i].getBlockCount() return False def fetch(self, index): if(index == 0): return self else: currIndex = index - 1; for i in range(0, len(self.trueBlocks)): if(currIndex == 0): return self.falseBlocks[i] rtn = self.falseBlocks[i].fetch(currIndex) if(rtn != None): return rtn currIndex -= self.falseBlocks[i].getBlockCount() for i in range(0, len(self.falseBlocks)): if(currIndex == 0): return self.falseBlocks[i] rtn = self.falseBlocks[i].fetch(currIndex) if(rtn != None): return rtn currIndex -= self.falseBlocks[i].getBlockCount() return None def setThresh(self, newThresh): self.mthresh = newThresh self.fontRender = self.font.render("If I have more than " + str(self.mthresh) + " Mana", 0, (0, 0, 0), (128, 205, 255)) # Branch Block, Health. Allows for some decision making based on how much Health a Golem has. class IfOwnHealthBlock(CodeBlock): def __init__(self): super(IfOwnHealthBlock, self).__init__() self.hthresh = 0 self.trueBlocks = [] self.falseBlocks = [] self.cwidth, self.cheight = self.font.size("If I have less than 999999 Health") self.fontRender = self.font.render("If I have less than 0 Health", 0, (0, 0, 0), (255, 200, 200)) self.elseRender = self.font.render("Otherwise", 0, (0, 0, 0), (255, 200, 200)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (255, 200, 200), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) heightsum = self.cheight + 8 selCount = 1 for i in range(0, len(self.trueBlocks)): heightsum += self.trueBlocks[i].render(surface, xOffset + 8, yOffset + heightsum, selIndex - selCount, mode) if(mode == 0): selCount += self.trueBlocks[i].getArrowCount() else: selCount += self.trueBlocks[i].getBlockCount() if(mode == 0 and selIndex == selCount): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + heightsum + 1), (xOffset - 10, yOffset + 6 + heightsum), (xOffset - 10, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + 6 + heightsum), (xOffset + self.cwidth + 16, yOffset + heightsum + 1)]) if(mode == 0): selCount += 1 pygame.draw.rect(surface, (255, 200, 200), (xOffset, yOffset + 1 + heightsum, self.cwidth + 16, self.cheight + 6)) secondBlitHeight = heightsum heightsum += self.cheight + 8 for i in range(0, len(self.falseBlocks)): heightsum += self.falseBlocks[i].render(surface, xOffset + 8, yOffset + heightsum, selIndex - selCount, mode) if(mode == 0): selCount += self.falseBlocks[i].getArrowCount() else: selCount += self.falseBlocks[i].getBlockCount() if(mode == 0 and selIndex == selCount): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + heightsum + 1), (xOffset - 10, yOffset + 6 + heightsum), (xOffset - 10, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + heightsum), (xOffset + self.cwidth + 26, yOffset + 6 + heightsum), (xOffset + self.cwidth + 16, yOffset + heightsum + 1)]) pygame.draw.rect(surface, (255, 200, 200), (xOffset, yOffset + 1 + heightsum, self.cwidth + 16, self.cheight + 6)) pygame.draw.rect(surface, (255, 200, 200), (xOffset, yOffset + 1, 6, heightsum + self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) surface.blit(self.elseRender, (xOffset + 4, yOffset + secondBlitHeight + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, heightsum + self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, heightsum + self.cheight + 6), 2) return heightsum + self.cheight + 8 def getArrowCount(self): rtn = 3 for block in self.trueBlocks: rtn += block.getArrowCount() for block in self.falseBlocks: rtn += block.getArrowCount() return rtn def getBlockCount(self): rtn = 1 for block in self.trueBlocks: rtn += block.getBlockCount() for block in self.falseBlocks: rtn += block.getBlockCount() return rtn def getRenderHeight(self): heightsum = self.cheight + 8 for i in range(0, len(self.trueBlocks)): heightsum += self.trueBlocks[i].getRenderHeight() heightsum += self.cheight + 8 for i in range(0, len(self.falseBlocks)): heightsum += self.falseBlocks[i].getRenderHeight() return heightsum + self.cheight + 8 def execute(self, ownerBot, opponentBot, callback,dryRun = False): if ownerBot.health < self.hthresh: for t_block in self.trueBlocks: t_block.execute(ownerBot, opponentBot,callback) else: for f_block in self.falseBlocks: f_block.execute(ownerBot, opponentBot,callback) def insert(self, blockToInsert, arrowIndex): if(arrowIndex == 0): # Insert before current block return False # Should have been handled by calling function else: # Insert into middle of list currArrowIndex = arrowIndex - 1; for i in range(0, len(self.trueBlocks)): if(currArrowIndex == 0): self.trueBlocks.insert(i, blockToInsert) return True elif(self.trueBlocks[i].insert(blockToInsert, currArrowIndex)): return True else: currArrowIndex -= self.trueBlocks[i].getArrowCount() if(currArrowIndex == 0): # Insert at end of TrueBlocks self.trueBlocks.append(blockToInsert) return True currArrowIndex -= 1 for i in range(0, len(self.falseBlocks)): if(currArrowIndex == 0): self.falseBlocks.insert(i, blockToInsert) return True elif(self.falseBlocks[i].insert(blockToInsert, currArrowIndex)): return True else: currArrowIndex -= self.falseBlocks[i].getArrowCount() if(currArrowIndex == 0): # Insert at end of FalseBlocks self.falseBlocks.append(blockToInsert) return True return False def remove(self, index): if(index == 0): # Remove current block return False # Should have been handled by calling function else: currIndex = index - 1; for i in range(0, len(self.trueBlocks)): if(currIndex == 0): del self.trueBlocks[i] return True elif(self.trueBlocks[i].remove(currIndex)): return True else: currIndex -= self.trueBlocks[i].getBlockCount() for i in range(0, len(self.falseBlocks)): if(currIndex == 0): del self.falseBlocks[i] return True elif(self.falseBlocks[i].remove(currIndex)): return True else: currIndex -= self.falseBlocks[i].getBlockCount() return False def fetch(self, index): if(index == 0): return self else: currIndex = index - 1; for i in range(0, len(self.trueBlocks)): if(currIndex == 0): return self.falseBlocks[i] rtn = self.falseBlocks[i].fetch(currIndex) if(rtn != None): return rtn currIndex -= self.falseBlocks[i].getBlockCount() for i in range(0, len(self.falseBlocks)): if(currIndex == 0): return self.falseBlocks[i] rtn = self.falseBlocks[i].fetch(currIndex) if(rtn != None): return rtn currIndex -= self.falseBlocks[i].getBlockCount() return None def setThresh(self, newThresh): self.hthresh = newThresh self.fontRender = self.font.render("If I have less than " + str(self.hthresh) + " Health", 0, (0, 0, 0), (255, 200, 200)) # Heal Block. Causes the Golem to cast the Heal spell, restoring a certain amount of health not controlled by the program. class HealBlock(CodeBlock): def __init__(self, heal_amount, mana_cost): super(HealBlock, self).__init__() self.cwidth, self.cheight = self.font.size("Cast Heal on myself") self.mana_cost = mana_cost self.heal_amount = heal_amount self.fontRender = self.font.render("Cast Heal on myself", 0, (0, 0, 0), (255, 200, 200)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (255, 200, 200), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): if dryRun: return (ownerBot.mana - self.mana_cost, False) callback(ownerBot.name + " healed " + opponentBot.name + " Cost: " + str(self.mana_cost) + " Amount: " + str(self.heal_amount)) ownerBot.mana -= self.mana_cost ownerBot.health = (ownerBot.health + self.heal_amount) if ownerBot.health > ownerBot.maxHealth: ownerBot.health = ownerBot.maxHealth # Fireball Block. Causes the Golem to cast Fireball, dealing ignis damage on an opponent. class FireballBlock(CodeBlock): def __init__(self, damage_amount, mana_cost): super(FireballBlock, self).__init__() self.cwidth, self.cheight = self.font.size("Cast Fireball at the enemy") self.mana_cost = mana_cost self.damage_amount = damage_amount self.fontRender = self.font.render("Cast Fireball at the enemy", 0, (255, 255, 255), (128, 0, 0)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (128, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): if dryRun: return (ownerBot.mana - self.mana_cost, False) callback(ownerBot.name + " hit " + opponentBot.name + "w/ a Fireball!" + " Cost: " + str(self.mana_cost) + " Damage: " + str(self.damage_amount)) ownerBot.mana -= self.mana_cost opponentBot.health -= self.damage_amount # Moss Leech Block. Causes the Golem to cast Moss Leech, dealing natura damage on an opponent. class MossLeechBlock(CodeBlock): def __init__(self, damage_amount, mana_cost): super(MossLeechBlock, self).__init__() self.mana_cost = mana_cost self.damage_amount = damage_amount self.cwidth, self.cheight = self.font.size("Cast Moss Leech at the enemy") self.fontRender = self.font.render("Cast Moss Leech at the enemy", 0, (255, 255, 255), (0, 128, 0)) def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (0, 128, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): if dryRun: return (ownerBot.mana - self.mana_cost, False) callback(ownerBot.name + " moss leeched " + opponentBot.name + "!" + " Cost: " + str(self.mana_cost) + " Damage: " + str(self.damage_amount)) ownerBot.mana -= self.mana_cost opponentBot.health -= self.damage_amount # Douse Block. Causes the Golem to cast Douse, dealing aqua damage on an opponent. class DouseBlock(CodeBlock): def __init__(self, damage_amount, mana_cost): super(DouseBlock, self).__init__() self.cwidth, self.cheight = self.font.size("Cast Douse at the enemy") self.fontRender = self.font.render("Cast Douse at the enemy", 0, (255, 255, 255), (0, 0, 255)) self.damage_amount = damage_amount self.mana_cost = mana_cost def render(self, surface, xOffset = 0, yOffset = 0, selIndex = -1, mode = -1): if(mode == 0 and selIndex == 0): pygame.draw.polygon(surface, (255, 255, 255), [(xOffset, yOffset + 1), (xOffset - 10, yOffset + 6), (xOffset - 10, yOffset), (xOffset + self.cwidth + 26, yOffset), (xOffset + self.cwidth + 26, yOffset + 6), (xOffset + self.cwidth + 16, yOffset + 1)]) pygame.draw.rect(surface, (0, 0, 255), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6)) surface.blit(self.fontRender, (xOffset + 4, yOffset + 4)) if(mode == 1 and selIndex == 0): pygame.draw.rect(surface, (128, 110, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) if(mode == 2 and selIndex == 0): pygame.draw.rect(surface, (255, 0, 0), (xOffset, yOffset + 1, self.cwidth + 16, self.cheight + 6), 2) return self.cheight + 8 def getRenderHeight(self): return self.cheight + 8 def execute(self, ownerBot, opponentBot, callback, dryRun = False): if dryRun: return (ownerBot.mana - self.mana_cost, False) callback(ownerBot.name + " doused " + opponentBot.name + "!" + " Cost: " + str(self.mana_cost) + " Damage: " + str(self.damage_amount)) ownerBot.mana -= self.mana_cost opponentBot.health -= self.damage_amount
slicing pain from their pale limbs. soothe desert dry lips with honey. to the beauty of my garden. by the busyness of survival? to rest when the sun disappears. Mrs.S – both poem and painting are wonderful. I am so glad her story has finally been written and painted!
# coding=utf-8 # 这是为Google和中文维基(无缝整合)镜像配置的示例配置文件 # # 使用方法: # 1. 复制本文件到 zmirror 根目录(wsgi.py所在目录), 并重命名为 config.py # 2. 修改 my_host_name 为你自己的域名 # # 各项设置选项的详细介绍请看 config_default.py 中对应的部分 # 本配置文件假定你的服务器本身在墙外 # 如果服务器本身在墙内(或者在本地环境下测试, 请修改`Proxy Settings`中的设置 # # 由于google搜索结果经常会出现中文维基, 所以顺便把它也加入了. # google跟中文维基之间使用了本程序的镜像隔离功能, 可以保证中文维基站的正常使用 # # 本配置文件试图还原出一个功能完整的google. # 但是由于程序本身所限, 还是不能[完整]镜像过来整个[google站群] # 在后续版本会不断增加可用的网站 # # 以下google服务完全可用: # google网页搜索/学术/图片/新闻/图书/视频(搜索)/财经/APP搜索/翻译/网页快照/... # google搜索与中文维基百科无缝结合 # 以下服务部分可用: # gg地图(地图可看, 左边栏显示不正常)/G+(不能登录) # 以下服务暂不可用(因为目前无法解决登录的问题): # 所有需要登录的东西, docs之类的 # # Github: https://github.com/aploium/zmirror # ############## Local Domain Settings ############## my_host_name = '127.0.0.1' my_host_scheme = 'http://' my_host_port = None # None表示使用默认端口, 可以设置成非标准端口, 比如 81 # ############## Target Domain Settings ############## target_domain = 'www.google.com.hk' target_scheme = 'https://' # 这里面大部分域名都是通过 `enable_automatic_domains_whitelist` 自动采集的, 我只是把它们复制黏贴到了这里 # 实际镜像一个新的站时, 手动只需要添加很少的几个域名就可以了. # 自动采集(如果开启的话)会不断告诉你新域名 external_domains = ( 'www.google.com', 'webcache.googleusercontent.com', # Google网页快照 'images.google.com.hk', 'images.google.com', 'apis.google.com', # Google学术 'scholar.google.com.hk', 'scholar.google.com', # 中文维基百科 'zh.wikipedia.org', 'zh.m.wikipedia.org', 'upload.wikipedia.org', 'meta.wikimedia.org', 'login.wikimedia.org', # Google静态资源域名 'ssl.gstatic.com', 'www.gstatic.com', 'encrypted-tbn0.gstatic.com', 'encrypted-tbn1.gstatic.com', 'encrypted-tbn2.gstatic.com', 'encrypted-tbn3.gstatic.com', 'csi.gstatic.com', 'fonts.googleapis.com', # Google登陆支持 'accounts.google.com', 'accounts.youtube.com', 'accounts.google.com.hk', 'myaccount.google.com', 'myaccount.google.com.hk', 'ajax.googleapis.com', 'translate.google.com', 'translate.google.com.hk', 'video.google.com.hk', 'books.google.com', 'cloud.google.com', 'analytics.google.com', 'security.google.com', 'investor.google.com', 'families.google.com', 'clients1.google.com', 'clients2.google.com', 'clients3.google.com', 'clients4.google.com', 'clients5.google.com', 'talkgadget.google.com', 'news.google.com.hk', 'news.google.com', 'support.google.com', 'docs.google.com', 'books.google.com.hk', 'chrome.google.com', 'profiles.google.com', 'feedburner.google.com', 'cse.google.com', 'sites.google.com', 'productforums.google.com', 'encrypted.google.com', 'm.google.com', 'research.google.com', 'maps.google.com.hk', 'hangouts.google.com', 'developers.google.com', 'get.google.com', 'afp.google.com', 'groups.google.com', 'payments.google.com', 'photos.google.com', 'play.google.com', 'mail.google.com', 'code.google.com', 'tools.google.com', 'drive.google.com', 'script.google.com', 'goto.google.com', 'calendar.google.com', 'wallet.google.com', 'privacy.google.com', 'ipv4.google.com', 'video.google.com', 'store.google.com', 'fi.google.com', 'apps.google.com', 'events.google.com', 'notifications.google.com', 'plus.google.com', 'dl.google.com', 'manifest.googlevideo.com', 'storage.googleapis.com', 'gg.google.com', 'scholar.googleusercontent.com', 'translate.googleusercontent.com', 't0.gstatic.com', 't1.gstatic.com', 't2.gstatic.com', 't3.gstatic.com', 's-v6exp1-ds.metric.gstatic.com', 'ci4.googleusercontent.com', 'gp3.googleusercontent.com', 'accounts.gstatic.com', # For Google Map (optional) 'maps-api-ssl.google.com', 'maps.gstatic.com', 'maps.google.com', 'fonts.gstatic.com', 'lh1.googleusercontent.com', 'lh2.googleusercontent.com', 'lh3.googleusercontent.com', 'lh4.googleusercontent.com', 'lh5.googleusercontent.com', 'lh6.googleusercontent.com', # 'upload.wikimedia.org', 'id.google.com.hk', 'id.google.com', # misc 'inputtools.google.com', 'inbox.google.com', '-v6exp3-v4.metric.gstatic.com', '-v6exp3-ds.metric.gstatic.com', 'if-v6exp3-v4.metric.gstatic.com', 'public.talk.google.com', 'ie.talkgadget.google.com', 'client-channel.google.com', 'maps.googleapis.com', 'people-pa.clients6.google.com', 'myphonenumbers-pa.googleapis.com', 'clients6.google.com', 'staging.talkgadget.google.com', 'preprod.hangouts.sandbox.google.com', 'dev-hangoutssearch-pa-googleapis.sandbox.google.com', 'picasaweb.google.com', 'schemas.google.com', 'contact.talk.google.com', 'groupchat.google.com', 'friendconnectchat.google.com', 'muvc.google.com', 'bot.talk.google.com', 'prom.corp.google.com', 'stun.l.google.com', 'stun1.l.google.com', 'stun2.l.google.com', 'stun3.l.google.com', 'stun4.l.google.com', 'onetoday.google.com', 'plus.googleapis.com', 'youtube.googleapis.com', 'picasa.google.com', "www-onepick-opensocial.googleusercontent.com", 'plus.sandbox.google.com', # gmail misc 'gmail.com', 'www.gmail.com', 'chatenabled.mail.google.com', 'filetransferenabled.mail.google.com', 'gmail.google.com', 'googlemail.l.google.com', 'isolated.mail.google.com', 'm.gmail.com', 'm.googlemail.com', 'mail-settings.google.com', 'm.android.com', ) # 强制所有Google站点使用HTTPS force_https_domains = 'ALL' # 自动动态添加域名 enable_automatic_domains_whitelist = True domains_whitelist_auto_add_glob_list = ( '*.google.com', '*.gstatic.com', '*.google.com.hk', '*.googleapis.com', "*.googleusercontent.com",) # ############## Proxy Settings ############## # 如果你在墙内使用本配置文件, 请指定一个墙外的http代理 is_use_proxy = False # 代理的格式及SOCKS代理, 请看 http://docs.python-requests.org/en/latest/user/advanced/#proxies requests_proxies = dict( http='http://127.0.0.1:8123', https='https://127.0.0.1:8123', ) # ############## Sites Isolation ############## enable_individual_sites_isolation = True # 镜像隔离, 用于支持Google和维基共存 isolated_domains = {'zh.wikipedia.org', 'zh.m.wikipedia.org'} # ############## URL Custom Redirect ############## url_custom_redirect_enable = True url_custom_redirect_list = { # 这是一个方便的设置, 如果你访问 /wiki ,程序会自动重定向到后面这个长长的wiki首页 '/wiki': '/extdomains/https-zh.wikipedia.org/', # 这是gmail '/gmail': '/extdomains/mail.google.com/mail/u/0/h/girbaeneuj90/', } # ############# Additional Functions ############# # 移除google搜索结果页面的url跳转 # 原理是往页面中插入一下面这段js # js来自: http://userscripts-mirror.org/scripts/review/117942 custom_inject_content = { "head_first": [ { "content": r"""<script> function checksearch(){ var list = document.getElementById('ires'); if(list){ document.removeEventListener('DOMNodeInserted',checksearch,false); document.addEventListener('DOMNodeInserted',clear,false) } }; function clear(){ var i; var items = document.querySelectorAll('a[onmousedown]'); for(i =0;i<items.length;i++){ items[i].removeAttribute('onmousedown'); } }; document.addEventListener('DOMNodeInserted',checksearch,false) </script>""", "url_regex": r"^www\.google(?:\.[a-z]{2,3}){1,2}", }, ] }
Food will be catered by “THIS IS IT!” BBQ. A cash bar will be there for all of your adult beverage needs. DJ Dre will be on the turntables playing your favorite tunes….and taking us straight to the West Coast!! Hazmat Boyz told me to ensure I have 2 mics….So they just may get up on stage for you!! The menu will include Rib Tips, BBQ Chicken, Mac & Cheese, Baked Beans & Potato Salad. We will also provide sweet tea (you can’t come to the south and not have some sweeeet tea) lemonade and several southern desserts to choose from. Ticket price is $25 per person in advance (non-refundable), and $30 at the door. Please print your ticket and bring your picture ID with you to the event. ID must match the name of the person purchasing tickets. TICKETS MUST BE PURCHASED ONLINE BY OCT 1ST!
import argparse import sys import os from osgeo import ogr from osgeo import osr import anyjson import shapely.geometry import shapely.ops import codecs import time format = '%.8f %.8f' tolerance = 0.01 infile = '/Users/kirilllebedev/Maps/50m-admin-0-countries/ne_50m_admin_0_countries.shp' outfile = 'map.shp' # Open the datasource to operate on. in_ds = ogr.Open( infile, update = 0 ) in_layer = in_ds.GetLayer( 0 ) in_defn = in_layer.GetLayerDefn() # Create output file with similar information. shp_driver = ogr.GetDriverByName( 'ESRI Shapefile' ) if os.path.exists('map.shp'): shp_driver.DeleteDataSource( outfile ) shp_ds = shp_driver.CreateDataSource( outfile ) shp_layer = shp_ds.CreateLayer( in_defn.GetName(), geom_type = in_defn.GetGeomType(), srs = in_layer.GetSpatialRef() ) in_field_count = in_defn.GetFieldCount() for fld_index in range(in_field_count): src_fd = in_defn.GetFieldDefn( fld_index ) fd = ogr.FieldDefn( src_fd.GetName(), src_fd.GetType() ) fd.SetWidth( src_fd.GetWidth() ) fd.SetPrecision( src_fd.GetPrecision() ) shp_layer.CreateField( fd ) # Load geometries geometries = [] for feature in in_layer: geometry = feature.GetGeometryRef() geometryType = geometry.GetGeometryType() if geometryType == ogr.wkbPolygon or geometryType == ogr.wkbMultiPolygon: shapelyGeometry = shapely.wkb.loads( geometry.ExportToWkb() ) #if not shapelyGeometry.is_valid: #buffer to fix selfcrosses #shapelyGeometry = shapelyGeometry.buffer(0) if shapelyGeometry: geometries.append(shapelyGeometry) in_layer.ResetReading() start = int(round(time.time() * 1000)) # Simplification points = [] connections = {} counter = 0 for geom in geometries: counter += 1 polygons = [] if isinstance(geom, shapely.geometry.Polygon): polygons.append(geom) else: for polygon in geom: polygons.append(polygon) for polygon in polygons: if polygon.area > 0: lines = [] lines.append(polygon.exterior) for line in polygon.interiors: lines.append(line) for line in lines: for i in range(len(line.coords)-1): indexFrom = i indexTo = i+1 pointFrom = format % line.coords[indexFrom] pointTo = format % line.coords[indexTo] if pointFrom == pointTo: continue if not (pointFrom in connections): connections[pointFrom] = {} connections[pointFrom][pointTo] = 1 if not (pointTo in connections): connections[pointTo] = {} connections[pointTo][pointFrom] = 1 print int(round(time.time() * 1000)) - start simplifiedLines = {} pivotPoints = {} def simplifyRing(ring): coords = list(ring.coords)[0:-1] simpleCoords = [] isPivot = False pointIndex = 0 while not isPivot and pointIndex < len(coords): pointStr = format % coords[pointIndex] pointIndex += 1 isPivot = ((len(connections[pointStr]) > 2) or (pointStr in pivotPoints)) pointIndex = pointIndex - 1 if not isPivot: simpleRing = shapely.geometry.LineString(coords).simplify(tolerance) if len(simpleRing.coords) <= 2: return None else: pivotPoints[format % coords[0]] = True pivotPoints[format % coords[-1]] = True simpleLineKey = format % coords[0]+':'+format % coords[1]+':'+format % coords[-1] simplifiedLines[simpleLineKey] = simpleRing.coords return simpleRing else: points = coords[pointIndex:len(coords)] points.extend(coords[0:pointIndex+1]) iFrom = 0 for i in range(1, len(points)): pointStr = format % points[i] if ((len(connections[pointStr]) > 2) or (pointStr in pivotPoints)): line = points[iFrom:i+1] lineKey = format % line[-1]+':'+format % line[-2]+':'+format % line[0] if lineKey in simplifiedLines: simpleLine = simplifiedLines[lineKey] simpleLine = list(reversed(simpleLine)) else: simpleLine = shapely.geometry.LineString(line).simplify(tolerance).coords lineKey = format % line[0]+':'+format % line[1]+':'+format % line[-1] simplifiedLines[lineKey] = simpleLine simpleCoords.extend( simpleLine[0:-1] ) iFrom = i if len(simpleCoords) <= 2: return None else: return shapely.geometry.LineString(simpleCoords) def simplifyPolygon(polygon): simpleExtRing = simplifyRing(polygon.exterior) if simpleExtRing is None: return None simpleIntRings = [] for ring in polygon.interiors: simpleIntRing = simplifyRing(ring) if simpleIntRing is not None: simpleIntRings.append(simpleIntRing) return shapely.geometry.Polygon(simpleExtRing, simpleIntRings) results = [] for geom in geometries: polygons = [] simplePolygons = [] if isinstance(geom, shapely.geometry.Polygon): polygons.append(geom) else: for polygon in geom: polygons.append(polygon) for polygon in polygons: simplePolygon = simplifyPolygon(polygon) if not (simplePolygon is None or simplePolygon._geom is None): simplePolygons.append(simplePolygon) if len(simplePolygons) > 0: results.append(shapely.geometry.MultiPolygon(simplePolygons)) else: results.append(None) # Process all features in input layer. in_feat = in_layer.GetNextFeature() counter = 0 while in_feat is not None: if results[counter] is not None: out_feat = ogr.Feature( feature_def = shp_layer.GetLayerDefn() ) out_feat.SetFrom( in_feat ) out_feat.SetGeometryDirectly( ogr.CreateGeometryFromWkb( shapely.wkb.dumps( results[counter] ) ) ) shp_layer.CreateFeature( out_feat ) out_feat.Destroy() else: print 'geometry is too small: '+in_feat.GetField(16) in_feat.Destroy() in_feat = in_layer.GetNextFeature() counter += 1 # Cleanup shp_ds.Destroy() in_ds.Destroy() print int(round(time.time() * 1000)) - start
The solution focuses on utilizing a view in order to simplify the execution plan produced for a batched delete operation. This is achieved by referencing the given table once, rather than twice which in turn reduces the amount of I/O required. The posts that provided this information referenced a link (http://blogs.msdn.com/sqlcat/archive/2009/05/21/fa...) provided by Kevin Stephenson of MySpace and Lubor Kollar, a member of the SQL Server Customer Advisory Team. This link is now unavailable but the Internet Archive has a copy of this page at http://web.archive.org/web/20100212155407/http://blogs.msdn.com/sqlcat/archive/2009/05/21/fast-ordered-delete.aspx. When dealing with deleting data from tables which have foreign key relationships - which is basically the case with any properly designed database - we can disable all the constraints, delete all the data and then re-enable constraints. More on disabling constraints and triggers here. if some of the tables have identity columns we may want to reseed them. EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)" The current identity value is set to the newReseedValue. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use newReseedValue as the identity. Otherwise, the next row inserted will use newReseedValue + 1. If the value of newReseedValue is less than the maximum value in the identity column, error message 2627 will be generated on subsequent references to the table.
#!/usr/bin/python import nltk from nltk.corpus import wordnet """ Similarity between two words Threshold decided manually, can be tweaked after discussion """ """" Sample Output: similarity( sparrow, parrot ) = 0.869565217391 ==> Very similar similarity( ship, boat ) = 0.909090909091 ==> Very similar similarity( cat, elephant ) = 0.814814814815 ==> Little similar similarity( dolphin, ship ) = 0.296296296296 ==> Not similar similarity( giraffe, tiger ) = 0.521739130435 ==> Not similar similarity( sheep, ship ) = 0.296296296296 ==> Not similar similarity( ship, cat ) = 0.32 ==> Not similar """ def similarity(a, b): suf=".n.01" a, b = a+suf, b+suf w1 = wordnet.synset(a) w2 = wordnet.synset(b) sim = w1.wup_similarity(w2) #print sim, output="" if sim >= 0.85: output="Very similar" elif sim >= 0.65: output="Little similar" else: output="Not similar" print 'similarity({:>15}, {:15}) = {:<15} ==> {} '.format(a[:a.find('.')],b[:b.find('.')], sim, output) sim = similarity # very similar print sim("sparrow", "parrot") sim("ship", "boat") # little similar print sim("cat", "elephant") # not similar print sim("dolphin", "ship") sim("giraffe", "tiger") sim("sheep", "ship") sim("ship", "cat")
Men\’s Popular Hairstyles. This awesome picture collections about Men\’s Popular Hairstyles is accessible to download. We collect this amazing photo from internet and select one of the best for you. Men\’s Popular Hairstyles photos and pictures selection that published here was properly chosen and published by sellgreat after selecting the ones which are best among the others. So, finally we make it and here these list ofamazing picture for your inspiration and informational purpose regarding the Men\’s Popular Hairstyles as part of sellgreat.info exclusive updates collection. So, take your time and find out the best Men\’s Popular Hairstyles photos and pictures posted here that suitable with your needs and use it for your own collection and personal use. About Pic information: Graphic has been added by sellgreat and has been tagged by girl hairstyle hairstyle boy hairstyle girls hairstyle ladies hairstyle men hairstyle simple hairstyles for medium hair Men’s Popular Hairstyles in Best Hairstyle field. You can easily leave your review as evaluations to our page value. They are ready for save, if you love and want to own it, simply click save symbol in the article, and it’ll be instantly downloaded in your laptop. For most up-dates and latest news about Men\’s Popular Hairstyles pictures, please kindly follow us on tweets, path, Instagram and google plus, or you mark this page on bookmark area, We try to offer you up-date periodically with all new and fresh images, enjoy your surfing, and find the ideal for you.
# -*- coding: utf-8 -*- from pathfinding.core.diagonal_movement import DiagonalMovement from pathfinding.core.grid import Grid from pathfinding.finder.a_star import AStarFinder import numpy as np BORDERLESS_GRID = """ xxx xxx """ BORDER_GRID = """ +---+ | | | | +---+ """ WALKED_GRID = """ +---+ |s# | |xe | +---+ """ SIMPLE_MATRIX = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] SIMPLE_WALKED = """ +---+ |sx | | #x| | e| +---+ """ def test_str(): """ test printing the grid """ grid = Grid(height=2, width=3) assert grid.grid_str(border=False, empty_chr='x') == BORDERLESS_GRID[1:-1] assert grid.grid_str(border=True) == BORDER_GRID[1:-1] grid.nodes[0][1].walkable = False start = grid.nodes[0][0] end = grid.nodes[1][1] path = [(0, 1)] assert grid.grid_str(path, start, end) == WALKED_GRID[1:-1] def test_empty(): """ special test for empty values """ matrix = () grid = Grid(matrix=matrix) assert grid.grid_str() == '++\n||\n++' matrix = np.array(matrix) grid = Grid(matrix=matrix) assert grid.grid_str() == '++\n||\n++' def test_numpy(): """ test grid from numpy array """ matrix = np.array(SIMPLE_MATRIX) grid = Grid(matrix=matrix) start = grid.node(0, 0) end = grid.node(2, 2) finder = AStarFinder(diagonal_movement=DiagonalMovement.always) path, runs = finder.find_path(start, end, grid) assert grid.grid_str(path, start, end) == SIMPLE_WALKED[1:-1] if __name__ == '__main__': test_str()
A company specialized in telecoms, IT and media, headquartered in London, UK. A communication company in the United Kingdom. Offers broadband, dial-up internet access products, advanced research & technology products & services for home and business. A provider of communications solutions to businesses and public sector organisations. Telecom consultants providing advice on all aspects of telecommunications to businesses in the UK. A distributor of headsets, handsets, audio conferencing, call recording and voice and data installation equipment. A voice and data solution provider serving the UK business community. Specializes in the integration and enhancement of OSS and BSS systems, old and new. Provides television, radio, telecommunications and wireless communications services. Manufacturers of business telephone systems in Europe. Provides up-to-date and archived information on the contact centre industry. Produces large scale international congresses, exhibitions, topical conferences, & professional skills training. Specialists installing and maintaining telephone systems, voicemail, access control, public address & premises cabling networks. Specialized in voice & data routing, business broadband & bespoke network design. A telecommunications company specialising in long distance phone calls and products. Offers communications services including systems, fixed and mobile voice as well as data and cabling services. Provides telecom products and services to UK businesses. Specialists in telephones and business telephone equipment. A manufacturer of masts and towers for the telecommunications industry and supporting steelwork and accessories. Integrated communications specialists in the UK. A company offering communications services for voice, data and IP. Supplies, installs and maintains business telephone and telecommunications systems. Suppliers and installers of new and used business telephone systems and equipment, plus data cabling and networking services. Offers auditing and performance measurement for telecommunications companies. Specialized in the provision of computer telephony integration, video conferencing, voice over IP and least cost routing. Provides solutions to record, analyze and evaluate communications. Provides telecoms and broadband internet hardware installation services. Midland Communications specializes in the field of business communications. Specialised in providing services within the telecommunication industry. A provider of mobile phones and broadband, offering the best tariffs, mobile phones and broadband deals. Specialized in communication systems, applications, and services. Provides a cabling and network solutions service. Supplies broadband, internet access, telephone services, data networking and other ICT applications and services. Provides online vehicle tracking systems using satellite telematics with real time GPS tracking. Provides telephone systems & IT solutions for business in London, UK. Technology which reduces the harmful side effects of radiation from phones and computers. UK`s leading conference call service provider offering teleconferencing, video calling and more.
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import euclidean from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import KDTree from sklearn.model_selection import LeaveOneOut import sys import abc import math import time import os.path import random from multiprocessing import Pool RESULT_DIR = './exp_result' class KNN(metaclass=abc.ABCMeta): @abc.abstractmethod def classify(self, obj, throw_closest=False): pass class KNN_Euclidean(KNN): def __init__(self, objects, labels, k): self.objects = objects self.labels = labels self.n = objects.shape[0] self.k = k def classify(self, obj, throw_closest=False): obj_repeated = np.array([obj,] * self.n) obj_repeated = np.repeat(obj, self.n).values.reshape((len(obj), self.n)).T obj_repeated -= self.objects norms = np.linalg.norm(obj_repeated, axis=1) indices = np.argpartition(norms, self.k + throw_closest) norms_indices = [(norms[i], i) for i in indices[:self.k + throw_closest]] norms_indices.sort() match_indices = [p[1] for p in norms_indices[int(throw_closest):]] votes_for_first_class = sum(self.labels[match_indices]) # The majority class is `0`. I guess that this is `no-spam` class. if votes_for_first_class * 2 > self.k: return 1 return 0 class KNN_Euclidean_KD(KNN): def __init__(self, objects, labels, k): self.objects_tree = KDTree(objects) self.labels = labels self.k = k def classify(self, obj, throw_closest=False): neighbours_idx = self.objects_tree.query([obj], self.k + int(throw_closest), sort_results=True, return_distance=False)[0][int(throw_closest):] votes = self.labels[neighbours_idx] votes_for_first_class = sum(votes) if votes_for_first_class * 2 > self.k: return 1 return 0 class KNN_Radius(KNN): def __init__(self, objects, labels, radius): self.objects = objects self.labels = labels self.n = objects.shape[0] self.radius = radius def classify(self, obj, throw_closest=False): obj_repeated = np.array([obj,] * self.n) obj_repeated = np.repeat(obj, self.n).values.reshape((len(obj), self.n)).T obj_repeated -= self.objects norms = np.linalg.norm(obj_repeated, axis=1) mask = norms <= self.radius if throw_closest: mask &= norms > 0 votes = self.labels[mask] votes_for_first_class = sum(votes) if votes_for_first_class * 2 > len(votes): return 1 return 0 def classify_one_obj(idx, row, classifier, right_label): guess = classifier.classify(row, True) return guess == right_label def leave_one_out_unparallel(classifier_cls, objects, labels, **kwargs): classifier = classifier_cls(objects, labels, **kwargs) num_objects = objects.shape[0] args = [(i, objects.iloc[i], classifier, labels.iloc[i]) for i in range(num_objects)] right_guesses = 0 for i in range(num_objects): obj = objects.iloc[i] ground_truth = labels.iloc[i] predicted = classifier.classify(obj, True) if i % 100 == 0: print('iteration i=',i) sys.stdout.flush() right_guesses += predicted == ground_truth return right_guesses / float(num_objects) def experiment_loo_unparallel(): classifier_cls = KNN_Euclidean print('Non-normalized data:') objects, labels = read_data() for k in [1, 3]: print('k=', k) loo_val = leave_one_out_unparallel(classifier_cls, objects, labels, k=k) print(loo_val) print('Normalized data') objects, labels = read_normalized_data() for k in [1, 3]: print('k=', k) loo_val = leave_one_out_unparallel(classifier_cls, objects, labels, k=k) print(loo_val) def leave_one_out(classifier_cls, objects, labels, **kwargs): classifier = classifier_cls(objects, labels, **kwargs) num_objects = objects.shape[0] args = [(i, objects.iloc[i], classifier, labels.iloc[i]) for i in range(num_objects)] right_guesses = 0 with Pool() as p: right_guesses = sum(p.starmap(classify_one_obj, args)) return right_guesses / float(num_objects) def read_data(): data = pd.read_csv('spambase.csv') objects, labels = data.iloc[:, :-1], data.iloc[:, -1] return objects, labels def read_normalized_data(): objects, labels = read_data() cols = objects.shape[1] rows = objects.shape[0] max_by_col = [0.001 for i in range(cols)] for i in range(rows): row = objects.iloc[i] for j in range(cols): val = row.iloc[j] max_by_col[j] = max(max_by_col[j], abs(val)) objects /= np.array(max_by_col) return objects, labels def simple_test(objects, labels): NUM = 330 row = objects.iloc[NUM] classifier = KNN_Euclidean(objects, labels, 10) print(classifier.classify(row, True)) print(labels.iloc[NUM]) def generic_euclidean_loo(classifier_cls, objects, labels, filename): k_values = list(range(1, 10 + 1)) loo_values = [] times = [] for k in k_values: print('Loo: k = ', k) time_before = time.time() loo_val = leave_one_out(classifier_cls, objects, labels, k=k) print('loo value: ', loo_val) time_after = time.time() time_delta = time_after - time_before times.append(time_delta) loo_values.append(loo_val) dct = {'K': k_values, 'LOO': loo_values, 'Time': times} frame = pd.DataFrame(dct) frame.to_csv(os.path.join(RESULT_DIR, filename)) def generic_radius_loo(classifier_cls, objects, labels, filename, maximal_radius): number_of_computations = 0 radiuses = [] loo_vals = [] times = [] def f(radius, saved=dict()): nonlocal number_of_computations # Cache already computed results. key = radius * 10 ** 100 if key not in saved: time_before = time.time() saved[key] = leave_one_out(classifier_cls, objects, labels, radius=radius) time_after = time.time() times.append(time_after - time_before) radiuses.append(radius) loo_vals.append(saved[key]) number_of_computations += 1 return saved[key] le = 0 rg = maximal_radius # Assume that LOO has unique maximum. # Use golden ratio search http://www.essie.ufl.edu/~kgurl/Classes/Lect3421/NM6_optim_s02.pdf # for lesser number of LOO calculations (which are *painfully* slow). golden_ratio = (1 + math.sqrt(5)) / 2 NUM_ITER = 10 for it in range(NUM_ITER): print('Iteration {}/{}:'.format(it + 1, NUM_ITER), 'left', le, 'right', rg) len_seg = (rg - le) len_left = len_seg / (1 + golden_ratio) len_right = len_left * golden_ratio mid1 = le + len_left mid2 = le + len_right loo_mid1 = f(mid1) loo_mid2 = f(mid2) print('LOO values:', loo_mid1, loo_mid2) if loo_mid1 < loo_mid2: le = mid1 else: rg = mid2 # Total number of computations is 27 vs 40 in regular ternary search (if we always choose rg = mid2). print('Total number of LOO computations:', number_of_computations) dct = {'Radius': radiuses, 'LOO': loo_vals, 'Time': times} frame = pd.DataFrame(dct) frame.to_csv(os.path.join(RESULT_DIR, filename)) def experiment_loo_euclidean(): objects, labels = read_data() generic_euclidean_loo(KNN_Euclidean, objects, labels, 'loo_euclidean.csv') def experiment_loo_radius(): objects, labels = read_data() generic_radius_loo(KNN_Radius, objects, labels, 'loo_radius.csv', 100.0) def experiment_loo_euclidean_normalized(): objects, labels = read_normalized_data() generic_euclidean_loo(KNN_Euclidean, objects, labels, 'loo_euclidean_normalized.csv') def experiment_loo_radius_normalized(): objects, labels = read_normalized_data() generic_radius_loo(KNN_Radius, objects, labels, 'loo_radius_normalized.csv', 1.0) def classify_one_obj_sklearn (k, objects, labels, train_index, test_index): x_train, x_test = objects[train_index], objects[test_index] y_train, y_test = labels[train_index], labels[test_index] classifier = KNeighborsClassifier(k) classifier.fit(x_train, y_train) return classifier.predict(x_test)[0] == y_test[0] def generic_test_sklearn(objects, labels, filename): # http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.LeaveOneOut.html loo = LeaveOneOut() objects = np.array(objects) labels = np.array(labels) k_values = list(range(1, 10 + 1)) loo_values = [] times = [] for k in k_values: print('Loo: k = ', k) classifier = KNeighborsClassifier(k, n_jobs=-1) right_guesses = 0 time_before = time.time() args = [] for train_index, test_index in loo.split(objects): args.append((k, objects, labels, train_index, test_index)) print('Computed args') right_guesses = 0 with Pool() as p: right_guesses = sum(p.starmap(classify_one_obj_sklearn, args)) loo_val = right_guesses / float(labels.shape[0]) print('Loo value: ', loo_val) time_after = time.time() times.append(time_after - time_before) loo_values.append(loo_val) dct = {'K': k_values, 'LOO': loo_values, 'Time': times} frame = pd.DataFrame(dct) frame.to_csv(os.path.join(RESULT_DIR, filename)) def experiment_loo_sklearn(): objects, labels = read_data() generic_test_sklearn(objects, labels, 'loo_euclidean_sklearn.csv') objects, labels = read_normalized_data() generic_test_sklearn(objects, labels, 'loo_euclidean_sklearn_normalized.csv') def experiment_time_kdtree(): objects, labels = read_data() generic_euclidean_loo(KNN_Euclidean_KD, objects, labels, 'loo_euclidean_kdtree.csv') objects, labels = read_normalized_data() generic_euclidean_loo(KNN_Euclidean_KD, objects, labels, 'loo_euclidean_kdtree_normalized.csv') def write_result_euclidean(): fname_prefixes = ['loo_euclidean', 'loo_euclidean_kdtree', 'loo_euclidean_sklearn'] for suffix in ['.csv', '_normalized.csv']: fnames = [os.path.join(RESULT_DIR, fname_prefix + suffix) for fname_prefix in fname_prefixes] csv_files = [pd.read_csv(fname) for fname in fnames] loos = [csv['LOO'] for csv in csv_files] loos = np.matrix(loos).T df = pd.DataFrame(loos, index=csv_files[0]['K'], columns=['my_knn', 'kdtree_knn', 'sklearn_knn']) df.plot() plt.title('KNN on {} data'.format('non-normalized' if suffix == '.csv' else 'normalized')) plt.xlabel('K') plt.ylabel('LOO') #plt.ylim([0.5, 1.0]) plt.savefig(os.path.join(RESULT_DIR, 'knn_euclidean{}.png'.format('' if suffix == '.csv' else '_normalized'))) for suffix in ['.csv']: fnames = [os.path.join(RESULT_DIR, fname_prefix + suffix) for fname_prefix in fname_prefixes] csv_files = [pd.read_csv(fname) for fname in fnames] loos = [csv['Time'][:-1] for csv in csv_files] loos = np.matrix(loos).T df = pd.DataFrame(loos, index=csv_files[0]['K'][:-1], columns=['my_knn', 'kdtree_knn', 'sklearn_knn']) df.plot() plt.title('Time of one LOO iteration') plt.xlabel('K') plt.ylabel('Time (seconds)') plt.savefig(os.path.join(RESULT_DIR, 'knn_time.png')) def write_result_radius(): fname_prefixes = ['loo_radius'] for suffix in ['.csv', '_normalized.csv']: fnames = [os.path.join(RESULT_DIR, fname_prefix + suffix) for fname_prefix in fname_prefixes] csv_files = [pd.read_csv(fname) for fname in fnames] frame = csv_files[0] frame.sort_values('Radius', inplace=True) loos = [frame['LOO']] loos = np.matrix(loos).T df = pd.DataFrame(loos, index=frame['Radius'], columns=['my_knn']) df.plot() plt.title('KNN on {} data'.format('non-normalized' if suffix == '.csv' else 'normalized')) plt.xlabel('Radius') plt.ylabel('LOO') plt.savefig(os.path.join(RESULT_DIR, 'knn_radius{}.png'.format('' if suffix == '.csv' else '_normalized'))) def compute_graphic_results(): write_result_euclidean() write_result_radius() def main(): #experiment_loo_unparallel() #experiment_loo_euclidean() #experiment_loo_radius() #experiment_loo_euclidean_normalized() #experiment_loo_radius_normalized() #experiment_loo_sklearn() #experiment_time_kdtree() compute_graphic_results() if __name__ == '__main__': main()
Reviews for C&S Electric Ltd. Have you hired C&S Electric Ltd.? Write a review and earn our First to Review badge. C&S Electric Ltd. has not added any photos.
""" Copyright 2014-2015 Rackspace 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. """ from functionaltests.api.v1.models.base_models import BaseModel class OrderModel(BaseModel): def __init__(self, type=None, name=None, status=None, secret_ref=None, expiration=None, updated=None, created=None, meta=None, payload_content_type=None, order_ref=None, container_ref=None, error_status_code=None, error_reason=None, sub_status=None, sub_status_message=None, creator_id=None): super(OrderModel, self).__init__() self.type = type self.name = name self.status = status self.sub_status = sub_status self.sub_status_message = sub_status_message self.secret_ref = secret_ref self.expiration = expiration self.updated = updated self.created = created self.meta = meta self.payload_content_type = payload_content_type self.order_ref = order_ref self.container_ref = container_ref self.error_status_code = error_status_code self.error_reason = error_reason self.creator_id = creator_id
During my exchange studies at Tama Art University in Tokyo, Japan, I did a research project on children's cultural experiences in Japan, focusing on costumes and clothing design. As a result, I designed a bag inspired by the Japanese symbolism, form and mindset. 渋 い (shibui) means subtle, organized and pure while 派 手 (hade) means the colorful, wild and loud language of the Japanese style. In order to reach an equilibrium one strives for 塩 梅 (anbai). The bag I designed and produced is based on this mindset. The bag is designed, produced and photographed by me. Unisex collection of children's coats based on the Cradle to Cradle design principle. All materials are 100 % chemical free and compostable. Illustration and Graphic design for Ruth Marthaförening recipe cards. Workshop for children in Daikanyama T-site, Tokyo. Arranged with Product Design students at Tama Art University. Unisex Block Sweatshirt made with organic cotton jersey and recycled woven cotton fabric. Designed with Zero Waste technique. Applique and embroidery. Please contact me for custom orders. Tool developed for children who have difficulties talking about emotions with parents or other grown-ups. Little Emotioners can sooth and help children communicate their feelings. Suitable for children aged 3-7. Artwork and layout design for Hubble Jive EP. The Bapron is a bib/apron hybrid made from recycled cotton fabric and an Oeko-tex certified water resistant fabric. Unisex and reversible! The Bapron closes with a press fastener in the back for maximum comfort and convenience. No straps to tie and nothing irritating kids neck! Workshop about traditional clothing and children's cultural belonging in Japan. Arranged by Petronella Nordman at an international pree-school in Tokyo. Illustration for book based on the Cradle to Cradle (C2C) principle. Cover and music video. Collaboration with Markus Bergfors.
import webbrowser import os def work_web(): """ Opens a website and saves it to tmp/url_work.txt if wanted """ if lang == 'ca': listdir = os.listdir('tmp') if 'url_work.txt' in listdir: work_url = open('tmp/url_work.txt', 'r').read() else: work_url = input('Url (sense http://): ') save = input('Guardar? ') save = save.lower() else: listdir = os.listdir('tmp') if 'url_work.txt' in listdir: work_url = open('tmp/url_work.txt', 'r').read() else: work_url = input('Url (without http://): ') save = input('Save? ') save = save.lower() try: if save == "yes" or save == "sí" or save == "y" or save == "s": document = open('tmp/url_work.txt', 'w') document.write(work_url) document.close() webbrowser.open('http://' + work_url) else: webbrowser.open('http://' + work_url) #work link except NameError: webbrowser.open('http://' + work_url) #work link
[ 2 syll. car-ri, ca-rri ] The baby boy name Carri is also used as a girl name, with the latter form being much more common. It is pronounced as KAA-RRiy- †. Carri is derived from English origins. Carri is a variant of the name Cary (English). Carri is infrequently used as a baby name for boys. It is not listed in the top 1000 names. Carri has predominantly been a girl name in the past century. Baby names that sound like Carri include Carrie, Caesear, Caezar, Cahir (Irish), Cairo (English), Carew, Carewe, Carey (English and Irish), Cari, Carie, Carree, Carrey, Carry, Cary (English), Casar (Slavic), Cathaoir (Irish), Cayro, Ceiro (Welsh), Chiro, and Cohor (English). † English pronunciation for Carri: K as in "key (K.IY)" ; AA as in "odd (AA.D)" ; R as in "race (R.EY.S)" ; IY as in "eat (IY.T)"
#!/usr/bin/env python # -*- coding: utf -8 -*- from __future__ import unicode_literals, division class Graph(object): """Defining class Graph.""" def __init__(self, iterable=None): """Initiate an instance of class Graph.""" self._dict = {} try: for item in iterable: try: self._dict.setdefault(item, []) except TypeError as e: e.args = ( 'Node must be an immutable data' ' type (string, integer, tuple, etc.)', ) raise except TypeError: if iterable is not None: self._dict.setdefault(iterable, []) def add_node(self, n): """Add a node to graph.""" try: self._dict.setdefault(n, []) except TypeError as e: e.args = ( 'Node must be an immutable data' ' type (string, integer, tuple, etc.)', ) raise def add_edge(self, n1, n2, weight): """Add a edge from n1 to n2.""" new_node = self._dict.setdefault(n1, []) self._dict.setdefault(n2, []) for tup in new_node: if n2 == tup[0]: raise ValueError('This edge already exists.') else: new_node.append((n2, weight)) def nodes(self): """Show all nodes.""" return self._dict.keys() def edges(self): """Show all edges.""" list_key_value = self._dict.items() list_edges = [] for pair in list_key_value: for tup in pair[1]: list_edges.append((pair[0], tup[0], tup[1]),) return list_edges def del_node(self, n): """Delete a node from graph.""" if n in self._dict: del self._dict[n] for key in self._dict: for tup in self._dict[key]: if n in tup: self._dict[key].remove(tup) else: raise KeyError('No such node in the graph.') def del_edge(self, n1, n2): """Delete a edge from n1 to n2.""" try: for tup in self._dict[n1]: if n2 in tup: self._dict[n1].remove(tup) except KeyError as e: e.args = ('No such edge exists',) raise def has_node(self, n): """Check if n is a node of graph.""" if n in self._dict.keys(): return True else: return False def neighbors(self, n): """Return a list of nodes that have edge connect to n.""" try: return [x[0] for x in self._dict[n]] except KeyError as e: e.agrs = ('Node not in the graph',) raise def adjacent(self, n1, n2): """Check if 2 nodes has connection.""" try: n1_neighbors = [x[0] for x in self._dict[n1]] n2_neighbors = [x[0] for x in self._dict[n2]] return n2 in n1_neighbors or n1 in n2_neighbors except KeyError as e: e.agrs = ('Node not in the graph',) raise def depth_first_traversal(self, start): """ Perform a full depth-traversal of the graph beggining at start. Return full visited path when traversal is complete. Raise a ValueError, if the graph is empty. """ if self._dict == {}: raise ValueError("Can't traverse an empty graph.") path_list = [start] visited_list = [start] current_node = start while current_node: for n in self.neighbors(current_node): if n not in path_list: path_list.append(n) visited_list.append(n) current_node = n break else: try: visited_list.pop() current_node = visited_list[-1] except IndexError: break return path_list def breadth_first_traversal(self, start): """ Perform a full breadth-traversal of the graph beggining at start. Return full visited path when traversal is complete. Raise a ValueError, if the graph is empty. """ if self._dict == {}: raise ValueError("Can't traverse an empty graph.") path_list = [start] pending_list = [] current_node = start while current_node: for n in self.neighbors(current_node): if n not in path_list: path_list.append(n) pending_list.append(n) try: current_node = pending_list.pop(0) except IndexError: break return path_list if __name__ == '__main__': iterable = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) gr = Graph(iterable) edges = [ (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (1, 3), (1, 4), (1, 5), (1, 7), (1, 8), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 5), (3, 7), (3, 8), (3, 9) ] for edge in edges: gr.add_edge(edge[0], edge[1]) breadth = gr.breadth_first_traversal(1) depth = gr.depth_first_traversal(1) print( "For a graph with nodes {} \n and edges\n {}\n" "the results are:\n depth traversal: {},\n breadth traversal: {}." .format(iterable, edges, depth, breadth) )
TLDR; There is a remote control mechanism in hardware that cannot be fully disabled and you cannot get Intel hardware without it. So while this patch may fix the current vulnerability this situation points to the urgent need for hardware diversity. Monday SemiAccurate brought you news of a critical remote exploit in all 2008+ Intel CPU’s. Today we will walk you through a chain of thought based on further investigation on how it could be exploited. While this is only analysis we will note that we believe this is in the wild right now. We would like to make very clear that none of the information here has been publicly proven. However, follow us on an excursion and let us know if you come to a different conclusion. Or if you have other enlightening information, please send it our way. First off all non-server, including workstation but possibly not Atom based, systems contain the hardware needed for this exploit. Over the past several years during conversations with Intel personnel, the hardware is said to be ‘not there’ on machines that don’t have the correct chipset, usually -Q coded variants. Unofficial conversations have led SemiAccurate to believe that the hardware necessary for the AMT exploit is both there and functional. For the short and mid-term past, there is only one chipset die across all ‘small’ (non-E/EP/EX) CPU platforms. Intel claims the ME is ‘fused off’ completely. SemiAccurate does not believe this to be totally accurate. Our research indicates that there were fuses blown but they don’t actually disable the hardware. If Intel’s claims are accurate then why are bits of functionality that should be “hard disabled” present in other consumer grade features? They may not be robust or fully featured but that is a firmware/software issue. The sizes of the latest branch of ME firmware are ~1.5MB for consumer and ~5MB for corporate. So if the hardware isn’t ‘hard off’, what is it? SemiAccurate supposes the fuses are used to indicate what the system should be allowed to do, not what it is actually physically capable of doing. This is similar to what many chipmakers do for CPUs. A 1S Xeon and a consumer CPU can be the same die, one has fuses blown that make it a Xeon, the other becomes an i5 for example. The software and drivers see them as different (based upon fuses) so you can’t install ‘professional’ drivers on an i5 and consumer drivers don’t pass muster on a Xeon. Nvidia does the same with Tesla and GeForce GPUs, same die but different fuses. AMD does the same as well with Radeon and Firepro. While this doesn’t preclude actual board or packaging changes, the silicon is common except a few fuses. Going back to the ME contained in the Intel chipsets we see a similar situation. If the right fuses are blown it can make the chip appear to be consumer level, corporate level, and likely various sub-sets for features. In short, if SemiAccurate’s information is correct the only difference between the various consumer and corporate hardware is the fuses that the ME firmware and installers makes decisions based on. Going back to the GPU examples, there have been various ways over the years to ‘unlock’ disabled cores like this one for some AMD GPUs. Similarly there have been tricks over the years to enable consumer to professional ‘unlocks’ on CPUs and GPUs. The majority of these are done through a technique similar to cracking games and software, you find the places where the software checks for the fuses and modify. Since the fuses are almost universally one time programmable, you can’t change them. However, the software can be changed. If the software sees fuse #3 being blown as ‘consumer hardware’ and not blown as ‘professional hardware’, you modify it so it reads the hardware in the opposite way. You can literally change one value and have the same hardware read “fuse-blown” as ‘professional hardware’ and “fuse-not-blown” as ‘consumer hardware’. While DRM in games and apps are far more sophisticated than this with multiple levels of checks it is possible to modify the software for access. We question whether Intel has bothered to put such multilayered defenses into their firmware updates much less obscure firmware bits for the ME. Since you can find modified system BIOS and ME firmware for Intel hardware, and hacks seem to be quite prevalent, we think the level of protection on ME code is likely quite low to non-existent. It is also fairly well documented, uses commonly available cores (ARC), and runs Java. This is the long way of saying it wouldn’t take much to modify some ME code rather arbitrarily if you wanted to spend the time and effort. Time and effort is key, remember this later. Another likely path is that the installer, not the firmware itself, does the validity checks. If this is the case, then an attacker can simply install legitimate ME firmware on hardware that it is not intended for. This would violate Intel policy and possibly open up any sophisticated nation/state hackers to some very steep financial penalties or lawsuits from Intel so we doubt this will happen in the wild. Yes that was sarcasm. Back to the ME and AMT exploit. SemiAccurate has strong reason to believe that there is an active exploit in the wild at the moment and it is a very sophisticated piece of code. Officially Intel says that the exploit is mitigated if AMT is turned off, the software is uninstalled, and several other hurdles are cleared. These official documents are very vague in the Description: section which lists a very generic and simple explanation of a possible remote hack. Other sources have described the remote version of the exploit as using custom tools to authenticate with privilege and do nefarious things to ME/AMT enabled machines. This strongly suggests that the parties behind the exploit are very sophisticated and skilled in what they do, think nation/state level actors, not bored teenagers. People with time and that can or want to afford the effort. In the local attack section Intel is equally vague, essentially only verifying that a local attacker could provision AMT, ISM, and SBT, then use the remote exploit. Once again SemiAccurate’s sources are pointing to an incredibly sophisticated and clever hack. It uses phishing emails to deliver malware which provisions AMT on the target system. We realize how complex this is to do and how many levels it entails. This is not trivial by any means, we do not mean for this to sound trivial, but the path is there. You not only have to know your victim but have an exploit for the OS they are running, and have patches for the ME firmware on the system they receive email on. Given a nation/state level actor, this may not be easy but it certainly is quite plausible. Once this patched ME firmware is installed, SemiAccurate is unaware of any method to detect that your ME code has been modified. If the phishing email leaves traces of itself, drivers, and code on the host system, that would be detectable, but would the firmware itself be flagged by anything? We doubt it. If it drops, downloads, or simply installs legitimate Intel AMT drivers and ME firmware, would those be flagged by antivirus/antimalware tools? We don’t think so, after all they are legitimate files from a legitimate supplier. Modified firmware itself would not fall into this category but if you only modified a few bits for a fuse check and didn’t change the versions numbers, reporting tools, if they exist, are unlikely to show very much amiss. Then again if a party exploiting this vulnerability is that sophisticated, fooling anything less than a full cryptographic checksum of the installed code should be trivial. Do you checksum your ME firmware on a regular basis? We lean towards believing Intel is accurate on the server claims but we can’t say with authority that they are not vulnerable. Servers tend to use IPMI of which AMT is a superset of so it could go either way. One example of how to do it right is Dell’s excellent DRAC cards which should avoid the issue on their hardware. Since Intel has been a little less than forthcoming on the ME/AMT issue, and security in general, we would urge readers to verify any claim they make. And verify it in detail. However, Intel servers are starting to look like they are in the clear. Intel also makes the same claim for consumer systems. Based on the fusings this appears to be the case. One look at the sizes of the ME firmware packages makes it clear there is a lot less in the consumer variant than there is in the professional version. The consumer code is about a third of the size of the professional version for those who didn’t check earlier, ~1.5MB vs ~5MB for the pedantic. The consumer firmware package won’t install on any professional hardware and conversely the professional software won’t install on any consumer hardware that SemiAccurate knows of. By Intel’s standards, this means consumer hardware is safe, and on the surface, it is. So back to Monday’s AMT vulnerability. We have Intel saying that servers and consumer systems are not at risk, only corporate SKUs from 2008 onwards with AMT enabled are in danger. This is true. Unless the attacker can modify the ME firmware to run on boards it wasn’t designed to install on. And deliver it via malware in a phishing email. And it goes undetected by the host system. And it can turn on AMT once installed. And the hacker can write their own tools to do things on the system with the tweaked ME firmware. SemiAccurate is aware that there are a lot of “ifs” in that chain of logic. If any of them are not possible, then consumer hardware is safe. Based on our research over the past few days and much more done on related topics over the past few years, we believe all of the above is well within the means of any smart individual and quite likely for any nation/state actors. Even if the flash size of the consumer SKUs is too small, a bit of custom code could add any feature needed. This isn’t trivial work, but if you can accomplish any of the other steps, custom coding ME firmware is well within reason. Remember Stuxnet? So that brings us to the several million dollar question, are ‘consumer’ PC’s safe or do they have the same AMT vulnerability? If you play by the rules, use the official tools, firmware, and code available from Intel, the answer is yes. So Intel is right in saying they are unaffected. Do you know any hackers who only play by the rules and use official tools, firmware, and code when plying their trade? If so, rest easy and don’t worry about the AMT vulnerabilities any more. If not, you would need to have a complex chain of “if’s” happen for it to be a problem. What are the odds?
from Vintageous import PluginLogger import sublime import os _logger = PluginLogger(__name__) class DotFile(object): def __init__(self, path): self.path = path @staticmethod def from_user(): path = os.path.join(sublime.packages_path(), 'User', '.vintageousrc') return DotFile(path) def run(self): try: with open(self.path, 'r') as f: for line in f: cmd, args = self.parse(line) if cmd: _logger.info('[DotFile] running: {0} {1}'.format(cmd, args)) sublime.active_window().run_command(cmd, args) except FileNotFoundError: pass def parse(self, line): try: _logger.info('[DotFile] parsing line: {0}'.format(line)) if line.startswith((':map ')): line = line[1:] return ('ex_map', {'command_line': line.rstrip()}) if line.startswith((':omap ')): line = line[len(':omap '):] return ('ex_omap', {'cmd': line.rstrip()}) if line.startswith((':vmap ')): line = line[len(':vmap '):] return ('ex_vmap', {'cmd': line.rstrip()}) if line.startswith((':let ')): line = line[1:] return ('ex_let', {'command_line': line.strip()}) except Exception: print('Vintageous: bad config in dotfile: "%s"' % line.rstrip()) _logger.debug('bad config inf dotfile: "%s"', line.rstrip()) return None, None
What Zipline have accomplished here is incredible – I’ve been stunned by the 5-minute order-to-takeoff response time, the 80km range, and the amount of safety and resilience built into the drones. Even technologically, they’ve made some amazing improvements – their most recent revision of the recapture system reduced the capture target on the drone from about 3 feet to about a centimetre, and their drop target at the hospitals is as small as two car parking spaces. In some of the videos you can see a hospital has a patch of grass which is fairly worn with all the deliveries – which makes me think they’re accurately dropped by parachute to within a 50cm.
from django.test import TestCase from django.core.exceptions import ValidationError import pytest from .models import Named, Notable, DateRange class TestNamed(TestCase): def test_str(self): named_obj = Named(name='foo') assert str(named_obj) == 'foo' class TestNotable(TestCase): def test_has_notes(self): noted = Notable() assert False == noted.has_notes() noted.notes = 'some text' assert True == noted.has_notes() noted.notes = '' assert False == noted.has_notes() noted.notes = None assert False == noted.has_notes() class TestDateRange(TestCase): def test_dates(self): span = DateRange() # no dates set assert '' == span.dates # date range with start and end span.start_year = 1900 span.end_year = 1901 assert '1900-1901' == span.dates # start and end dates are same year = single year span.end_year = span.start_year assert span.start_year == span.dates # start date but no end span.end_year = None assert '1900-' == span.dates # end date but no start span.end_year = 1950 span.start_year = None assert '-1950' == span.dates def test_clean_fields(self): with pytest.raises(ValidationError): DateRange(start_year=1901, end_year=1900).clean_fields() # should not raise exception # - same year is ok (single year range) DateRange(start_year=1901, end_year=1901).clean_fields() # - end after start DateRange(start_year=1901, end_year=1905).clean_fields() # - only one date set DateRange(start_year=1901).clean_fields() DateRange(end_year=1901).clean_fields() # exclude set DateRange(start_year=1901, end_year=1900).clean_fields(exclude=['start_year']) DateRange(start_year=1901, end_year=1900).clean_fields(exclude=['end_year']) class TestRobotsTxt(TestCase): '''Test for default robots.txt inclusion''' def test_robots_txt(self): res = self.client.get('/robots.txt') # successfully gets robots.txt assert res.status_code == 200 # is text/plain assert res['Content-Type'] == 'text/plain' # uses robots.txt template assert 'robots.txt' in [template.name for template in res.templates] with self.settings(DEBUG=False): res = self.client.get('/robots.txt') self.assertContains(res, 'Disallow: /admin') with self.settings(DEBUG=True): res = self.client.get('/robots.txt') self.assertContains(res, 'Disallow: /')
Nigeria’s Afro pop artist Ndee has hit the studio once again and this time he’s here with this magical sound and conscious song titled, End The Trend. The artist who is under the wings of Mkpon Mkpon Entertainment got inspired by Neo Life International philosophy and he decided to come up with this beautiful piece. According to him, he believes Neo Life who has been in existence for over 60 years now and still waxing strong is on a mission to make the world a healthier and a happier place by ending the trend to Poor Nutrition, Chronic Disease and Poverty. Support the cause, enjoy good Music and stay healthy.
from random import randint def montyhall(firstdoor="duck", switchornot="duck"): """ This function can be called with no parameters, so you can play the game, or with params to simulate the games """ sim = False if firstdoor == "duck" or switchornot == "duck": sim = True doors = ["", "", ""] cardoor = randint(0,2) doors[cardoor] = "car" for idx, door in enumerate(doors): if door != "car": doors[idx] = "goat" if sim: print("You're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats.") print("D D D") print("1 2 3") firstpick = 999 if sim: firstpick = int(input("Pick a door: ")) - 1 else: firstpick = int(firstdoor) - 1 if sim: print("I will now open a door!") others = doors st = others[firstpick] others[firstpick] = "none" notfound = True reveal = 0 while notfound: r = randint(0,2) if others[r] == "goat": reveal = r notfound = False if sim: print("Door "+str(reveal+1)+" is a goat!") newprint = doors pstr = "" for idx, np in enumerate(newprint): if idx != reveal: if pstr == "": pstr = "D" else: pstr = pstr + " D" else: if pstr == "": pstr = "G" else: pstr = pstr + " G" if sim: print(pstr) if sim: switch = input("You selected door "+str(firstpick+1)+" would you like to change? (y/n): ") else: switch = switchornot newpick = "no" if switch == "y": ndoors = doors pdoo = "" for idx, nd in enumerate(ndoors): if idx != reveal and idx != firstpick: pdoo = str(idx + 1) newpick = doors[idx] if sim: print("You have switched to door "+pdoo) print(newpick) else: return newpick else: if sim: print("You have stayed with door " + str(firstpick+1)) print(st) else: return st """ This code calls the sim function tons of times and displays the results """ #Settings switchfail = 0 switchwin = 0 switchtimes = 10000 stayfail = 0 staywin = 0 staytimes = 10000 #Don't touch code below unless you know what you are doing. for i in range(switchtimes): mh = montyhall(randint(1,3), "y") if mh == "car": switchwin = switchwin + 1 else: switchfail = switchfail + 1 for i in range(staytimes): mh2 = montyhall(randint(1,3), "n") if mh2 == "car": staywin = staywin + 1 else: stayfail = stayfail + 1 print("== MONTY HALL ==") print("Switching "+str(switchtimes)+" times") print("Staying "+str(staytimes)+" times") print("=== RESULTS ===") print("Switch: "+str((switchwin/switchtimes) * 100)+"% win, "+str((switchfail/switchtimes) * 100)+"% lose") print("Stay: "+str((staywin/staytimes) * 100)+"% win, "+str((stayfail/staytimes) * 100)+"% lose")
In what is shaping up as the battle of San Diego’s biotechnology tools titans, Life Technologies (NASDAQ: LIFE) has filed a patent-infringement suit against rival Illumina, claiming that some of Illumina’s best-selling genetic-sequencing products violate Life Tech’s intellectual property. The suit, filed in U.S. District Court in Delaware, claims that certain Illumina products, including the Genome Analyzer and the second-generation Genome Analyzer II, infringe upon three Life Tech patents. The suit seeks an unspecified amount in damages, and a permanent injunction restraining Illumina (NASDAQ: ILMN) from further infringement. If granted, the injunction would prevent Illumina from selling its equipment. Telephone and e-mail messages to an Illumina spokesperson were not returned. Illumina’s Genome Analyzer products are a mainstay of the company’s genetics analysis business, and are important to Illumina’s growth. The $50,000 whole-genome analysis that Illumina began offering to the public in June uses the Genome Analyzer. The company has stated that one of its corporate goals is to make the Genome Analyzer the industry standard for genetic analysis. Last year, the device accounted for the bulk of Illumina’s $64.8 million increase in instrument sales. Life Technologies, formed last November through the merger of Invitrogen and Applied Biosystems, claims it is the leader in the genetic sequencing business. The Carlsbad, CA-based company had revenue of $3.1 billion in 2008, dwarfing Illumina’s 2008 revenue of $570 million. Listed as plaintiffs along with Life Tech are patent owners Alexander Chetverin and Helena Chetverina, both of Russia; The Institute for Protein Research of the Russian Academy of Sciences; and William Hone of New York. According to the suit, the patents cover certain methods of amplifying and expressing nucleic acid, a building block of DNA. Applied Biosystems had an exclusive license to the patents, which issued in the late 1990s. Illumina subsidiary Solexa is also named as a defendant.
from setuptools import setup, find_packages from codecs import open from os import path __version__ = '0.0.1' here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # get the dependencies and installs with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\n') install_requires = [x.strip() for x in all_reqs if 'git+' not in x] dependency_links = [x.strip().replace('git+', '') for x in all_reqs if 'git+' not in x] setup( name='mirrord', version=__version__, description='yet another mirror daemon', long_description=long_description, url='https://github.com/pandada8/mirrord', download_url='https://github.com/pandada8/mirrord/tarball/' + __version__, license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', ], keywords='', entry_points={ 'console_scripts': [ 'mirrord = mirrord.daemon:run' ] }, packages=find_packages(exclude=['docs', 'tests*']), include_package_data=True, author='Pandada8', install_requires=install_requires, dependency_links=dependency_links, author_email='pandada8@gmail.com' )
Welcome to this The Nursing Diary product report page. Before we get going, allow me to briefly describe just how this site works. I hope to provide you with an impartial report on the product. I use statistical indicators to create my product evaluations, ensuring they are 100% impartial. I also provide information about where to purchase, a customer comments system than only allows verified customers to review and my exclusive purchase bonus that benefits you for using r.ecommended.com. Please be aware that I do have an affiliate association with thenursingdiary.com, for more information please see how this site is financed. Due to the large number of items on this website, I'm not able to individually look at every one. But I still would like to provide my visitors with an analysis of the product. So what to do? The answer is statistics. Having said that, seeing as this is a brand new product it's a little too early to tell just what reaction of customers is. We don't yet have any sales statistics. So for the moment we are examining it as being 'average' and waiting more time before giving it our final verdict. Please note that r.ecommended.com does not sell The Nursing Diary directly. Instead, we'll only hyperlink you through to the thenursingdiary.com site to purchase the product. https://thenursingdiary.com/ is the sole site where The Nursing Diary is on the market to purchase. It is for sale there for the asking price of 0.00. Taking into account every little thing, we have given The Nursing Diary an over-all rating of 3.44. We'd say this is definitely a product to consider - add it to your shortlist. Now, while our reviews are fully neutral, we do have an “affiliate” connection with the product publisher. This means that when we send them over a purchaser we're compensated with a commission fee. If you use one of the hyperlinks on this web page to check out thenursingdiary.com and finally end up buying, we will be compensated. In turn, we would like to reward you. This pay back is what we call the purchase bonus. There’s no expense to you – all you have to do is use our link and you’ll get the reward. For more information concerning the bonus click here.
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # 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. # ============================================================================== """Builds the Wide-ResNet Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import custom_ops as ops import numpy as np import tensorflow as tf def residual_block( x, in_filter, out_filter, stride, activate_before_residual=False): """Adds residual connection to `x` in addition to applying BN->ReLU->3x3 Conv. Args: x: Tensor that is the output of the previous layer in the model. in_filter: Number of filters `x` has. out_filter: Number of filters that the output of this layer will have. stride: Integer that specified what stride should be applied to `x`. activate_before_residual: Boolean on whether a BN->ReLU should be applied to x before the convolution is applied. Returns: A Tensor that is the result of applying two sequences of BN->ReLU->3x3 Conv and then adding that Tensor to `x`. """ if activate_before_residual: # Pass up RELU and BN activation for resnet with tf.variable_scope('shared_activation'): x = ops.batch_norm(x, scope='init_bn') x = tf.nn.relu(x) orig_x = x else: orig_x = x block_x = x if not activate_before_residual: with tf.variable_scope('residual_only_activation'): block_x = ops.batch_norm(block_x, scope='init_bn') block_x = tf.nn.relu(block_x) with tf.variable_scope('sub1'): block_x = ops.conv2d( block_x, out_filter, 3, stride=stride, scope='conv1') with tf.variable_scope('sub2'): block_x = ops.batch_norm(block_x, scope='bn2') block_x = tf.nn.relu(block_x) block_x = ops.conv2d( block_x, out_filter, 3, stride=1, scope='conv2') with tf.variable_scope( 'sub_add'): # If number of filters do not agree then zero pad them if in_filter != out_filter: orig_x = ops.avg_pool(orig_x, stride, stride) orig_x = ops.zero_pad(orig_x, in_filter, out_filter) x = orig_x + block_x return x def _res_add(in_filter, out_filter, stride, x, orig_x): """Adds `x` with `orig_x`, both of which are layers in the model. Args: in_filter: Number of filters in `orig_x`. out_filter: Number of filters in `x`. stride: Integer specifying the stide that should be applied `orig_x`. x: Tensor that is the output of the previous layer. orig_x: Tensor that is the output of an earlier layer in the network. Returns: A Tensor that is the result of `x` and `orig_x` being added after zero padding and striding are applied to `orig_x` to get the shapes to match. """ if in_filter != out_filter: orig_x = ops.avg_pool(orig_x, stride, stride) orig_x = ops.zero_pad(orig_x, in_filter, out_filter) x = x + orig_x orig_x = x return x, orig_x def build_wrn_model(images, num_classes, wrn_size): """Builds the WRN model. Build the Wide ResNet model from https://arxiv.org/abs/1605.07146. Args: images: Tensor of images that will be fed into the Wide ResNet Model. num_classes: Number of classed that the model needs to predict. wrn_size: Parameter that scales the number of filters in the Wide ResNet model. Returns: The logits of the Wide ResNet model. """ kernel_size = wrn_size filter_size = 3 num_blocks_per_resnet = 4 filters = [ min(kernel_size, 16), kernel_size, kernel_size * 2, kernel_size * 4 ] strides = [1, 2, 2] # stride for each resblock # Run the first conv with tf.variable_scope('init'): x = images output_filters = filters[0] x = ops.conv2d(x, output_filters, filter_size, scope='init_conv') first_x = x # Res from the beginning orig_x = x # Res from previous block for block_num in range(1, 4): with tf.variable_scope('unit_{}_0'.format(block_num)): activate_before_residual = True if block_num == 1 else False x = residual_block( x, filters[block_num - 1], filters[block_num], strides[block_num - 1], activate_before_residual=activate_before_residual) for i in range(1, num_blocks_per_resnet): with tf.variable_scope('unit_{}_{}'.format(block_num, i)): x = residual_block( x, filters[block_num], filters[block_num], 1, activate_before_residual=False) x, orig_x = _res_add(filters[block_num - 1], filters[block_num], strides[block_num - 1], x, orig_x) final_stride_val = np.prod(strides) x, _ = _res_add(filters[0], filters[3], final_stride_val, x, first_x) with tf.variable_scope('unit_last'): x = ops.batch_norm(x, scope='final_bn') x = tf.nn.relu(x) x = ops.global_avg_pool(x) logits = ops.fc(x, num_classes) return logits
Technology companies entering other sectors like Transportation, Medicine, Entertainment. Large cash reserves for research & development. What might happen, but not necessarily what will happen. Uses radar, camera and lasers to map surroundings. See more than a human. Google 1.2 million miles of testing - only accident were people driven cars. Many will choose to use temporary rentals rather than own. A Japanese company expects to have a fleet of self driving taxis operational by 2020 for the Olympic games. 33,000 highway fatalities, 3.9 million injuries and 24 million damaged vehicles, cost 870 billion. Connected cars will help to reduce traffic jams & spread traffic around. Cars could be cheaper with less need for injury prevention and other components. Elderly will always have transportation - no loss of their car. Next smartphone may be a watch. Tests suggest we will pay more when ordering online. More conversational, portable and anticipate needs. If going out it will check weather and let us know if rain is expected. Jibo, Buddy, Pepper from Softbank - sold 1,000 units in less than a minute. Home security & monitors - detect your presence. Technology companies heavily investing in research and development. app for detecting skin cancers. for eye examination used in 3rd world countries. Detect mood and offer advice. 10% of death due to diagnostic error. IBM Deep Blue - use data from medical records, images and personal health monitors to predict or diagnose symptoms. Personal digital assistants will act as reminders and coaches. Example slow down eating. Drs will become more health coaches - confirming software based diagnostics and implementing treatment plans. Sports - will be able to see things from the perspective of a Quarterback. With eye tracking will be able to see where the QB is looking. Movies will be more like games. Will be able to become a character so see things from a character's perspective. Already a film festival for showcasing Virtual Reality movies. Display labels on the things we look at. Real Estate - virtual visits to properties. May even be able to see home with their own furniture. already, but large industry with high volume & resource to program.
from binascii import unhexlify from time import time from django import forms from django.forms import ModelForm, Form from django.utils.translation import ugettext_lazy as _ from django_otp.forms import OTPAuthenticationFormMixin from django_otp.oath import totp from django_otp.plugins.otp_totp.models import TOTPDevice from two_factor.utils import totp_digits try: from otp_yubikey.models import RemoteYubikeyDevice, YubikeyDevice except ImportError: RemoteYubikeyDevice = YubikeyDevice = None from .models import (PhoneDevice, get_available_phone_methods, get_available_methods) class MethodForm(forms.Form): method = forms.ChoiceField(label=_("Method"), initial='generator', widget=forms.RadioSelect) def __init__(self, **kwargs): super(MethodForm, self).__init__(**kwargs) self.fields['method'].choices = get_available_methods() class PhoneNumberMethodForm(ModelForm): method = forms.ChoiceField(widget=forms.RadioSelect, label=_('Method')) class Meta: model = PhoneDevice fields = 'number', 'method', def __init__(self, **kwargs): super(PhoneNumberMethodForm, self).__init__(**kwargs) self.fields['method'].choices = get_available_phone_methods() class PhoneNumberForm(ModelForm): class Meta: model = PhoneDevice fields = 'number', class DeviceValidationForm(forms.Form): token = forms.IntegerField(label=_("Token"), min_value=1, max_value=int('9' * totp_digits())) error_messages = { 'invalid_token': _('Entered token is not valid.'), } def __init__(self, device, **args): super(DeviceValidationForm, self).__init__(**args) self.device = device def clean_token(self): token = self.cleaned_data['token'] if not self.device.verify_token(token): raise forms.ValidationError(self.error_messages['invalid_token']) return token class YubiKeyDeviceForm(DeviceValidationForm): token = forms.CharField(label=_("YubiKey")) error_messages = { 'invalid_token': _("The YubiKey could not be verified."), } def clean_token(self): self.device.public_id = self.cleaned_data['token'][:-32] return super(YubiKeyDeviceForm, self).clean_token() class TOTPDeviceForm(forms.Form): token = forms.IntegerField(label=_("Token"), min_value=0, max_value=int('9' * totp_digits())) error_messages = { 'invalid_token': _('Entered token is not valid.'), } def __init__(self, key, user, metadata=None, **kwargs): super(TOTPDeviceForm, self).__init__(**kwargs) self.key = key self.tolerance = 1 self.t0 = 0 self.step = 30 self.drift = 0 self.digits = totp_digits() self.user = user self.metadata = metadata or {} @property def bin_key(self): """ The secret key as a binary string. """ return unhexlify(self.key.encode()) def clean_token(self): token = self.cleaned_data.get('token') validated = False t0s = [self.t0] key = self.bin_key if 'valid_t0' in self.metadata: t0s.append(int(time()) - self.metadata['valid_t0']) for t0 in t0s: for offset in range(-self.tolerance, self.tolerance): if totp(key, self.step, t0, self.digits, self.drift + offset) == token: self.drift = offset self.metadata['valid_t0'] = int(time()) - t0 validated = True if not validated: raise forms.ValidationError(self.error_messages['invalid_token']) return token def save(self): return TOTPDevice.objects.create(user=self.user, key=self.key, tolerance=self.tolerance, t0=self.t0, step=self.step, drift=self.drift, digits=self.digits, name='default') class DisableForm(forms.Form): understand = forms.BooleanField(label=_("Yes, I am sure")) class AuthenticationTokenForm(OTPAuthenticationFormMixin, Form): otp_token = forms.IntegerField(label=_("Token"), min_value=1, max_value=int('9' * totp_digits())) def __init__(self, user, initial_device, **kwargs): """ `initial_device` is either the user's default device, or the backup device when the user chooses to enter a backup token. The token will be verified against all devices, it is not limited to the given device. """ super(AuthenticationTokenForm, self).__init__(**kwargs) self.user = user # YubiKey generates a OTP of 44 characters (not digits). So if the # user's primary device is a YubiKey, replace the otp_token # IntegerField with a CharField. if RemoteYubikeyDevice and YubikeyDevice and \ isinstance(initial_device, (RemoteYubikeyDevice, YubikeyDevice)): self.fields['otp_token'] = forms.CharField(label=_('YubiKey')) def clean(self): self.clean_otp(self.user) return self.cleaned_data class BackupTokenForm(AuthenticationTokenForm): otp_token = forms.CharField(label=_("Token"))
Here at Utah Valley Church, we have very simple family integrated service which consists of several contemporary worship songs and a time of Bible teaching. Communion (the sacrament or the Lord’s supper) is also made available at this time. Take some time to hang out before each service and enjoy hot cocoa or coffee.
"""Dense univariate polynomials with coefficients in Galois fields.""" import math import random from ..ntheory import factorint from .densearith import (dmp_add, dmp_add_term, dmp_mul, dmp_quo, dmp_rem, dmp_sqr, dmp_sub) from .densebasic import dmp_degree_in, dmp_normal, dmp_one_p from .densetools import dmp_ground_monic from .euclidtools import dmp_gcd from .polyconfig import query from .polyutils import _sort_factors def dup_gf_pow_mod(f, n, g, K): """ Compute ``f**n`` in ``GF(q)[x]/(g)`` using repeated squaring. Given polynomials ``f`` and ``g`` in ``GF(q)[x]`` and a non-negative integer ``n``, efficiently computes ``f**n (mod g)`` i.e. the remainder of ``f**n`` from division by ``g``, using the repeated squaring algorithm. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(3*x**2 + 2*x + 4) >>> g = R.to_dense(x + 1) >>> dup_gf_pow_mod(f, 3, g, R.domain) [] References ========== * :cite:`Gathen1999modern`, algorithm 4.8 """ if not n: return [K.one] elif n == 1: return dmp_rem(f, g, 0, K) elif n == 2: return dmp_rem(dmp_sqr(f, 0, K), g, 0, K) h = [K.one] while True: if n & 1: h = dmp_mul(h, f, 0, K) h = dmp_rem(h, g, 0, K) n -= 1 n >>= 1 if not n: break f = dmp_sqr(f, 0, K) f = dmp_rem(f, g, 0, K) return h def dup_gf_compose_mod(g, h, f, K): """ Compute polynomial composition ``g(h)`` in ``GF(q)[x]/(f)``. Examples ======== >>> R, x = ring('x', FF(5)) >>> g = R.to_dense(3*x**2 + 2*x + 4) >>> h = R.to_dense(2*x**2 + 2*x + 2) >>> f = R.to_dense(4*x + 3) >>> dup_gf_compose_mod(g, h, f, R.domain) [4 mod 5] """ if not g: return [] comp = [g[0]] for a in g[1:]: comp = dmp_mul(comp, h, 0, K) comp = dmp_add_term(comp, a, 0, 0, K) comp = dmp_rem(comp, f, 0, K) return comp def dup_gf_trace_map(a, b, c, n, f, K): """ Compute polynomial trace map in ``GF(q)[x]/(f)``. Given a polynomial ``f`` in ``GF(q)[x]``, polynomials ``a``, ``b``, ``c`` in the quotient ring ``GF(q)[x]/(f)`` such that ``b = c**t (mod f)`` for some positive power ``t`` of ``q``, and a positive integer ``n``, returns a mapping:: a -> a**t**n, a + a**t + a**t**2 + ... + a**t**n (mod f) In factorization context, ``b = x**q mod f`` and ``c = x mod f``. This way we can efficiently compute trace polynomials in equal degree factorization routine, much faster than with other methods, like iterated Frobenius algorithm, for large degrees. Examples ======== >>> R, x = ring('x', FF(5)) >>> a = R.to_dense(x + 2) >>> b = R.to_dense(4*x + 4) >>> c = R.to_dense(x + 1) >>> f = R.to_dense(3*x**2 + 2*x + 4) >>> dup_gf_trace_map(a, b, c, 4, f, R.domain) ([1 mod 5, 3 mod 5], [1 mod 5, 3 mod 5]) References ========== * :cite:`Gathen1992ComputingFM`, algorithm 5.2 """ u = dup_gf_compose_mod(a, b, f, K) v = b if n & 1: U = dmp_add(a, u, 0, K) V = b else: U = a V = c n >>= 1 while n: u = dmp_add(u, dup_gf_compose_mod(u, v, f, K), 0, K) v = dup_gf_compose_mod(v, v, f, K) if n & 1: U = dmp_add(U, dup_gf_compose_mod(u, V, f, K), 0, K) V = dup_gf_compose_mod(v, V, f, K) n >>= 1 return dup_gf_compose_mod(a, V, f, K), U def dup_gf_random(n, K): """ Generate a random polynomial in ``GF(q)[x]`` of degree ``n``. Examples ======== >>> dup_gf_random(4, FF(5)) # doctest: +SKIP [1 mod 5, 4 mod 5, 4 mod 5, 2 mod 5, 1 mod 5] """ return [K.one] + [K(random.randint(0, K.order - 1)) for i in range(n)] def dup_gf_irreducible(n, K): """ Generate random irreducible polynomial of degree ``n`` in ``GF(q)[x]``. Examples ======== >>> dup_gf_irreducible(4, FF(5)) # doctest: +SKIP [1 mod 5, 2 mod 5, 4 mod 5, 4 mod 5, 3 mod 5] >>> dup_gf_irreducible_p(_, FF(5)) True """ while True: f = dup_gf_random(n, K) if dup_gf_irreducible_p(f, K): return f def dup_gf_irred_p_ben_or(f, K): """ Ben-Or's polynomial irreducibility test over finite fields. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**10 + 4*x**9 + 2*x**8 + 2*x**7 + 3*x**6 + ... 2*x**5 + 4*x**4 + x**3 + 4*x**2 + 4) >>> dup_gf_irred_p_ben_or(f, R.domain) True >>> f = R.to_dense(3*x**2 + 2*x + 4) >>> dup_gf_irred_p_ben_or(f, R.domain) False References ========== * :cite:`Ben-Or1981ff` """ n, q = dmp_degree_in(f, 0, 0), K.order if n <= 1: return True x = [K.one, K.zero] f = dmp_ground_monic(f, 0, K) H = h = dup_gf_pow_mod(x, q, f, K) for i in range(n//2): g = dmp_sub(h, x, 0, K) if dmp_one_p(dmp_gcd(f, g, 0, K), 0, K): h = dup_gf_compose_mod(h, H, f, K) else: return False return True def dup_gf_irred_p_rabin(f, K): """ Rabin's polynomial irreducibility test over finite fields. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**10 + 4*x**9 + 2*x**8 + 2*x**7 + 3*x**6 + ... 2*x**5 + 4*x**4 + x**3 + 4*x**2 + 4) >>> dup_gf_irred_p_rabin(f, R.domain) True >>> f = R.to_dense(3*x**2 + 2*x + 4) >>> dup_gf_irred_p_rabin(f, R.domain) False References ========== * :cite:`Gathen1999modern`, algorithm 14.36 """ n, q = dmp_degree_in(f, 0, 0), K.order if n <= 1: return True x = [K.one, K.zero] f = dmp_ground_monic(f, 0, K) indices = {n//d for d in factorint(n)} H = h = dup_gf_pow_mod(x, q, f, K) for i in range(1, n): if i in indices: g = dmp_sub(h, x, 0, K) if not dmp_one_p(dmp_gcd(f, g, 0, K), 0, K): return False h = dup_gf_compose_mod(h, H, f, K) return h == x _irred_methods = { 'ben-or': dup_gf_irred_p_ben_or, 'rabin': dup_gf_irred_p_rabin, } def dup_gf_irreducible_p(f, K): """ Test irreducibility of a polynomial ``f`` in ``GF(q)[x]``. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**10 + 4*x**9 + 2*x**8 + 2*x**7 + 3*x**6 + ... 2*x**5 + 4*x**4 + x**3 + 4*x**2 + 4) >>> dup_gf_irreducible_p(f, R.domain) True >>> f = R.to_dense(3*x**2 + 2*x + 4) >>> dup_gf_irreducible_p(f, R.domain) False """ method = query('GF_IRRED_METHOD') return _irred_methods[method](f, K) def dup_gf_primitive_p(f, K): """Test if ``f`` is a primitive polynomial over ``GF(p)``.""" p = K.characteristic assert K.order == p if not dup_gf_irreducible_p(f, K): return False n = dmp_degree_in(f, 0, 0) t = [K.one] + [K.zero]*n for m in range(n, p**n - 1): r = dmp_rem(t, f, 0, K) if r == [K.one]: return False t = dmp_mul(r, [K.one, K.zero], 0, K) return True def dup_gf_Qmatrix(f, K): """ Calculate Berlekamp's ``Q`` matrix. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(3*x**2 + 2*x + 4) >>> dup_gf_Qmatrix(f, R.domain) [[1 mod 5, 0 mod 5], [3 mod 5, 4 mod 5]] >>> f = R.to_dense(x**4 + 1) >>> dup_gf_Qmatrix(f, R.domain) [[1 mod 5, 0 mod 5, 0 mod 5, 0 mod 5], [0 mod 5, 4 mod 5, 0 mod 5, 0 mod 5], [0 mod 5, 0 mod 5, 1 mod 5, 0 mod 5], [0 mod 5, 0 mod 5, 0 mod 5, 4 mod 5]] References ========== * :cite:`Geddes1992algorithms`, algorithm 8.5 """ n, q = dmp_degree_in(f, 0, 0), K.order r = [K.one] + [K.zero]*(n - 1) Q = [r.copy()] + [[]]*(n - 1) for i in range(1, (n - 1)*q + 1): c, r[1:], r[0] = r[-1], r[:-1], K.zero for j in range(n): r[j] -= c*f[-j - 1] if not (i % q): Q[i//q] = r.copy() return Q def dup_gf_berlekamp(f, K): """ Factor a square-free polynomial over finite fields of small order. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**4 + 1) >>> dup_gf_berlekamp([1, 0, 0, 0, 1], R.domain) [[1 mod 5, 0 mod 5, 2 mod 5], [1 mod 5, 0 mod 5, 3 mod 5]] References ========== * :cite:`Geddes1992algorithms`, algorithm 8.4 * :cite:`Knuth1985seminumerical`, section 4.6.2 """ from .solvers import RawMatrix Q = dup_gf_Qmatrix(f, K) Q = RawMatrix(Q) - RawMatrix.eye(len(Q)) V = Q.T.nullspace() for i, v in enumerate(V): V[i] = dmp_normal(list(reversed(v)), 0, K) factors = [f] for v in V[1:]: for f in list(factors): for s in range(K.order): h = dmp_add_term(v, -K(s), 0, 0, K) g = dmp_gcd(f, h, 0, K) if not dmp_one_p(g, 0, K) and g != f: factors.remove(f) f = dmp_quo(f, g, 0, K) factors.extend([f, g]) if len(factors) == len(V): return _sort_factors(factors, multiple=False) return _sort_factors(factors, multiple=False) def dup_gf_ddf_zassenhaus(f, K): """ Cantor-Zassenhaus: Deterministic Distinct Degree Factorization. Given a monic square-free polynomial ``f`` in ``GF(q)[x]``, computes partial distinct degree factorization ``f_1 ... f_d`` of ``f`` where ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0`` is an argument to the equal degree factorization routine. Examples ======== >>> R, x = ring('x', FF(11)) >>> f = R.to_dense(x**15 - 1) >>> dup_gf_ddf_zassenhaus(f, R.domain) [([1 mod 11, 0 mod 11, 0 mod 11, 0 mod 11, 0 mod 11, 10 mod 11], 1), ([1 mod 11, 0 mod 11, 0 mod 11, 0 mod 11, 0 mod 11, 1 mod 11, 0 mod 11, 0 mod 11, 0 mod 11, 0 mod 11, 1 mod 11], 2)] To obtain factorization into irreducibles, use equal degree factorization procedure (EDF) with each of the factors. References ========== * :cite:`Gathen1999modern`, algorithm 14.3 * :cite:`Geddes1992algorithms`, algorithm 8.8 See Also ======== dup_gf_edf_zassenhaus """ factors, q = [], K.order g, x = [[K.one, K.zero]]*2 for i in range(1, dmp_degree_in(f, 0, 0)//2 + 1): g = dup_gf_pow_mod(g, q, f, K) h = dmp_gcd(f, dmp_sub(g, x, 0, K), 0, K) if not dmp_one_p(h, 0, K): factors.append((h, i)) f = dmp_quo(f, h, 0, K) g = dmp_rem(g, f, 0, K) if not dmp_one_p(f, 0, K): factors += [(f, dmp_degree_in(f, 0, 0))] return factors def dup_gf_edf_zassenhaus(f, n, K): """ Cantor-Zassenhaus: Probabilistic Equal Degree Factorization. Given a monic square-free polynomial ``f`` in ``GF(q)[x]`` and an integer ``n``, such that ``n`` divides ``deg(f)``, returns all irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``. EDF procedure gives complete factorization over Galois fields. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**3 + x**2 + x + 1) >>> dup_gf_edf_zassenhaus(f, 1, R.domain) [[1 mod 5, 1 mod 5], [1 mod 5, 2 mod 5], [1 mod 5, 3 mod 5]] References ========== * :cite:`Geddes1992algorithms`, algorithm 8.9 See Also ======== dup_gf_ddf_zassenhaus """ factors = [f] if dmp_degree_in(f, 0, 0) <= n: return factors p, q = K.characteristic, K.order N = dmp_degree_in(f, 0, 0) // n while len(factors) < N: r = dup_gf_random(2*n - 1, K) if p == 2: h = r for i in range(1, n): r = dup_gf_pow_mod(r, q, f, K) h = dmp_add(h, r, 0, K) else: h = dup_gf_pow_mod(r, (q**n - 1) // 2, f, K) h = dmp_add_term(h, -K.one, 0, 0, K) g = dmp_gcd(f, h, 0, K) if not dmp_one_p(g, 0, K) and g != f: factors = (dup_gf_edf_zassenhaus(g, n, K) + dup_gf_edf_zassenhaus(dmp_quo(f, g, 0, K), n, K)) return _sort_factors(factors, multiple=False) def dup_gf_ddf_shoup(f, K): """ Kaltofen-Shoup: Deterministic Distinct Degree Factorization. Given a monic square-free polynomial ``f`` in ``GF(q)[x]``, computes partial distinct degree factorization ``f_1 ... f_d`` of ``f`` where ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0`` is an argument to the equal degree factorization routine. Notes ===== This algorithm is an improved version of Zassenhaus algorithm for large ``deg(f)`` and order ``q`` (especially for ``deg(f) ~ lg(q)``). Examples ======== >>> R, x = ring('x', FF(3)) >>> f = R.to_dense(x**6 - x**5 + x**4 + x**3 - x) >>> dup_gf_ddf_shoup(f, R.domain) [([1 mod 3, 1 mod 3, 0 mod 3], 1), ([1 mod 3, 1 mod 3, 0 mod 3, 1 mod 3, 2 mod 3], 2)] References ========== * :cite:`Kaltofen1998subquadratic`, algorithm D * :cite:`Shoup1995factor` * :cite:`Gathen1992frobenious` See Also ======== dup_gf_edf_shoup """ n, q = dmp_degree_in(f, 0, 0), K.order k = math.ceil(math.sqrt(n//2)) x = [K.one, K.zero] h = dup_gf_pow_mod(x, q, f, K) # U[i] = x**(q**i) U = [x, h] + [K.zero]*(k - 1) for i in range(2, k + 1): U[i] = dup_gf_compose_mod(U[i - 1], h, f, K) h, U = U[k], U[:k] # V[i] = x**(q**(k*(i+1))) V = [h] + [K.zero]*(k - 1) for i in range(1, k): V[i] = dup_gf_compose_mod(V[i - 1], h, f, K) factors = [] for i, v in enumerate(V): h, j = [K.one], k - 1 for u in U: g = dmp_sub(v, u, 0, K) h = dmp_mul(h, g, 0, K) h = dmp_rem(h, f, 0, K) g = dmp_gcd(f, h, 0, K) f = dmp_quo(f, g, 0, K) for u in reversed(U): h = dmp_sub(v, u, 0, K) F = dmp_gcd(g, h, 0, K) if not dmp_one_p(F, 0, K): factors.append((F, k*(i + 1) - j)) g, j = dmp_quo(g, F, 0, K), j - 1 if not dmp_one_p(f, 0, K): factors.append((f, dmp_degree_in(f, 0, 0))) return factors def dup_gf_edf_shoup(f, n, K): """ Gathen-Shoup: Probabilistic Equal Degree Factorization. Given a monic square-free polynomial ``f`` in ``GF(q)[x]`` and an integer ``n``, such that ``n`` divides ``deg(f)``, returns all irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``. EDF procedure gives complete factorization over Galois fields. Notes ===== This algorithm is an improved version of Zassenhaus algorithm for large ``deg(f)`` and order ``q`` (especially for ``deg(f) ~ lg(q)``). Examples ======== >>> R, x = ring('x', FF(2917)) >>> f = R.to_dense(x**2 + 2837*x + 2277) >>> dup_gf_edf_shoup(f, 1, R.domain) [[1 mod 2917, 852 mod 2917], [1 mod 2917, 1985 mod 2917]] References ========== * :cite:`Shoup1991ffactor` * :cite:`Gathen1992ComputingFM`, algorithm 3.6 See Also ======== dup_gf_ddf_shoup """ q, p = K.order, K.characteristic N = dmp_degree_in(f, 0, 0) if not N: return [] if N <= n: return [f] factors, x = [f], [K.one, K.zero] r = dup_gf_random(N - 1, K) h = dup_gf_pow_mod(x, q, f, K) H = dup_gf_trace_map(r, h, x, n - 1, f, K)[1] if p == 2: h1 = dmp_gcd(f, H, 0, K) h2 = dmp_quo(f, h1, 0, K) factors = dup_gf_edf_shoup(h1, n, K) + dup_gf_edf_shoup(h2, n, K) else: h = dup_gf_pow_mod(H, (q - 1)//2, f, K) h1 = dmp_gcd(f, h, 0, K) h2 = dmp_gcd(f, dmp_add_term(h, -K.one, 0, 0, K), 0, K) h3 = dmp_quo(f, dmp_mul(h1, h2, 0, K), 0, K) factors = (dup_gf_edf_shoup(h1, n, K) + dup_gf_edf_shoup(h2, n, K) + dup_gf_edf_shoup(h3, n, K)) return _sort_factors(factors, multiple=False) def dup_gf_zassenhaus(f, K): """ Factor a square-free polynomial over finite fields of medium order. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**2 + 4*x + 3) >>> dup_gf_zassenhaus(f, R.domain) [[1 mod 5, 1 mod 5], [1 mod 5, 3 mod 5]] """ factors = [] for factor, n in dup_gf_ddf_zassenhaus(f, K): factors += dup_gf_edf_zassenhaus(factor, n, K) return _sort_factors(factors, multiple=False) def dup_gf_shoup(f, K): """ Factor a square-free polynomial over finite fields of large order. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**2 + 4*x + 3) >>> dup_gf_shoup(f, R.domain) [[1 mod 5, 1 mod 5], [1 mod 5, 3 mod 5]] """ factors = [] for factor, n in dup_gf_ddf_shoup(f, K): factors += dup_gf_edf_shoup(factor, n, K) return _sort_factors(factors, multiple=False) _factor_methods = { 'berlekamp': dup_gf_berlekamp, # ``p`` : small 'zassenhaus': dup_gf_zassenhaus, # ``p`` : medium 'shoup': dup_gf_shoup, # ``p`` : large } def dup_gf_factor_sqf(f, K): """ Factor a square-free polynomial ``f`` in ``GF(q)[x]``. Returns its complete factorization into irreducibles:: f_1(x) f_2(x) ... f_d(x) where each ``f_i`` is a monic polynomial and ``gcd(f_i, f_j) == 1``, for ``i != j``. The result is given as a list of factors of ``f``. Square-free factors of ``f`` can be factored into irreducibles over finite fields using three very different methods: Berlekamp efficient for very small values of order ``q`` (usually ``q < 25``) Cantor-Zassenhaus efficient on average input and with "typical" ``q`` Shoup-Kaltofen-Gathen efficient with very large inputs and order If you want to use a specific factorization method - set ``GF_FACTOR_METHOD`` configuration option with one of ``"berlekamp"``, ``"zassenhaus"`` or ``"shoup"`` values. Examples ======== >>> R, x = ring('x', FF(5)) >>> f = R.to_dense(x**2 + 4*x + 3) >>> dup_gf_factor_sqf(f, R.domain) [[1 mod 5, 1 mod 5], [1 mod 5, 3 mod 5]] References ========== * :cite:`Gathen1999modern`, chapter 14 """ method = query('GF_FACTOR_METHOD') return _factor_methods[method](f, K)
World War Z is a cooperative shooter designed for 4-player cooperation based on the license of a movie by the same title. The game was developed by Saber Interactive, also known for creating such games as TimeShift, Inversion and God Mode. World War Z takes players to a world overrun by a zombie pandemic. Players take control over characters, whose primary objective is to fight for survival. The game features indirect references to the movie, however, seeing the move is not necessary to understand the story shown in the game. In World War Z, players observe the action from the third-person perspective (TPP). The game comprises of three main chapters taking place in New York, Moscow, and Jerusalem. In each location, players control 4 characters with different abilities. As players progress through the game, they earn experience and unlock new levels that give them new abilities. Similarly to the Left 4 Dead series, players have to traverse different locations, complete objectives, and eliminate hordes of living dead. A single horde can comprise even hundreds of zombies moving with extraordinary speed and able to climb each other getting to seemingly safe, high places. Developers give at players' disposal an elaborate selection of firearms (that can be modified). Players can also fortify themselves – in selected areas, one can build a barbed fence, deploy mines and HMG positions. World War Z is based on the proprietary Swarm Engine that facilitates high-quality visuals despite hundreds of opponents present on the screen.
#Classes for MazingGame. # # The MIT License (MIT) # Copyright (c) 2015, 2016 Sami Salkosuo # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from mazepy import mazepy class Player: def __init__(self,name): self.name=name #row and column are location in maze grid self.row=0 self.column=0 self.startingRow=0 self.startingColumn=0 #screeenRow and screenColumn are location in screen self.screenRow=0 self.screenColumn=0 self.visitedCells=[] self.symbol="@" def addVisitedCell(self,cell): self.visitedCells.append(cell) def __str__(self): output="Name: %s. Maze position:[%d,%d]. Screen position: [%d,%d]" % (self.name,self.row,self.column,self.screenRow,self.screenColumn) return output class Goal: def __init__(self,row,column,screenRow,screenColumn): self.row=row self.column=column self.screenRow=screenRow self.screenColumn=screenColumn self.symbol="X" def __str__(self): output="Goal maze position: [%d,%d], screen position: [%d,%d]" % (self.row,self.column,self.screenRow,self.screenColumn) return output class MazingCell(mazepy.Cell): pass class GameGrid(mazepy.Grid): def contentsOf(self,cell): return cell.getContent()
About Us – The Tangible Effect Inc. That Small Business is the lifeblood of the Community providing jobs, services and creating infrastructure. Small Business Owners struggle with operating their businesses, often because they don’t know what they don’t know. Every Small Business Owner should have the opportunity to create the business of their dreams. A Small Business Owner can be the best leader for their business. Small Business Owners need support, encouragement, self-development, peers, a collaborative network, and truth. To empower business owners to utilize the right information at the right time for their business’s growth stage transforming their vision into reality. Helping business owners see their future and empowering them to achieve it.
import numpy as np from sklearn import svm from sklearn.datasets import fetch_20newsgroups from sklearn.svm import libsvm import sys from time import time from functools import wraps LIBSVM_IMPL = ['c_svc', 'nu_svc', 'one_class', 'epsilon_svr', 'nu_svr'] def caching(): """ Cache decorator. Arguments to the cached function must be hashable. """ def decorate_func(func): cache = dict() # separating positional and keyword args kwarg_point = object() @wraps(func) def cache_value(*args, **kwargs): key = args if kwargs: key += (kwarg_point,) + tuple(sorted(kwargs.items())) if key in cache: result = cache[key] else: result = func(*args, **kwargs) cache[key] = result return result def cache_clear(): """ Clear the cache """ cache.clear() # Clear the cache cache_value.cache_clear = cache_clear return cache_value return decorate_func class StringKernelSVM(svm.SVC): """ Implementation of string kernel from article: H. Lodhi, C. Saunders, J. Shawe-Taylor, N. Cristianini, and C. Watkins. Text classification using string kernels. Journal of Machine Learning Research, 2, 2002 . svm.SVC is a basic class from scikit-learn for SVM classification (in multiclass case, it uses one-vs-one approach) """ def __init__(self, subseq_length=3, lambda_decay=0.5): """ Constructor :param lambda_decay: lambda parameter for the algorithm :type lambda_decay: float :param subseq_length: maximal subsequence length :type subseq_length: int """ self.lambda_decay = lambda_decay self.subseq_length = subseq_length svm.SVC.__init__(self, kernel='precomputed') @caching() def _K(self, n, s, t): """ K_n(s,t) in the original article; recursive function :param n: length of subsequence :type n: int :param s: document #1 :type s: str :param t: document #2 :type t: str :return: float value for similarity between s and t """ if min(len(s), len(t)) < n: return 0 else: part_sum = 0 for j in range(1, len(t)): if t[j] == s[-1]: #not t[:j-1] as in the article but t[:j] because of Python slicing rules!!! part_sum += self._K1(n - 1, s[:-1], t[:j]) result = self._K(n, s[:-1], t) + self.lambda_decay ** 2 * part_sum return result @caching() def _K1(self, n, s, t): """ K'_n(s,t) in the original article; auxiliary intermediate function; recursive function :param n: length of subsequence :type n: int :param s: document #1 :type s: str :param t: document #2 :type t: str :return: intermediate float value """ if n == 0: return 1 elif min(len(s), len(t)) < n: return 0 else: part_sum = 0 for j in range(1, len(t)): if t[j] == s[-1]: #not t[:j-1] as in the article but t[:j] because of Python slicing rules!!! part_sum += self._K1(n - 1, s[:-1], t[:j]) * (self.lambda_decay ** (len(t) - (j + 1) + 2)) result = self.lambda_decay * self._K1(n, s[:-1], t) + part_sum return result def _gram_matrix_element(self, s, t, sdkvalue1, sdkvalue2): """ Helper function :param s: document #1 :type s: str :param t: document #2 :type t: str :param sdkvalue1: K(s,s) from the article :type sdkvalue1: float :param sdkvalue2: K(t,t) from the article :type sdkvalue2: float :return: value for the (i, j) element from Gram matrix """ if s == t: return 1 else: try: return self._K(self.subseq_length, s, t) / \ (sdkvalue1 * sdkvalue2) ** 0.5 except ZeroDivisionError: print("Maximal subsequence length is less or equal to documents' minimal length." "You should decrease it") sys.exit(2) def string_kernel(self, X1, X2): """ String Kernel computation :param X1: list of documents (m rows, 1 column); each row is a single document (string) :type X1: list :param X2: list of documents (m rows, 1 column); each row is a single document (string) :type X2: list :return: Gram matrix for the given parameters """ len_X1 = len(X1) len_X2 = len(X2) # numpy array of Gram matrix gram_matrix = np.zeros((len_X1, len_X2), dtype=np.float32) sim_docs_kernel_value = {} #when lists of documents are identical if X1 == X2: #store K(s,s) values in dictionary to avoid recalculations for i in range(len_X1): sim_docs_kernel_value[i] = self._K(self.subseq_length, X1[i], X1[i]) #calculate Gram matrix for i in range(len_X1): for j in range(i, len_X2): gram_matrix[i, j] = self._gram_matrix_element(X1[i], X2[j], sim_docs_kernel_value[i], sim_docs_kernel_value[j]) #using symmetry gram_matrix[j, i] = gram_matrix[i, j] #when lists of documents are not identical but of the same length elif len_X1 == len_X2: sim_docs_kernel_value[1] = {} sim_docs_kernel_value[2] = {} #store K(s,s) values in dictionary to avoid recalculations for i in range(len_X1): sim_docs_kernel_value[1][i] = self._K(self.subseq_length, X1[i], X1[i]) for i in range(len_X2): sim_docs_kernel_value[2][i] = self._K(self.subseq_length, X2[i], X2[i]) #calculate Gram matrix for i in range(len_X1): for j in range(i, len_X2): gram_matrix[i, j] = self._gram_matrix_element(X1[i], X2[j], sim_docs_kernel_value[1][i], sim_docs_kernel_value[2][j]) #using symmetry gram_matrix[j, i] = gram_matrix[i, j] #when lists of documents are neither identical nor of the same length else: sim_docs_kernel_value[1] = {} sim_docs_kernel_value[2] = {} min_dimens = min(len_X1, len_X2) #store K(s,s) values in dictionary to avoid recalculations for i in range(len_X1): sim_docs_kernel_value[1][i] = self._K(self.subseq_length, X1[i], X1[i]) for i in range(len_X2): sim_docs_kernel_value[2][i] = self._K(self.subseq_length, X2[i], X2[i]) #calculate Gram matrix for square part of rectangle matrix for i in range(min_dimens): for j in range(i, min_dimens): gram_matrix[i, j] = self._gram_matrix_element(X1[i], X2[j], sim_docs_kernel_value[1][i], sim_docs_kernel_value[2][j]) #using symmetry gram_matrix[j, i] = gram_matrix[i, j] #if more rows than columns if len_X1 > len_X2: for i in range(min_dimens, len_X1): for j in range(len_X2): gram_matrix[i, j] = self._gram_matrix_element(X1[i], X2[j], sim_docs_kernel_value[1][i], sim_docs_kernel_value[2][j]) #if more columns than rows else: for i in range(len_X1): for j in range(min_dimens, len_X2): gram_matrix[i, j] = self._gram_matrix_element(X1[i], X2[j], sim_docs_kernel_value[1][i], sim_docs_kernel_value[2][j]) print sim_docs_kernel_value return gram_matrix def fit(self, X, Y): gram_matr = self.string_kernel(X, X) self.__X = X super(svm.SVC, self).fit(gram_matr, Y) def predict(self, X): svm_type = LIBSVM_IMPL.index(self.impl) if not self.__X: print('You should train the model first!!!') sys.exit(3) else: gram_matr_predict_new = self.string_kernel(X, self.__X) gram_matr_predict_new = np.asarray(gram_matr_predict_new, dtype=np.float64, order='C') return libsvm.predict( gram_matr_predict_new, self.support_, self.support_vectors_, self.n_support_, self.dual_coef_, self._intercept_, self._label, self.probA_, self.probB_, svm_type=svm_type, kernel=self.kernel, C=self.C, nu=self.nu, probability=self.probability, degree=self.degree, shrinking=self.shrinking, tol=self.tol, cache_size=self.cache_size, coef0=self.coef0, gamma=self._gamma, epsilon=self.epsilon) if __name__ == '__main__': cur_f = __file__.split('/')[-1] if len(sys.argv) != 3: print >> sys.stderr, 'usage: ' + cur_f + ' <maximal subsequence length> <lambda (decay)>' sys.exit(1) else: subseq_length = int(sys.argv[1]) lambda_decay = float(sys.argv[2]) #The dataset is the 20 newsgroups dataset. It will be automatically downloaded, then cached. t_start = time() news = fetch_20newsgroups(subset='train') X_train = news.data[:10] Y_train = news.target[:10] print('Data fetched in %.3f seconds' % (time() - t_start)) clf = StringKernelSVM(subseq_length=subseq_length, lambda_decay=lambda_decay) t_start = time() clf.fit(X_train, Y_train) print('Model trained in %.3f seconds' % (time() - t_start)) t_start = time() result = clf.predict(news.data[10:14]) print('New data predicted in %.3f seconds' % (time() - t_start)) print result
ACUdraw Replacement Covers is rated 1.8 out of 5 by 4. Rated 3 out of 5 by Dillon from Works Well but Lacking Screw Stops I ordered a camo set to replace the original black covers that came with my Turbo XLT. Both sets have one big flaw - no screw stops. The screws cannot be tightened very much because they just keep going and press the tops of the covers in. A set of stand-offs from the hardware store solved the issue. Rated 1 out of 5 by Musky from ACUdraw Cover Screw Holes Although the ACUdraw system works much better than other systems I have used on crossbows I am disappointed in the plastic cover on the right side of my system. Both screw holes broke open in the cover so that the screws no longer can hold the right side of the cover in place. I believe a heavier plastic might solve the issue but for now I plan to use washers with my new replacement cover. Rated 1 out of 5 by Az80 from Acudraw Plastic Cover The cover is terrible, All of the screw slots have broken off and I have to replace the cover. I posted an earlier question about these covers and have seen many Customers have complained about the covers cracking. Seems to me that this issue should be addressed as $30 for 2 thin pieces of plastic is a lot. Typically the only reason the covers cracked is if they get over tightened. Will these coves work on my new Horton Legend Ultra lite? Do these come with attaching hardware? yes, they will fit and yes, the screws come with them. The AcuDraw covers no longer come in camouflage. Do you guys have upgraded covers? I'm on the second set now and need a 3rd. They keep cracking by the screws. Dealer installed both times. I truly think you need to re-engineer these covers. You mentioned they are a durable polymer, seem everyone I spoke with has this issue. Maybe standoffs would help? I haven't tested this plastic, but I think an ABS would better suit this need. Maybe a mixture with a little more butadine will give it the strength and flexibility it will need to withstand the vibration with out cracking. Just a thought from a process engineer in injection molding. Contact us directly and we should be able to help you. We do not have camo covers for the Acudraw. The covers are barely visible when the bow is at the resting position and when you shoulder it, it is hidden between your arm and your body, so it is not visible at all then. The covers typically do not crack unless the screw gets over tightened. Can these be purchased in a camo vs. black? We only stock them in black now. We have gone away from the camo covers.
from fabric.api import local, abort, env from fabric.contrib import django django.project('ohs_site') from django.conf import settings import os BUILD_DIR = settings.BUILD_DIR def setup(): local('cp ohs_site/offline/sample.env ohs_site/.env') local('nano ohs_site/.env') def build_site(): e = getattr(env, 'environment', None) if e == 'production': local("foreman run python manage.py build --skip-media --skip-static") else: local("python manage.py build") def build_extras(): if not os.path.exists(BUILD_DIR): os.makedirs(BUILD_DIR) local('cp ohs_site/extras/* %s' % BUILD_DIR) def build_blog(): pass # blog = settings.STATICBLOG_COMPILE_DIRECTORY # if not os.path.exists(blog): # os.makedirs(blog) # e = getattr(env, 'environment', None) # if e == 'production': # local("foreman run python manage.py update_blog --all") # else: # local("python manage.py update_blog") def build(): build_site() build_blog() build_extras() def deploy(): local('python manage.py collectstatic --noinput') env.environment = 'production' build() local('foreman run python manage.py collectstatic --noinput') local('ghp-import -p %s' % BUILD_DIR, capture=True) env.environment = None
…find some moss…and take a break at the swingset. On another morning outside you might even find an earthworm to study! Later in the week, on a sunny Saturday, we head to Mama Ann’s to explore the well worn paths. A whole carpet of moss! Back at home…then we ask the question – what is the difference between moss and lichen? And we pull out the microscope and look even closer for an answer. (Apologia Biology study for the older two. Sure love how nature study goes hand in hand with Apologia Biology). What fun to have brothers – nine years apart in age – with their heads together at the microscope!! And we’re amazed even more now that we’ve searched and we’ve found and we’ve studied. Now our eyes are open to moss and lichen everywhere. Maybe it’s because all the trees are just starting to bud and we can see it even better? Yes, and I sure like that we can study it all together. How about your homeschool – have you gotten outside to notice some signs of spring? Such beautiful images of your moss and lichen too! Moss plays such an important role in our gardens and fills in all those spaces in between the stones and rocks. I am beginning to appreciate that. Thanks for sharing with the OHC Carnival. I love all the energy and happiness in your nature study. I love using the microscope. I just love this post, especially the photo with your older son smiling by the microscope. Beautiful moment and a wonderful way to study God’s creation. What beautiful pictures! Thank you for sharing them with us. I need to starting looking more closely for some signs. I’m sure they are there, but I haven’t noticed them yet. Thanks for the encouragement. Have a great week! I love the picture of your oldest and youngest enjoying nature study together! And what a great idea to explore the differences between moss and lichen under the microscope. I too have 5 kids 9 years apart in age. While schooling a wide range of ages can have its challenges, nature study for our family is a delightful way to all get outside together and enjoy doing the same thing. Great to see the microscope out and multi age study. I find that we’re still looking at moss too–my husband is even sending me pictures of when he’s out and about. Thanks! I’ve spent the last 40 mins reading into your wonderfully full and blessed blog! I’ve only stumbled across it from Practical Pages, & am rapt by what you do, how you do it,& my favourite so far is the entire family all doing pastel chalk art at the table! I’ve been searching everywhere for a good microscope & noticed that you’re happy with the one you’re using ! Please tell me if I can order one as such online (is there a link?) as I live in Australia & would like feedback from another homeschooler. I value the opinion of an experienced person such as yourself. Thank you and God bless your homeschooling journey. And I do hope you will join us for some art!
# -*- coding: utf-8 -*- # Copyright 2010-present Basho Technologies, Inc. # # 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. import copy import os import sys import unittest from six import string_types, PY2, PY3 from time import sleep from riak import ConflictError, RiakError, ListError from riak import RiakClient, RiakBucket, BucketType from riak.resolver import default_resolver, last_written_resolver from riak.tests import RUN_KV, RUN_RESOLVE, PROTOCOL from riak.tests.base import IntegrationTestBase from riak.tests.comparison import Comparison try: import simplejson as json except ImportError: import json if PY2: import cPickle test_pickle_dumps = cPickle.dumps test_pickle_loads = cPickle.loads else: import pickle test_pickle_dumps = pickle.dumps test_pickle_loads = pickle.loads testrun_sibs_bucket = 'sibsbucket' testrun_props_bucket = 'propsbucket' def setUpModule(): if not RUN_KV: return c = IntegrationTestBase.create_client() c.bucket(testrun_sibs_bucket).allow_mult = True c.close() def tearDownModule(): if not RUN_KV: return c = IntegrationTestBase.create_client() c.bucket(testrun_sibs_bucket).clear_properties() c.bucket(testrun_props_bucket).clear_properties() c.close() class NotJsonSerializable(object): def __init__(self, *args, **kwargs): self.args = list(args) self.kwargs = kwargs def __eq__(self, other): if len(self.args) != len(other.args): return False if len(self.kwargs) != len(other.kwargs): return False for name, value in self.kwargs.items(): if other.kwargs[name] != value: return False value1_args = copy.copy(self.args) value2_args = copy.copy(other.args) value1_args.sort() value2_args.sort() for i in range(len(value1_args)): if value1_args[i] != value2_args[i]: return False return True class KVUnitTests(unittest.TestCase): def test_list_keys_exception(self): c = RiakClient() bt = BucketType(c, 'test') b = RiakBucket(c, 'test', bt) with self.assertRaises(ListError): b.get_keys() def test_stream_buckets_exception(self): c = RiakClient() with self.assertRaises(ListError): bs = [] for bl in c.stream_buckets(): bs.extend(bl) def test_stream_keys_exception(self): c = RiakClient() with self.assertRaises(ListError): ks = [] for kl in c.stream_keys('test'): ks.extend(kl) def test_ts_stream_keys_exception(self): c = RiakClient() with self.assertRaises(ListError): ks = [] for kl in c.ts_stream_keys('test'): ks.extend(kl) @unittest.skipUnless(RUN_KV, 'RUN_KV is 0') class BasicKVTests(IntegrationTestBase, unittest.TestCase, Comparison): def test_no_returnbody(self): bucket = self.client.bucket(self.bucket_name) o = bucket.new(self.key_name, "bar").store(return_body=False) self.assertEqual(o.vclock, None) @unittest.skipUnless(PROTOCOL == 'pbc', 'Only available on pbc') def test_get_no_returnbody(self): bucket = self.client.bucket(self.bucket_name) o = bucket.new(self.key_name, "Ain't no body") o.store() stored_object = bucket.get(self.key_name, head_only=True) self.assertFalse(stored_object.data) list_of_objects = bucket.multiget([self.key_name], head_only=True) for stored_object in list_of_objects: self.assertFalse(stored_object.data) def test_many_link_headers_should_work_fine(self): bucket = self.client.bucket(self.bucket_name) o = bucket.new("lots_of_links", "My god, it's full of links!") for i in range(0, 300): link = ("other", "key%d" % i, "next") o.add_link(link) o.store() stored_object = bucket.get("lots_of_links") self.assertEqual(len(stored_object.links), 300) def test_is_alive(self): self.assertTrue(self.client.is_alive()) def test_store_and_get(self): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = bucket.new('foo', rand) obj.store() obj = bucket.get('foo') self.assertTrue(obj.exists) self.assertEqual(obj.bucket.name, self.bucket_name) self.assertEqual(obj.key, 'foo') self.assertEqual(obj.data, rand) # unicode objects are fine, as long as they don't # contain any non-ASCII chars if PY2: self.client.bucket(unicode(self.bucket_name)) # noqa else: self.client.bucket(self.bucket_name) if PY2: self.assertRaises(TypeError, self.client.bucket, u'búcket') self.assertRaises(TypeError, self.client.bucket, 'búcket') else: self.client.bucket(u'búcket') self.client.bucket('búcket') bucket.get(u'foo') if PY2: self.assertRaises(TypeError, bucket.get, u'føø') self.assertRaises(TypeError, bucket.get, 'føø') self.assertRaises(TypeError, bucket.new, u'foo', 'éå') self.assertRaises(TypeError, bucket.new, u'foo', 'éå') self.assertRaises(TypeError, bucket.new, 'foo', u'éå') self.assertRaises(TypeError, bucket.new, 'foo', u'éå') else: bucket.get(u'føø') bucket.get('føø') bucket.new(u'foo', 'éå') bucket.new(u'foo', 'éå') bucket.new('foo', u'éå') bucket.new('foo', u'éå') obj2 = bucket.new('baz', rand, 'application/json') obj2.charset = 'UTF-8' obj2.store() obj2 = bucket.get('baz') self.assertEqual(obj2.data, rand) def test_store_obj_with_unicode(self): bucket = self.client.bucket(self.bucket_name) data = {u'føø': u'éå'} obj = bucket.new('foo', data) obj.store() obj = bucket.get('foo') self.assertEqual(obj.data, data) def test_store_unicode_string(self): bucket = self.client.bucket(self.bucket_name) data = u"some unicode data: \u00c6" obj = bucket.new(self.key_name, encoded_data=data.encode('utf-8'), content_type='text/plain') obj.charset = 'utf-8' obj.store() obj2 = bucket.get(self.key_name) self.assertEqual(data, obj2.encoded_data.decode('utf-8')) def test_string_bucket_name(self): # Things that are not strings cannot be bucket names for bad in (12345, True, None, {}, []): with self.assert_raises_regex(TypeError, 'must be a string'): self.client.bucket(bad) with self.assert_raises_regex(TypeError, 'must be a string'): RiakBucket(self.client, bad, None) # Unicode bucket names are not supported in Python 2.x, # if they can't be encoded to ASCII. This should be changed in a # future release. if PY2: with self.assert_raises_regex(TypeError, 'Unicode bucket names ' 'are not supported'): self.client.bucket(u'føø') else: self.client.bucket(u'føø') # This is fine, since it's already ASCII self.client.bucket('ASCII') def test_generate_key(self): # Ensure that Riak generates a random key when # the key passed to bucket.new() is None. bucket = self.client.bucket(self.bucket_name) o = bucket.new(None, data={}) self.assertIsNone(o.key) o.store() self.assertIsNotNone(o.key) self.assertNotIn('/', o.key) existing_keys = bucket.get_keys() self.assertEqual(len(existing_keys), 1) def maybe_store_keys(self): skey = 'rkb-init' bucket = self.client.bucket('random_key_bucket') sobj = bucket.get(skey) if sobj.exists: return for key in range(1, 1000): o = bucket.new(None, data={}) o.store() o = bucket.new(skey, data={}) o.store() def test_stream_keys(self): self.maybe_store_keys() bucket = self.client.bucket('random_key_bucket') regular_keys = bucket.get_keys() self.assertNotEqual(len(regular_keys), 0) streamed_keys = [] for keylist in bucket.stream_keys(): self.assertNotEqual([], keylist) for key in keylist: self.assertIsInstance(key, string_types) streamed_keys += keylist self.assertEqual(sorted(regular_keys), sorted(streamed_keys)) def test_stream_keys_timeout(self): self.maybe_store_keys() bucket = self.client.bucket('random_key_bucket') streamed_keys = [] with self.assertRaises(RiakError): for keylist in self.client.stream_keys(bucket, timeout=1): self.assertNotEqual([], keylist) for key in keylist: self.assertIsInstance(key, string_types) streamed_keys += keylist def test_stream_keys_abort(self): self.maybe_store_keys() bucket = self.client.bucket('random_key_bucket') regular_keys = bucket.get_keys() self.assertNotEqual(len(regular_keys), 0) try: for keylist in bucket.stream_keys(): raise RuntimeError("abort") except RuntimeError: pass # If the stream was closed correctly, this will not error robj = bucket.get(regular_keys[0]) self.assertEqual(len(robj.siblings), 1) self.assertEqual(True, robj.exists) def test_bad_key(self): bucket = self.client.bucket(self.bucket_name) obj = bucket.new() with self.assertRaises(TypeError): bucket.get(None) with self.assertRaises(TypeError): self.client.get(obj) with self.assertRaises(TypeError): bucket.get(1) def test_binary_store_and_get(self): bucket = self.client.bucket(self.bucket_name) # Store as binary, retrieve as binary, then compare... rand = str(self.randint()) if PY2: rand = bytes(rand) else: rand = bytes(rand, 'utf-8') obj = bucket.new(self.key_name, encoded_data=rand, content_type='text/plain') obj.store() obj = bucket.get(self.key_name) self.assertTrue(obj.exists) self.assertEqual(obj.encoded_data, rand) # Store as JSON, retrieve as binary, JSON-decode, then compare... data = [self.randint(), self.randint(), self.randint()] key2 = self.randname() obj = bucket.new(key2, data) obj.store() obj = bucket.get(key2) self.assertEqual(data, json.loads(obj.encoded_data.decode())) def test_blank_binary_204(self): bucket = self.client.bucket(self.bucket_name) # this should *not* raise an error empty = "" if PY2: empty = bytes(empty) else: empty = bytes(empty, 'utf-8') obj = bucket.new('foo2', encoded_data=empty, content_type='text/plain') obj.store() obj = bucket.get('foo2') self.assertTrue(obj.exists) self.assertEqual(obj.encoded_data, empty) def test_custom_bucket_encoder_decoder(self): bucket = self.client.bucket(self.bucket_name) # Teach the bucket how to pickle bucket.set_encoder('application/x-pickle', test_pickle_dumps) bucket.set_decoder('application/x-pickle', test_pickle_loads) data = {'array': [1, 2, 3], 'badforjson': NotJsonSerializable(1, 3)} obj = bucket.new(self.key_name, data, 'application/x-pickle') obj.store() obj2 = bucket.get(self.key_name) self.assertEqual(data, obj2.data) def test_custom_client_encoder_decoder(self): bucket = self.client.bucket(self.bucket_name) # Teach the client how to pickle self.client.set_encoder('application/x-pickle', test_pickle_dumps) self.client.set_decoder('application/x-pickle', test_pickle_loads) data = {'array': [1, 2, 3], 'badforjson': NotJsonSerializable(1, 3)} obj = bucket.new(self.key_name, data, 'application/x-pickle') obj.store() obj2 = bucket.get(self.key_name) self.assertEqual(data, obj2.data) def test_unknown_content_type_encoder_decoder(self): # Bypass the content_type encoders bucket = self.client.bucket(self.bucket_name) data = "some funny data" if PY3: # Python 3.x needs to store binaries data = data.encode() obj = bucket.new(self.key_name, encoded_data=data, content_type='application/x-frobnicator') obj.store() obj2 = bucket.get(self.key_name) self.assertEqual(data, obj2.encoded_data) def test_text_plain_encoder_decoder(self): bucket = self.client.bucket(self.bucket_name) data = "some funny data" obj = bucket.new(self.key_name, data, content_type='text/plain') obj.store() obj2 = bucket.get(self.key_name) self.assertEqual(data, obj2.data) def test_missing_object(self): bucket = self.client.bucket(self.bucket_name) obj = bucket.get(self.key_name) self.assertFalse(obj.exists) # Object with no siblings should not raise the ConflictError self.assertIsNone(obj.data) def test_delete(self): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = bucket.new(self.key_name, rand) obj.store() obj = bucket.get(self.key_name) self.assertTrue(obj.exists) obj.delete() obj.reload() self.assertFalse(obj.exists) def test_bucket_delete(self): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = bucket.new(self.key_name, rand) obj.store() bucket.delete(self.key_name) obj.reload() self.assertFalse(obj.exists) def test_set_bucket_properties(self): bucket = self.client.bucket(testrun_props_bucket) # Test setting allow mult... bucket.allow_mult = True # Test setting nval... bucket.n_val = 1 c2 = self.create_client() bucket2 = c2.bucket(testrun_props_bucket) self.assertTrue(bucket2.allow_mult) self.assertEqual(bucket2.n_val, 1) # Test setting multiple properties... bucket.set_properties({"allow_mult": False, "n_val": 2}) c3 = self.create_client() bucket3 = c3.bucket(testrun_props_bucket) self.assertFalse(bucket3.allow_mult) self.assertEqual(bucket3.n_val, 2) # clean up! c2.close() c3.close() def test_if_none_match(self): bucket = self.client.bucket(self.bucket_name) obj = bucket.get(self.key_name) obj.delete() obj.reload() self.assertFalse(obj.exists) obj.data = ["first store"] obj.content_type = 'application/json' obj.store() obj.data = ["second store"] with self.assertRaises(Exception): obj.store(if_none_match=True) def test_siblings(self): # Set up the bucket, clear any existing object... bucket = self.client.bucket(testrun_sibs_bucket) obj = bucket.get(self.key_name) bucket.allow_mult = True # Even if it previously existed, let's store a base resolved version # from which we can diverge by sending a stale vclock. obj.data = 'start' obj.content_type = 'text/plain' obj.store() vals = set(self.generate_siblings(obj, count=5)) # Make sure the object has five siblings... obj = bucket.get(self.key_name) self.assertEqual(len(obj.siblings), 5) # When the object is in conflict, using the shortcut methods # should raise the ConflictError with self.assertRaises(ConflictError): obj.data # Get each of the values - make sure they match what was # assigned vals2 = set([sibling.data for sibling in obj.siblings]) self.assertEqual(vals, vals2) # Resolve the conflict, and then do a get... resolved_sibling = obj.siblings[3] obj.siblings = [resolved_sibling] self.assertEqual(len(obj.siblings), 1) obj.store() self.assertEqual(len(obj.siblings), 1) self.assertEqual(obj.data, resolved_sibling.data) @unittest.skipUnless(RUN_RESOLVE, "RUN_RESOLVE is 0") def test_resolution(self): bucket = self.client.bucket(testrun_sibs_bucket) obj = bucket.get(self.key_name) bucket.allow_mult = True # Even if it previously existed, let's store a base resolved version # from which we can diverge by sending a stale vclock. obj.data = 'start' obj.content_type = 'text/plain' obj.store() vals = self.generate_siblings(obj, count=5, delay=1.01) # Make sure the object has five siblings when using the # default resolver obj = bucket.get(self.key_name) obj.reload() self.assertEqual(len(obj.siblings), 5) # Setting the resolver on the client object to use the # "last-write-wins" behavior self.client.resolver = last_written_resolver obj.reload() self.assertEqual(obj.resolver, last_written_resolver) self.assertEqual(1, len(obj.siblings)) self.assertEqual(obj.data, vals[-1]) # Set the resolver on the bucket to the default resolver, # overriding the resolver on the client bucket.resolver = default_resolver obj.reload() self.assertEqual(obj.resolver, default_resolver) self.assertEqual(len(obj.siblings), 5) # Define our own custom resolver on the object that returns # the maximum value, overriding the bucket and client resolvers def max_value_resolver(obj): obj.siblings = [max(obj.siblings, key=lambda s: s.data), ] obj.resolver = max_value_resolver obj.reload() self.assertEqual(obj.resolver, max_value_resolver) self.assertEqual(obj.data, max(vals)) # Setting the resolver to None on all levels reverts to the # default resolver. obj.resolver = None self.assertEqual(obj.resolver, default_resolver) # set by bucket bucket.resolver = None self.assertEqual(obj.resolver, last_written_resolver) # set by client self.client.resolver = None self.assertEqual(obj.resolver, default_resolver) # reset self.assertEqual(bucket.resolver, default_resolver) # reset self.assertEqual(self.client.resolver, default_resolver) # reset @unittest.skipUnless(RUN_RESOLVE, "RUN_RESOLVE is 0") def test_resolution_default(self): # If no resolver is setup, be sure to resolve to default_resolver bucket = self.client.bucket(testrun_sibs_bucket) self.assertEqual(self.client.resolver, default_resolver) self.assertEqual(bucket.resolver, default_resolver) def test_tombstone_siblings(self): # Set up the bucket, clear any existing object... bucket = self.client.bucket(testrun_sibs_bucket) obj = bucket.get(self.key_name) bucket.allow_mult = True obj.data = 'start' obj.content_type = 'text/plain' obj.store(return_body=True) obj.delete() vals = set(self.generate_siblings(obj, count=4)) obj = bucket.get(self.key_name) # TODO this used to be 5, only siblen = len(obj.siblings) self.assertTrue(siblen == 4 or siblen == 5) non_tombstones = 0 for sib in obj.siblings: if sib.exists: non_tombstones += 1 self.assertTrue(not sib.exists or sib.data in vals) self.assertEqual(non_tombstones, 4) def test_store_of_missing_object(self): bucket = self.client.bucket(self.bucket_name) # for json objects o = bucket.get(self.key_name) self.assertEqual(o.exists, False) o.data = {"foo": "bar"} o.content_type = 'application/json' o = o.store() self.assertEqual(o.data, {"foo": "bar"}) self.assertEqual(o.content_type, "application/json") o.delete() # for binary objects o = bucket.get(self.randname()) self.assertEqual(o.exists, False) if PY2: o.encoded_data = "1234567890" else: o.encoded_data = "1234567890".encode() o.content_type = 'application/octet-stream' o = o.store() if PY2: self.assertEqual(o.encoded_data, "1234567890") else: self.assertEqual(o.encoded_data, "1234567890".encode()) self.assertEqual(o.content_type, "application/octet-stream") o.delete() def test_store_metadata(self): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = bucket.new(self.key_name, rand) obj.usermeta = {'custom': 'some metadata'} obj.store() obj = bucket.get(self.key_name) self.assertEqual('some metadata', obj.usermeta['custom']) def test_list_buckets(self): bucket = self.client.bucket(self.bucket_name) bucket.new("one", {"foo": "one", "bar": "red"}).store() buckets = self.client.get_buckets() self.assertTrue(self.bucket_name in [x.name for x in buckets]) def test_stream_buckets(self): bucket = self.client.bucket(self.bucket_name) bucket.new(self.key_name, data={"foo": "one", "bar": "baz"}).store() buckets = [] for bucket_list in self.client.stream_buckets(): buckets.extend(bucket_list) self.assertTrue(self.bucket_name in [x.name for x in buckets]) def test_stream_buckets_abort(self): bucket = self.client.bucket(self.bucket_name) bucket.new(self.key_name, data={"foo": "one", "bar": "baz"}).store() try: for bucket_list in self.client.stream_buckets(): raise RuntimeError("abort") except RuntimeError: pass robj = bucket.get(self.key_name) self.assertTrue(robj.exists) self.assertEqual(len(robj.siblings), 1) def test_get_params(self): bucket = self.client.bucket(self.bucket_name) bucket.new(self.key_name, data={"foo": "one", "bar": "baz"}).store() bucket.get(self.key_name, basic_quorum=False) bucket.get(self.key_name, basic_quorum=True) bucket.get(self.key_name, notfound_ok=True) bucket.get(self.key_name, notfound_ok=False) missing = bucket.get('missing-key', notfound_ok=True, basic_quorum=True) self.assertFalse(missing.exists) def test_preflist(self): nodes = ['riak@127.0.0.1', 'dev1@127.0.0.1'] bucket = self.client.bucket(self.bucket_name) bucket.new(self.key_name, data={"foo": "one", "bar": "baz"}).store() try: preflist = bucket.get_preflist(self.key_name) preflist2 = self.client.get_preflist(bucket, self.key_name) for pref in (preflist, preflist2): self.assertEqual(len(pref), 3) self.assertIn(pref[0]['node'], nodes) [self.assertTrue(node['primary']) for node in pref] except NotImplementedError as e: raise unittest.SkipTest(e) def generate_siblings(self, original, count=5, delay=None): vals = [] for _ in range(count): while True: randval = str(self.randint()) if randval not in vals: break other_obj = original.bucket.new(key=original.key, data=randval, content_type='text/plain') other_obj.vclock = original.vclock other_obj.store() vals.append(randval) if delay: sleep(delay) return vals @unittest.skipUnless(RUN_KV, 'RUN_KV is 0') class BucketPropsTest(IntegrationTestBase, unittest.TestCase): def test_rw_settings(self): bucket = self.client.bucket(testrun_props_bucket) self.assertEqual(bucket.r, "quorum") self.assertEqual(bucket.w, "quorum") self.assertEqual(bucket.dw, "quorum") self.assertEqual(bucket.rw, "quorum") bucket.w = 1 self.assertEqual(bucket.w, 1) bucket.r = "quorum" self.assertEqual(bucket.r, "quorum") bucket.dw = "all" self.assertEqual(bucket.dw, "all") bucket.rw = "one" self.assertEqual(bucket.rw, "one") bucket.set_properties({'w': 'quorum', 'r': 'quorum', 'dw': 'quorum', 'rw': 'quorum'}) bucket.clear_properties() def test_primary_quora(self): bucket = self.client.bucket(testrun_props_bucket) self.assertEqual(bucket.pr, 0) self.assertEqual(bucket.pw, 0) bucket.pr = 1 self.assertEqual(bucket.pr, 1) bucket.pw = "quorum" self.assertEqual(bucket.pw, "quorum") bucket.set_properties({'pr': 0, 'pw': 0}) bucket.clear_properties() def test_clear_bucket_properties(self): bucket = self.client.bucket(testrun_props_bucket) bucket.allow_mult = True self.assertTrue(bucket.allow_mult) bucket.n_val = 1 self.assertEqual(bucket.n_val, 1) # Test setting clearing properties... self.assertTrue(bucket.clear_properties()) self.assertFalse(bucket.allow_mult) self.assertEqual(bucket.n_val, 3) @unittest.skipUnless(RUN_KV, 'RUN_KV is 0') class KVFileTests(IntegrationTestBase, unittest.TestCase): def test_store_binary_object_from_file(self): bucket = self.client.bucket(self.bucket_name) obj = bucket.new_from_file(self.key_name, __file__) obj.store() obj = bucket.get(self.key_name) self.assertNotEqual(obj.encoded_data, None) is_win32 = sys.platform == 'win32' self.assertTrue(obj.content_type == 'text/x-python' or (is_win32 and obj.content_type == 'text/plain') or obj.content_type == 'application/x-python-code') def test_store_binary_object_from_file_should_use_default_mimetype(self): bucket = self.client.bucket(self.bucket_name) filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, 'README.md') obj = bucket.new_from_file(self.key_name, filepath) obj.store() obj = bucket.get(self.key_name) self.assertEqual(obj.content_type, 'application/octet-stream') def test_store_binary_object_from_file_should_fail_if_file_not_found(self): bucket = self.client.bucket(self.bucket_name) with self.assertRaises(IOError): bucket.new_from_file(self.key_name, 'FILE_NOT_FOUND') obj = bucket.get(self.key_name) # self.assertEqual(obj.encoded_data, None) self.assertFalse(obj.exists) @unittest.skipUnless(RUN_KV, 'RUN_KV is 0') class CounterTests(IntegrationTestBase, unittest.TestCase): def test_counter_requires_allow_mult(self): bucket = self.client.bucket(self.bucket_name) if bucket.allow_mult: bucket.allow_mult = False self.assertFalse(bucket.allow_mult) with self.assertRaises(Exception): bucket.update_counter(self.key_name, 10) def test_counter_ops(self): bucket = self.client.bucket(testrun_sibs_bucket) self.assertTrue(bucket.allow_mult) # Non-existent counter has no value self.assertEqual(None, bucket.get_counter(self.key_name)) # Update the counter bucket.update_counter(self.key_name, 10) self.assertEqual(10, bucket.get_counter(self.key_name)) # Update with returning the value self.assertEqual(15, bucket.update_counter(self.key_name, 5, returnvalue=True)) # Now try decrementing self.assertEqual(10, bucket.update_counter(self.key_name, -5, returnvalue=True))
Plug your XT90 equipped ARRMA ECS into any Deans plug equipped battery pack. Plug and play wireless solution. Also makes a great charging adapter too. Compact no wires low resistance adapter. XT90 end female and EC5 end male. Perfect for your ARRMA monster trucks!
import requests import json import sys import os import tarfile import shutil from MotionPicture import * import imp import argparse import getpass parser = argparse.ArgumentParser(description="Render MotionPicture video segment from remote.") parser.add_argument("--booking", nargs="?", default="-1", type=int, help="Number of booking in one attempt") parser.add_argument("--addr", required=True, dest="base_url", help="URL of rendering server") parser.add_argument("--user", required=True, help="Username to login to server") parser.add_argument("--project", required=True, help="Project name") parser.add_argument("--workspace", required=True, help="Local directory to save project data") parser.add_argument("--process", nargs="?", default=1, type=int, help="Number of process to spawn") args = parser.parse_args() username = args.user passwd = getpass.getpass("[{0}]'s password:".format(args.user)) base_url = args.base_url project_name = args.project workbase_path = args.workspace process_count = args.process booking_per_call = args.booking def write_json_to_file(filepath, data): f = open(filepath, "w") json.dump(data, f) f.close() def write_segment_status(segments_folder, segment): segment_folder = os.path.join(segments_folder, u"{0:04}".format(segment["id"])) if not os.path.exists(segment_folder): os.makedirs(segment_folder) status_file = os.path.join(segment_folder, "status.txt") write_json_to_file(status_file, active_segment) mp_url = base_url + "/mp" project_url = mp_url + "/project/" + project_name s = requests.session() login_data = { "username": username, "password": passwd } r=s.post(mp_url+'/login', login_data) jr = json.loads(r.text) if jr["result"] == "success": print("Fetching information about project [{0}]".format(project_name)) r=s.get(project_url+'/info') project = json.loads(r.text) if project.get("id"): extras = project["extras"] local_project_path = os.path.join(workbase_path, u"{0}".format(project_name)) if not os.path.exists(local_project_path): os.makedirs(local_project_path) local_data_path = os.path.join(local_project_path, project["data_file_name"]) if not os.path.isfile(local_data_path): print("Downloading data-file of project [{0}]".format(project_name)) f = open(local_data_path, "wb") r = s.get(project_url+"/data_file", stream=True) total_size = int(r.headers.get("Content-Length")) downloaded_size = 0 for data in r.iter_content(chunk_size=4096): f.write(data) downloaded_size += len(data) percent = int(downloaded_size*100./total_size) sys.stdout.write("\rProgress: {0:>5}% (of {2:>10}/{1:<10} byte)".format( percent, total_size, downloaded_size)) f.close() print("\n") extracted_folder = local_data_path + u"_extracted" if not os.path.exists(extracted_folder): os.makedirs(extracted_folder) print("Extracting data-file of project [{0}]".format(project_name)) tar_ref = tarfile.open(local_data_path, "r") tar_ref.extractall(extracted_folder) segments_folder = os.path.join(local_project_path, u"segments") if not os.path.exists(segments_folder): os.makedirs(segments_folder) while True: active_segment = None for filename in sorted(os.listdir(segments_folder)): folder = os.path.join(segments_folder , filename) if not os.path.isdir(folder): continue status_file = os.path.join(folder, "status.txt") if not os.path.isfile(status_file): seg = dict() else: f = open(status_file, "r") seg = json.load(f) f.close() if seg.get("status") in ("Booked",): active_segment = seg break #Get new booking if not active_segment: bc = 0 while bc<booking_per_call or booking_per_call<0: print("Fetching next booking of project [{0}]".format(project_name)) r=s.get(project_url+'/book') booking = json.loads(r.text) if booking.get("id"): booking["status"] = "Booked" if not active_segment: active_segment = booking write_segment_status(segments_folder, booking) print("Segment id {0} is booked.".format(booking["id"])) bc += 1 else: break if booking_per_call<0: break if bc == 0: print("No booking can be made.") break if active_segment: segment_folder = os.path.join(segments_folder, u"{0:04}".format(active_segment["id"])) if not os.path.exists(segment_folder): os.makedirs(segment_folder) status_file = os.path.join(segment_folder, "status.txt") write_json_to_file(status_file, active_segment) temp_output_filename = os.path.join( segment_folder, "temp_video{0}".format(extras["file_ext"])) output_filename = os.path.join( segment_folder, "video{0}".format(extras["file_ext"])) #Make the movie if not os.path.isfile(output_filename): pre_script = extras.get("pre_script") if pre_script: pre_script_path = os.path.join(extracted_folder, pre_script) if os.path.isfile(pre_script_path): imp.load_source("pre_script", pre_script_path) print("Building segment id-{2}:{0}-{1}".format( active_segment["start_time"], active_segment["end_time"], active_segment["id"])) doc_filename = os.path.join(extracted_folder, project["main_filename"]) kwargs = dict( src_filename = doc_filename, dest_filename = temp_output_filename, time_line = project["time_line_name"], start_time = active_segment["start_time"], end_time = active_segment["end_time"], resolution = extras.get("resolution", "1280x720"), process_count=process_count ) extra_param_names = ["ffmpeg_params", "bit_rate", "codec", "fps"] for param_name in extra_param_names: if param_name in extras: kwargs[param_name] = extras[param_name] ThreeDShape.HQRender = True doc_movie = DocMovie(**kwargs) doc_movie.make() if os.path.isfile(temp_output_filename): shutil.move(temp_output_filename, output_filename) if os.path.isfile(output_filename): segment_url = project_url+"/segment/{0}".format(active_segment["id"]) #Upload print("Uploading segment id-{2}:{0}-{1}".format( active_segment["start_time"], active_segment["end_time"], active_segment["id"])) video_file = open(output_filename, "rb") r=s.post(segment_url+"/upload", files={"video": video_file}) response = json.loads(r.text) if response.get("result") == "success": active_segment["status"] = "Uploaded" write_json_to_file(status_file, active_segment) print("Segment id-{2}:{0}-{1} is uploaded.".format( active_segment["start_time"], active_segment["end_time"], active_segment["id"])) active_segment = None #end while else: print("No project with name [{0}] is found.".format(project_name))
By studying three layers of graphene — sheets of honeycomb-arrayed carbon atoms — stacked in a particular way, scientists at the U.S. Department of Energy’s Brookhaven National Laboratory have discovered a “little universe” populated by a new kind of “quasiparticles” — particle-like excitations of electric charge. Unlike massless photon-like quasiparticles in single-layer graphene, these new quasiparticles have mass, which depends on their energy (or velocity), and would become infinitely massive at rest. That accumulation of mass at low energies means this trilayer graphene system, if magnetized by incorporating it into a heterostructure with magnetic material, could potentially generate a much larger density of spin-polarized charge carriers than single-layer graphene — making it very attractive for a new class of devices based on controlling not just electric charge but also spin, commonly known as spintronics. “Our research shows that these very unusual quasiparticles, predicted by theory, actually exist in three-layer graphene, and that they govern properties such as how the material behaves in a magnetic field — a property that could be used to control graphene-based electronic devices,” said Brookhaven physicist Igor Zaliznyak, who led the research team. Their work measuring properties of tri-layer graphene as a first step toward engineering such devices was published online in Nature Physics . Graphene has been the subject of intense research since its discovery in 2004, in particular because of the unusual behavior of its electrons, which flow freely across flat, single-layer sheets of the substance. Stacking layers changes the way electrons flow: Stacking two layers, for example, provides a “tunable” break in the energy levels the electrons can occupy, thus giving scientists a way to turn the current on and off. That opens the possibility of incorporating the inexpensive substance into new types of electronics. With three layers, the situation gets more complicated, scientists have found, but also potentially more powerful. One important variable is the way the layers are stacked: In “ABA” systems, the carbon atoms making up the honeycomb rings are directly aligned in the top and bottom layers (A) while those in the middle layer (B) are offset; in “ABC” variants, the honeycombs in each stacked layer are offset, stepping upwards layer by layer like a staircase. So far, ABC stacking appears to give rise to more interesting behaviors — such as those that are the subject of the current study. For this study, the scientists created the tri-layer graphene at the Center for Functional Nanomaterials (CFN) at Brookhaven Lab, peeling it from graphite, the form of carbon found in pencil lead. They used microRaman microscopy to map the samples and identify those with three layers stacked in the ABC arrangement. Then they used the CFN’s nanolithography tools, including ion-beam milling, to shape the samples in a particular way so they could be connected to electrodes for measurements. At the National High Magnetic Field Laboratory (NHMFL) in Tallahassee, Florida, the scientists then studied the material’s electronic properties — specifically the effect of an external magnetic field on the transport of electronic charge as a function of charge carrier density, magnetic field strength, and temperature. “Ultimately, the success of this project relied on hard work and rare experimental prowess of talented young researchers with whom we engaged in these studies, in particular, Liyuan Zhang, who at the time was research associate at Brookhaven, and Yan Zhang, then a graduate student from Stony Brook University,” said Igor Zaliznyak. The measurements provide the first experimental evidence for the existence of a particular type of quasiparticle, or electronic excitation that acts like a particle and serves as a charge carrier in the tri-layer graphene system. These particular quasiparticles, which were predicted by theoretical studies, have ill-defined mass — that is, they behave as if they have a range of masses — and those masses diverge as the energy level decreases with quasiparticles becoming infinitely massive. Ordinarily such particles would be unstable and couldn’t exist due to interactions with virtual particle-hole pairs — similar to virtual pairs of oppositely charged electrons and positrons, which annihilate when they interact. But a property of the quasiparticles called chirality, which is related to a special flavor of spin in graphene sytems, keeps the quasiparticles from being destroyed by these interactions. So these exotic infinitively massive particles can exist. “These results provide experimental validation for the large body of recent theoretical work on graphene, and uncover new exciting possibilities for future studies aimed at using the exotic properties of these quasiparticles,” Zaliznyak said. For example, combining magnetic materials with tri-layer graphene could align the spins of the charge-carrier quasiparticles. “We believe that such graphene-magnet heterostructures with spin-polarized charge carriers could lead to real breakthroughs in the field of spintronics,” Zaliznyak said. Liyuan Zhang, Yan Zhang, Jorge Camacho, Maxim Khodas, Igor Zaliznyak, "The experimental observation of quantum Hall effect of l=3 chiral quasiparticles in trilayer graphene", Nature Physics, doi:10.1038/nphys2104 (Published online September 25, 2011). Abstract.
#!/usr/bin/python ################################################## # currentcostd.py # # # # @author Gareth John <gljohn@fedoraproject.org> # ################################################## import sys import time import logging import logging.handlers from daemon import Daemon from meter import Meter from parser import * class MeterDaemon(Daemon): def __init__(self, pid): self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.INFO) ##create a file handler handler = logging.FileHandler('/var/log/meterd.log') handler.setLevel(logging.INFO) ##create a logging format formatter = logging.Formatter('%(asctime)s - ' + '%(name)s - ' + '%(levelname)s - ' + '%(message)s') handler.setFormatter(formatter) ##add the handlers to the logger self.logger.addHandler(handler) self.logger.info('Logging started...') self.logger.info('Pid is:' + pid) super(MeterDaemon, self).__init__(pid) self.m = Meter('/dev/ttyUSB0', 57600, 8, 'mastermeter', 'watts', self.logger) def run(self): self.m.open() self.logger.debug('Meter open.') while 1: self.m.read() self.m.parse() self.m.submit() time.sleep(6) def stop(self): self.m.close() self.logger.debug('Meter close.') super(MeterDaemon, self).stop() if __name__ == "__main__": daemon = MeterDaemon('/tmp/meter-daemon.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print("Unknown command") sys.exit(2) sys.exit(0) else: print("usage: %s start|stop|restart" % sys.argv[0]) sys.exit(2)
subbubble.com» What an amazing vibe to be sharing with you party people!! What an amazing vibe to be sharing with you party people!! Here at Sub Bubble Records time is just right to witness a flow of powerful creative energy given to birth by a uniquely talented crew. With Groovedesign freshly become part of the team, we are on the ball and ready to progress with an energising plan for the time to come. Our aim is to communicate our visions, passion and emotions through new experimental soundscapes where hedges between genres aren’t clearly marked and cross contamination opens vast horizons yet to be admired…. Together we will explore the fringes between Progressive, Techno, Psy-Trance, Deep, Dark Tech, Minimal Techno and some crazy (trust me), absolutely crazy stuff!!!!! Our first release ‘Psyshe’ Volume 1 is scheduled for May 1th 2015. Open your heart to the Spirit of true Underground Psychedelic Festivals and let us take you on a special tour across electronic music: buckle up!!
# Copyright 2016 Pinterest, Inc. # # 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. # -*- coding: utf-8 -*- """Collection of all env related views """ from django.middleware.csrf import get_token from django.shortcuts import render, redirect from django.views.generic import View from django.template.loader import render_to_string from django.http import HttpResponse from django.contrib import messages from deploy_board.settings import IS_PINTEREST from django.conf import settings import agent_report import common import random import json from helpers import builds_helper, environs_helper, agents_helper, ratings_helper, deploys_helper, \ systems_helper, environ_hosts_helper, clusters_helper, tags_helper, groups_helper, schedules_helper import math from dateutil.parser import parse import calendar from deploy_board.webapp.agent_report import TOTAL_ALIVE_HOST_REPORT, TOTAL_HOST_REPORT, ALIVE_STAGE_HOST_REPORT, \ FAILED_HOST_REPORT, UNKNOWN_HOST_REPORT, PROVISION_HOST_REPORT from diff_match_patch import diff_match_patch import traceback import logging import os import datetime import time if IS_PINTEREST: from helpers import s3_helper, autoscaling_groups_helper, private_builds_helper ENV_COOKIE_NAME = 'teletraan.env.names' ENV_COOKIE_CAPACITY = 5 DEFAULT_TOTAL_PAGES = 7 DEFAULT_PAGE_SIZE = 30 BUILD_STAGE = "BUILD" DEFAULT_ROLLBACK_DEPLOY_NUM = 6 STATUS_COOKIE_NAME = 'sort-by-status' MODE_COOKIE_NAME = 'show-mode' log = logging.getLogger(__name__) class EnvListView(View): def get(self, request): index = int(request.GET.get('page_index', '1')) size = int(request.GET.get('page_size', DEFAULT_PAGE_SIZE)) names = environs_helper.get_all_env_names(request, index=index, size=size) envs_tag = tags_helper.get_latest_by_targe_id(request, 'TELETRAAN') return render(request, 'environs/envs_landing.html', { "names": names, "pageIndex": index, "pageSize": DEFAULT_PAGE_SIZE, "disablePrevious": index <= 1, "disableNext": len(names) < DEFAULT_PAGE_SIZE, "envs_tag": envs_tag, }) class OverrideItem(object): def __init__(self, key=None, root=None, override=None): self.key = key self.root = root self.override = override def get_all_stages2(envs, stage): stages = [] stageName = "stageName" env = None for temp in envs: if stage and stage == temp[stageName]: env = temp stages.append(temp[stageName]) stages.sort() if not env: stage = stages[0] for temp in envs: if temp[stageName] == stage: env = temp break return stages, env def _fetch_param_with_cookie(request, param_name, cookie_name, default): """Gets a parameter from the GET request, or from the cookie, or the default. """ saved_value = request.COOKIES.get(cookie_name, default) return request.GET.get(param_name, saved_value) def update_deploy_progress(request, name, stage): env = environs_helper.get_env_by_stage(request, name, stage) progress = deploys_helper.update_progress(request, name, stage) showMode = _fetch_param_with_cookie( request, 'showMode', MODE_COOKIE_NAME, 'complete') sortByStatus = _fetch_param_with_cookie( request, 'sortByStatus', STATUS_COOKIE_NAME, 'true') report = agent_report.gen_report(request, env, progress, sortByStatus=sortByStatus) report.showMode = showMode report.sortByStatus = sortByStatus html = render_to_string('deploys/deploy_progress.tmpl', { "report": report, "env": env, }) response = HttpResponse(html) # save preferences response.set_cookie(MODE_COOKIE_NAME, showMode) response.set_cookie(STATUS_COOKIE_NAME, sortByStatus) return response def removeEnvCookie(request, name): if ENV_COOKIE_NAME in request.COOKIES: cookie = request.COOKIES[ENV_COOKIE_NAME] saved_names = cookie.split(',') names = [] total = 0 for saved_name in saved_names: if total >= ENV_COOKIE_CAPACITY: break if not saved_name == name: names.append(saved_name) total += 1 return ','.join(names) else: return "" def genEnvCookie(request, name): if ENV_COOKIE_NAME in request.COOKIES: # keep 5 recent visited env cookie = request.COOKIES[ENV_COOKIE_NAME] saved_names = cookie.split(',') names = [name] total = 1 for saved_name in saved_names: if total >= ENV_COOKIE_CAPACITY: break if not saved_name == name: names.append(saved_name) total += 1 return ','.join(names) else: return name def getRecentEnvNames(request): if ENV_COOKIE_NAME in request.COOKIES: cookie = request.COOKIES[ENV_COOKIE_NAME] return cookie.split(',') else: return None def get_recent_envs(request): names = getRecentEnvNames(request) html = render_to_string('environs/simple_envs.tmpl', { "envNames": names, "isPinterest": IS_PINTEREST, }) return HttpResponse(html) def check_feedback_eligible(request, username): # Checks to see if a user should be asked for feedback or not. if username and ratings_helper.is_user_eligible(request, username) and IS_PINTEREST: num = random.randrange(0, 100) if num <= 10: return True return False class EnvLandingView(View): def get(self, request, name, stage=None): envs = environs_helper.get_all_env_stages(request, name) if len(envs) == 0: return redirect('/') stages, env = common.get_all_stages(envs, stage) env_promote = environs_helper.get_env_promotes_config(request, name, env['stageName']) stage = env['stageName'] username = request.teletraan_user_id.name request_feedback = check_feedback_eligible(request, username) groups = environs_helper.get_env_capacity(request, name, stage, capacity_type="GROUP") metrics = environs_helper.get_env_metrics_config(request, name, stage) alarms = environs_helper.get_env_alarms_config(request, name, stage) env_tag = tags_helper.get_latest_by_targe_id(request, env['id']) basic_cluster_info = None capacity_info = {'groups': groups} if IS_PINTEREST: basic_cluster_info = clusters_helper.get_cluster(request, env.get('clusterName')) capacity_info['cluster'] = basic_cluster_info if not env['deployId']: capacity_hosts = deploys_helper.get_missing_hosts(request, name, stage) provisioning_hosts = environ_hosts_helper.get_hosts(request, name, stage) if IS_PINTEREST: basic_cluster_info = clusters_helper.get_cluster(request, env.get('clusterName')) if basic_cluster_info and basic_cluster_info.get('capacity'): hosts_in_cluster = groups_helper.get_group_hosts(request, env.get('clusterName')) num_to_fake = basic_cluster_info.get('capacity') - len(hosts_in_cluster) for i in range(num_to_fake): faked_host = {} faked_host['hostName'] = 'UNKNOWN' faked_host['hostId'] = 'UNKNOWN' faked_host['state'] = 'PROVISIONED' provisioning_hosts.append(faked_host) response = render(request, 'environs/env_landing.html', { "envs": envs, "env": env, "env_promote": env_promote, "stages": stages, "metrics": metrics, "alarms": alarms, "request_feedback": request_feedback, "groups": groups, "capacity_hosts": capacity_hosts, "provisioning_hosts": provisioning_hosts, "basic_cluster_info": basic_cluster_info, "capacity_info": json.dumps(capacity_info), "env_tag": env_tag, "pinterest": IS_PINTEREST, "csrf_token": get_token(request), }) showMode = 'complete' sortByStatus = 'true' else: # Get deploy progress progress = deploys_helper.update_progress(request, name, stage) showMode = _fetch_param_with_cookie( request, 'showMode', MODE_COOKIE_NAME, 'complete') sortByStatus = _fetch_param_with_cookie( request, 'sortByStatus', STATUS_COOKIE_NAME, 'true') report = agent_report.gen_report(request, env, progress, sortByStatus=sortByStatus) report.showMode = showMode report.sortByStatus = sortByStatus response = render(request, 'environs/env_landing.html', { "envs": envs, "env": env, "env_promote": env_promote, "stages": stages, "report": report, "has_deploy": True, "metrics": metrics, "alarms": alarms, "request_feedback": request_feedback, "groups": groups, "basic_cluster_info": basic_cluster_info, "capacity_info": json.dumps(capacity_info), "env_tag": env_tag, "pinterest": IS_PINTEREST, }) # save preferences response.set_cookie(ENV_COOKIE_NAME, genEnvCookie(request, name)) response.set_cookie(MODE_COOKIE_NAME, showMode) response.set_cookie(STATUS_COOKIE_NAME, sortByStatus) return response def _compute_range(totalItems, thisPageIndex, totalItemsPerPage, totalPagesToShow): totalPages = int(math.ceil(float(totalItems) / totalItemsPerPage)) if totalItems <= 0: return range(0), 0, 0 halfPagesToShow = totalPagesToShow / 2 startPageIndex = thisPageIndex - halfPagesToShow if startPageIndex <= 0: startPageIndex = 1 endPageIndex = startPageIndex + totalPagesToShow if endPageIndex > totalPages: endPageIndex = totalPages + 1 prevPageIndex = thisPageIndex - 1 nextPageIndex = thisPageIndex + 1 if nextPageIndex > totalPages: nextPageIndex = 0 return range(startPageIndex, endPageIndex), prevPageIndex, nextPageIndex def _convert_time(date_str, time_str): # We use pacific time by default if not time_str: time_str = "00:00:00" datestr = "%s %s -08:00" % (date_str, time_str) dt = parse(datestr) return calendar.timegm(dt.utctimetuple()) * 1000 def _convert_2_timestamp(date_str): # We use pacific time by default dt = parse(date_str) return calendar.timegm(dt.utctimetuple()) * 1000 def _get_commit_info(request, commit, repo=None, branch='master'): # We try teletraan for commit info first, if not found, try backend builds = builds_helper.get_builds(request, commit=commit) if builds: build = builds[0] return build['repo'], build['branch'], build['commitDate'] if not repo: # Without repo, we can not call github api, return None log.error("Repo is expected when query based on commit which has no build") return None, None, None try: commit_info = builds_helper.get_commit(request, repo, commit) return repo, branch, commit_info['date'] except: log.error(traceback.format_exc()) return None, None, None def _gen_deploy_query_filter(request, from_date, from_time, to_date, to_time, size, reverse_date, operator, commit, repo, branch): filter = {} filter_text = "" query_string = "" bad_commit = False if commit: filter_text += "commit=%s, " % commit query_string += "commit=%s&" % commit if repo: filter_text += "repo=%s, " % repo query_string += "repo=%s&" % repo if branch: filter_text += "branch=%s, " % branch query_string += "branch=%s&" % branch repo, branch, commit_date = _get_commit_info(request, commit, repo, branch) if repo and branch and commit_date: filter['repo'] = repo filter['branch'] = branch filter['commit'] = commit filter['commitDate'] = commit_date else: bad_commit = True if from_date: if from_time: filter_text += "from=%sT%s, " % (from_date, from_time) query_string += "from_date=%s&from_time=%s&" % (from_date, from_time) else: filter_text += "from=%s, " % from_date query_string += "from_time=%s&" % from_time after = _convert_time(from_date, from_time) filter['after'] = after if to_date: if to_time: filter_text += "to=%sT%s, " % (to_date, to_time) query_string += "to_date=%s&to_time=%s&" % (to_date, to_time) else: filter_text += "to=%s, " % to_date query_string += "to_time=%s&" % to_time before = _convert_time(to_date, to_time) filter['before'] = before if reverse_date and reverse_date.lower() == "true": filter_text += "earliest deploy first, " filter['oldestFirst'] = True query_string += "reverse_date=true&" if operator: filter_text += "operator=%s, " % operator filter['operator'] = operator query_string += "operator=%s&" % operator if size != DEFAULT_PAGE_SIZE: filter_text += "page_size=%s, " % size query_string += "page_size=%s&" % size if filter_text: filter_title = "Filter (%s)" % filter_text[:-2] else: filter_title = "Filter" if bad_commit: return None, filter_title, query_string else: return filter, filter_title, query_string def _gen_deploy_summary(request, deploys, for_env=None): deploy_summaries = [] for deploy in deploys: if for_env: env = for_env else: env = environs_helper.get(request, deploy['envId']) build_with_tag = builds_helper.get_build_and_tag(request, deploy['buildId']) summary = {} summary['deploy'] = deploy summary['env'] = env summary['build'] = build_with_tag['build'] summary['buildTag'] = build_with_tag['tag'] deploy_summaries.append(summary) return deploy_summaries def get_all_deploys(request): index = int(request.GET.get('page_index', '1')) size = int(request.GET.get('page_size', DEFAULT_PAGE_SIZE)) from_date = request.GET.get('from_date') from_time = request.GET.get('from_time') to_date = request.GET.get('to_date') to_time = request.GET.get('to_time') commit = request.GET.get('commit') repo = request.GET.get('repo') branch = request.GET.get('branch') reverse_date = request.GET.get('reverse_date') operator = request.GET.get('operator') if not branch: branch = 'master' filter, filter_title, query_string = \ _gen_deploy_query_filter(request, from_date, from_time, to_date, to_time, size, reverse_date, operator, commit, repo, branch) if filter is None: # specified a bad commit return render(request, 'deploys/all_history.html', { "deploy_summaries": [], "filter_title": filter_title, "pageIndex": index, "pageSize": size, "from_date": from_date, "from_time": from_time, "to_date": to_date, "to_time": to_time, "commit": commit, "repo": repo, "branch": branch, "reverse_date": reverse_date, "operator": operator, 'pageRange': range(0), "prevPageIndex": 0, "nextPageIndex": 0, "query_string": query_string, }) filter['pageIndex'] = index filter['pageSize'] = size result = deploys_helper.get_all(request, **filter) deploy_summaries = _gen_deploy_summary(request, result['deploys']) page_range, prevPageIndex, nextPageIndex = _compute_range(result['total'], index, size, DEFAULT_TOTAL_PAGES) return render(request, 'deploys/all_history.html', { "deploy_summaries": deploy_summaries, "filter_title": filter_title, "pageIndex": index, "pageSize": size, "from_date": from_date, "from_time": from_time, "to_date": to_date, "to_time": to_time, "commit": commit, "repo": repo, "branch": branch, "reverse_date": reverse_date, "operator": operator, 'pageRange': page_range, "prevPageIndex": prevPageIndex, "nextPageIndex": nextPageIndex, "query_string": query_string, }) def get_env_deploys(request, name, stage): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) index = int(request.GET.get('page_index', '1')) size = int(request.GET.get('page_size', DEFAULT_PAGE_SIZE)) from_date = request.GET.get('from_date', None) from_time = request.GET.get('from_time', None) to_date = request.GET.get('to_date', None) to_time = request.GET.get('to_time', None) commit = request.GET.get('commit', None) repo = request.GET.get('repo', None) branch = request.GET.get('branch', None) reverse_date = request.GET.get('reverse_date', None) operator = request.GET.get('operator', None) filter, filter_title, query_string = \ _gen_deploy_query_filter(request, from_date, from_time, to_date, to_time, size, reverse_date, operator, commit, repo, branch) if filter is None: return render(request, 'environs/env_history.html', { "envs": envs, "env": env, "stages": stages, "deploy_summaries": [], "filter_title": filter_title, "pageIndex": index, "pageSize": size, "from_date": from_date, "from_time": from_time, "to_date": to_date, "to_time": to_time, "commit": commit, "repo": repo, "branch": branch, "reverse_date": reverse_date, "operator": operator, 'pageRange': range(0), "prevPageIndex": 0, "nextPageIndex": 0, "query_string": query_string, "pinterest": IS_PINTEREST }) filter['envId'] = [env['id']] filter['pageIndex'] = index filter['pageSize'] = size result = deploys_helper.get_all(request, **filter) deploy_summaries = _gen_deploy_summary(request, result['deploys'], for_env=env) page_range, prevPageIndex, nextPageIndex = _compute_range(result['total'], index, size, DEFAULT_TOTAL_PAGES) return render(request, 'environs/env_history.html', { "envs": envs, "env": env, "stages": stages, "deploy_summaries": deploy_summaries, "filter_title": filter_title, "pageIndex": index, "pageSize": size, "from_date": from_date, "from_time": from_time, "to_date": to_date, "to_time": to_time, "commit": commit, "repo": repo, "branch": branch, "reverse_date": reverse_date, "operator": operator, 'pageRange': page_range, "prevPageIndex": prevPageIndex, "nextPageIndex": nextPageIndex, "query_string": query_string, "pinterest": IS_PINTEREST }) def get_env_names(request): # TODO create a loop to get all names max_size = 10000 names = environs_helper.get_all_env_names(request, index=1, size=max_size) return HttpResponse(json.dumps(names), content_type="application/json") def search_envs(request, filter): max_size = 10000 names = environs_helper.get_all_env_names(request, name_filter=filter, index=1, size=max_size) if not names: return redirect('/envs/') if len(names) == 1: return redirect('/env/%s/' % names[0]) envs_tag = tags_helper.get_latest_by_targe_id(request, 'TELETRAAN') return render(request, 'environs/envs_landing.html', { "names": names, "pageIndex": 1, "pageSize": DEFAULT_PAGE_SIZE, "disablePrevious": True, "disableNext": True, "envs_tag": envs_tag, }) def post_create_env(request): # TODO how to validate envName data = request.POST env_name = data["env_name"] stage_name = data["stage_name"] clone_env_name = data.get("clone_env_name") clone_stage_name = data.get("clone_stage_name") description = data.get('description') if clone_env_name and clone_stage_name: common.clone_from_stage_name(request, env_name, stage_name, clone_env_name, clone_stage_name, description) else: data = {} data['envName'] = env_name data['stageName'] = stage_name data['description'] = description environs_helper.create_env(request, data) return redirect('/env/' + env_name + '/' + stage_name + '/config/') class EnvNewDeployView(View): def get(self, request, name, stage): env = environs_helper.get_env_by_stage(request, name, stage) env_promote = environs_helper.get_env_promotes_config(request, name, stage) current_build = None if 'deployId' in env and env['deployId']: deploy = deploys_helper.get(request, env['deployId']) current_build = builds_helper.get_build(request, deploy['buildId']) return render(request, 'deploys/new_deploy.html', { "env": env, "env_promote": env_promote, "buildName": env['buildName'], "current_build": current_build, "pageIndex": 1, "pageSize": common.DEFAULT_BUILD_SIZE, }) def post(self, request, name, stage): common.deploy(request, name, stage) if name == 'ngapp2-A' or name == 'ngapp2-B': return redirect("/env/ngapp2/deploy/?stage=2") return redirect('/env/%s/%s/deploy' % (name, stage)) def post_add_stage(request, name): # TODO how to validate stage name data = request.POST stage = data.get("stage") from_stage = data.get("from_stage") description = data.get("description") if from_stage: common.clone_from_stage_name(request, name, stage, name, from_stage, description) else: data = {} data['envName'] = name data['stageName'] = stage data['description'] = description environs_helper.create_env(request, data) return redirect('/env/' + name + '/' + stage + '/config/') def remove_stage(request, name, stage): # TODO so we need to make sure the capacity is empty??? environs_helper.delete_env(request, name, stage) envs = environs_helper.get_all_env_stages(request, name) response = redirect('/env/' + name) if len(envs) == 0: cookie_response = removeEnvCookie(request, name) if not cookie_response: response.delete_cookie(ENV_COOKIE_NAME) else: response.set_cookie(ENV_COOKIE_NAME, cookie_response) return response def get_builds(request, name, stage): env = environs_helper.get_env_by_stage(request, name, stage) env_promote = environs_helper.get_env_promotes_config(request, name, stage) show_lock = False if env_promote['type'] == 'AUTO' and env_promote['predStage'] and \ env_promote['predStage'] == environs_helper.BUILD_STAGE: show_lock = True if 'buildName' not in env and not env['buildName']: html = render_to_string('builds/simple_builds.tmpl', { "builds": [], "env": env, "show_lock": show_lock, }) return HttpResponse(html) current_publish_date = 0 if 'deployId' in env and env['deployId']: deploy = deploys_helper.get(request, env['deployId']) build = builds_helper.get_build(request, deploy['buildId']) current_publish_date = build['publishDate'] # return only the new builds index = int(request.GET.get('page_index', '1')) size = int(request.GET.get('page_size', common.DEFAULT_BUILD_SIZE)) builds = builds_helper.get_builds_and_tags(request, name=env['buildName'], pageIndex=index, pageSize=size) new_builds = [] for build in builds: if build['build']['publishDate'] > current_publish_date: new_builds.append(build) html = render_to_string('builds/simple_builds.tmpl', { "builds": new_builds, "current_publish_date": current_publish_date, "env": env, "show_lock": show_lock, }) return HttpResponse(html) def upload_private_build(request, name, stage): return private_builds_helper.handle_uploaded_build(request, request.FILES['file'], name, stage) def get_groups(request, name, stage): groups = common.get_env_groups(request, name, stage) html = render_to_string('groups/simple_groups.tmpl', { "groups": groups, }) return HttpResponse(html) def deploy_build(request, name, stage, build_id): env = environs_helper.get_env_by_stage(request, name, stage) current_build = None deploy_state = None if env.get('deployId'): current_deploy = deploys_helper.get(request, env['deployId']) current_build = builds_helper.get_build(request, current_deploy['buildId']) deploy_state = deploys_helper.get(request, env['deployId'])['state'] build = builds_helper.get_build_and_tag(request, build_id) builds = [build] scm_url = systems_helper.get_scm_url(request) html = render_to_string('deploys/deploy_build.html', { "env": env, "builds": builds, "current_build": current_build, "scm_url": scm_url, "buildName": env.get('buildName'), "branch": env.get('branch'), "csrf_token": get_token(request), "deployState": deploy_state, "overridePolicy": env.get('overridePolicy'), }) return HttpResponse(html) def deploy_commit(request, name, stage, commit): env = environs_helper.get_env_by_stage(request, name, stage) builds = builds_helper.get_builds_and_tags(request, commit=commit) current_build = None if env.get('deployId'): deploy = deploys_helper.get(request, env['deployId']) current_build = builds_helper.get_build(request, deploy['buildId']) scm_url = systems_helper.get_scm_url(request) html = render_to_string('deploys/deploy_build.html', { "env": env, "builds": builds, "current_build": current_build, "scm_url": scm_url, "buildName": env.get('buildName'), "branch": env.get('branch'), "csrf_token": get_token(request), }) return HttpResponse(html) def promote_to(request, name, stage, deploy_id): query_dict = request.POST toStages = query_dict['toStages'] description = query_dict['description'] toStage = None for toStage in toStages.split(','): deploys_helper.promote(request, name, toStage, deploy_id, description) return redirect('/env/%s/%s/deploy' % (name, toStage)) def restart(request, name, stage): common.restart(request, name, stage) return redirect('/env/%s/%s/deploy' % (name, stage)) def rollback_to(request, name, stage, deploy_id): common.rollback_to(request, name, stage, deploy_id) return redirect('/env/%s/%s/deploy' % (name, stage)) def rollback(request, name, stage): query_dict = request.GET to_deploy_id = query_dict.get('to_deploy_id', None) envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) result = deploys_helper.get_all(request, envId=[env['id']], pageIndex=1, pageSize=DEFAULT_ROLLBACK_DEPLOY_NUM) deploys = result.get("deploys") # remove the first deploy if exists if deploys: deploys.pop(0) # append the build info deploy_summaries = [] branch = None commit = None build_id = None for deploy in deploys: build_info = builds_helper.get_build_and_tag(request, deploy['buildId']) build = build_info["build"] tag = build_info.get("tag", None) summary = {} summary['deploy'] = deploy summary['build'] = build summary['tag'] = tag if not to_deploy_id and deploy['state'] == 'SUCCEEDED': to_deploy_id = deploy['id'] if to_deploy_id and to_deploy_id == deploy['id']: branch = build['branch'] commit = build['commitShort'] build_id = build['id'] deploy_summaries.append(summary) html = render_to_string("environs/env_rollback.html", { "envs": envs, "stages": stages, "envs": envs, "env": env, "deploy_summaries": deploy_summaries, "to_deploy_id": to_deploy_id, "branch": branch, "commit": commit, "build_id": build_id, "csrf_token": get_token(request), }) return HttpResponse(html) def get_deploy(request, name, stage, deploy_id): deploy = deploys_helper.get(request, deploy_id) build = builds_helper.get_build(request, deploy['buildId']) env = environs_helper.get_env_by_stage(request, name, stage) return render(request, 'environs/env_deploy_details.html', { "deploy": deploy, "csrf_token": get_token(request), "build": build, "env": env, }) def promote(request, name, stage, deploy_id): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) env_wrappers = [] for temp_env in envs: env_wrapper = {} env_wrapper["env"] = temp_env env_wrapper["env_promote"] = environs_helper.get_env_promotes_config(request, temp_env['envName'], temp_env['stageName']) env_wrappers.append(env_wrapper) deploy = deploys_helper.get(request, deploy_id) build = builds_helper.get_build(request, deploy['buildId']) html = render_to_string("environs/env_promote.html", { "envs": envs, "stages": stages, "envs": envs, "env": env, "env_wrappers": env_wrappers, "deploy": deploy, "build": build, "csrf_token": get_token(request), }) return HttpResponse(html) def pause(request, name, stage): deploys_helper.pause(request, name, stage) return redirect('/env/%s/%s/deploy' % (name, stage)) def resume(request, name, stage): deploys_helper.resume(request, name, stage) return redirect('/env/%s/%s/deploy' % (name, stage)) def enable_env_change(request, name, stage): params = request.POST description = params.get('description') environs_helper.enable_env_changes(request, name, stage, description) return redirect('/env/%s/%s/deploy' % (name, stage)) def disable_env_change(request, name, stage): params = request.POST description = params.get('description') environs_helper.disable_env_changes(request, name, stage, description) return redirect('/env/%s/%s/deploy' % (name, stage)) def enable_all_env_change(request): params = request.POST description = params.get('description') environs_helper.enable_all_env_changes(request, description) return redirect('/envs/') def disable_all_env_change(request): params = request.POST description = params.get('description') environs_helper.disable_all_env_changes(request, description) return redirect('/envs/') # get all reachable hosts def get_hosts(request, name, stage): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) agents = agents_helper.get_agents(request, env['envName'], env['stageName']) title = "All hosts" agents_wrapper = {} for agent in agents: if agent['deployId'] not in agents_wrapper: agents_wrapper[agent['deployId']] = [] agents_wrapper[agent['deployId']].append(agent) return render(request, 'environs/env_hosts.html', { "envs": envs, "env": env, "stages": stages, "agents_wrapper": agents_wrapper, "title": title, }) # get total alive hosts (hostStage == -1000) # get alive hosts by using deploy_id and its stage (hostStage = 0 ~ 8) def get_hosts_by_deploy(request, name, stage, deploy_id): hostStageString = request.GET.get('hostStage') if hostStageString is None: hostStage = TOTAL_ALIVE_HOST_REPORT else: hostStage = hostStageString envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) progress = deploys_helper.update_progress(request, name, stage) agents_wrapper = agent_report.gen_agent_by_deploy(progress, deploy_id, ALIVE_STAGE_HOST_REPORT, hostStage) title = "All hosts with deploy " + deploy_id return render(request, 'environs/env_hosts.html', { "envs": envs, "env": env, "stages": stages, "agents_wrapper": agents_wrapper, "title": title, }) # reset all failed hosts for this env, this deploy def reset_failed_hosts(request, name, stage, deploy_id): agents_helper.reset_failed_agents(request, name, stage, deploy_id) return HttpResponse(json.dumps({'html': ''}), content_type="application/json") # retry failed deploy stage for this env, this host def reset_deploy(request, name, stage, host_id): agents_helper.retry_deploy(request, name, stage, host_id) return HttpResponse(json.dumps({'html': ''}), content_type="application/json") # pause deploy for this this env, this host def pause_deploy(request, name, stage, host_id): agents_helper.pause_deploy(request, name, stage, host_id) return HttpResponse(json.dumps({'html': ''}), content_type="application/json") # resume deploy stage for this env, this host def resume_deploy(request, name, stage, host_id): agents_helper.resume_deploy(request, name, stage, host_id) return HttpResponse(json.dumps({'html': ''}), content_type="application/json") # pause hosts for this env and stage def pause_hosts(request, name, stage): post_params = request.POST host_ids = None if 'hostIds' in post_params: hosts_str = post_params['hostIds'] host_ids = [x.strip() for x in hosts_str.split(',')] environs_helper.pause_hosts(request, name, stage, host_ids) return redirect('/env/{}/{}/'.format(name, stage)) # resume hosts for this env and stage def resume_hosts(request, name, stage): post_params = request.POST host_ids = None if 'hostIds' in post_params: hosts_str = post_params['hostIds'] host_ids = [x.strip() for x in hosts_str.split(',')] environs_helper.resume_hosts(request, name, stage, host_ids) return redirect('/env/{}/{}/'.format(name, stage)) # reset hosts for this env and stage def reset_hosts(request, name, stage): post_params = request.POST host_ids = None if 'hostIds' in post_params: hosts_str = post_params['hostIds'] host_ids = [x.strip() for x in hosts_str.split(',')] environs_helper.reset_hosts(request, name, stage, host_ids) return redirect('/env/{}/{}/hosts'.format(name, stage)) # get total unknown(unreachable) hosts def get_unknown_hosts(request, name, stage): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) progress = deploys_helper.update_progress(request, name, stage) agents_wrapper = agent_report.gen_agent_by_deploy(progress, env['deployId'], UNKNOWN_HOST_REPORT) title = "Unknow hosts" return render(request, 'environs/env_hosts.html', { "envs": envs, "env": env, "stages": stages, "agents_wrapper": agents_wrapper, "title": title, }) # get provisioning hosts def get_provisioning_hosts(request, name, stage): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) progress = deploys_helper.update_progress(request, name, stage) agents_wrapper = agent_report.gen_agent_by_deploy(progress, env['deployId'], PROVISION_HOST_REPORT) title = "Provisioning hosts" return render(request, 'environs/env_hosts.html', { "envs": envs, "env": env, "stages": stages, "agents_wrapper": agents_wrapper, "title": title, }) # get total (unknown+alive) hosts def get_all_hosts(request, name, stage): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) progress = deploys_helper.update_progress(request, name, stage) agents_wrapper = agent_report.gen_agent_by_deploy(progress, env['deployId'], TOTAL_HOST_REPORT) title = "All hosts" return render(request, 'environs/env_hosts.html', { "envs": envs, "env": env, "stages": stages, "agents_wrapper": agents_wrapper, "title": title, }) # get failed (but alive) hosts (agent status > 0) def get_failed_hosts(request, name, stage): envs = environs_helper.get_all_env_stages(request, name) stages, env = common.get_all_stages(envs, stage) progress = deploys_helper.update_progress(request, name, stage) agents_wrapper = agent_report.gen_agent_by_deploy(progress, env['deployId'], FAILED_HOST_REPORT) failed_hosts = [agent['hostId'] for agent in agents_wrapper[env['deployId']]] host_ids = ",".join(failed_hosts) title = "Failed Hosts" return render(request, 'environs/env_hosts.html', { "envs": envs, "env": env, "stages": stages, "agents_wrapper": agents_wrapper, "title": title, "is_retryable": True, "host_ids": host_ids, "pinterest": IS_PINTEREST, }) def get_pred_deploys(request, name, stage): index = int(request.GET.get('page_index', '1')) size = int(request.GET.get('page_size', DEFAULT_PAGE_SIZE)) env = environs_helper.get_env_by_stage(request, name, stage) env_promote = environs_helper.get_env_promotes_config(request, name, stage) show_lock = False predStage = env_promote.get('predStage') if env_promote['type'] != "MANUAL" and predStage: show_lock = True current_startDate = 0 if not predStage or predStage == "BUILD": deploys = [] else: pred_env = environs_helper.get_env_by_stage(request, name, predStage) result = deploys_helper.get_all(request, envId=[pred_env['id']], pageIndex=index, pageSize=size) deploys = result["deploys"] if env.get('deployId'): deploy = deploys_helper.get(request, env['deployId']) build = builds_helper.get_build(request, deploy['buildId']) current_startDate = build['publishDate'] deploy_wrappers = [] for deploy in deploys: build = builds_helper.get_build(request, deploy['buildId']) if build['publishDate'] > current_startDate: deploy_wrapper = {} deploy_wrapper['deploy'] = deploy deploy_wrapper['build'] = build deploy_wrappers.append(deploy_wrapper) html = render_to_string('deploys/simple_pred_deploys.tmpl', { "deploy_wrappers": deploy_wrappers, "envName": name, "stageName": predStage, "show_lock": show_lock, "current_startDate": current_startDate, }) return HttpResponse(html) def warn_for_deploy(request, name, stage, buildId): """ Returns a warning message if: 1. The build has been tagged as build build 2. a build doesn't have a successful deploy on the preceding stage. TODO: we would have call backend twice since the getAllDeploys call does not support filtering on multiple states; Also, getAllDeploys return all deploys with commits after the specific commit, it would be good if there is options to return the exact matched deploys. """ build_info = builds_helper.get_build_and_tag(request, buildId) build = build_info["build"] tag = build_info.get("tag") if tag is not None and tag["value"] == tags_helper.TagValue.BAD_BUILD: html = render_to_string('warn_deploy_bad_build.tmpl', { 'tag': tag, }) return HttpResponse(html) env_promote = environs_helper.get_env_promotes_config(request, name, stage) pred_stage = env_promote.get('predStageName') if not pred_stage or pred_stage == BUILD_STAGE: return HttpResponse("") pred_env = environs_helper.get_env_by_stage(request, name, pred_stage) filter = {} filter['envId'] = [pred_env['id']] filter['commit'] = build['commit'] filter['repo'] = build['repo'] filter['oldestFirst'] = True filter['deployState'] = "SUCCEEDING" filter['pageIndex'] = 1 filter['pageSize'] = 1 result = deploys_helper.get_all(request, **filter) succeeding_deploys = result['deploys'] if succeeding_deploys: return HttpResponse("") filter['deployState'] = "SUCCEEDED" result = deploys_helper.get_all(request, **filter) succeeded_deploys = result['deploys'] if succeeded_deploys: return HttpResponse("") html = render_to_string('warn_no_success_deploy_in_pred.tmpl', { 'envName': name, 'predStageName': pred_stage, }) return HttpResponse(html) def get_env_config_history(request, name, stage): index = int(request.GET.get('page_index', '1')) size = int(request.GET.get('page_size', DEFAULT_PAGE_SIZE)) env = environs_helper.get_env_by_stage(request, name, stage) configs = environs_helper.get_config_history(request, name, stage, index, size) for config in configs: replaced_config = config["configChange"].replace(",", ", ").replace("#", "%23").replace("\"", "%22")\ .replace("{", "%7B").replace("}", "%7D").replace("_", "%5F") config["replaced_config"] = replaced_config return render(request, 'configs/config_history.html', { "envName": name, "stageName": stage, "envId": env['id'], "configs": configs, "pageIndex": index, "pageSize": DEFAULT_PAGE_SIZE, "disablePrevious": index <= 1, "disableNext": len(configs) < DEFAULT_PAGE_SIZE, }) def _parse_config_comparison(query_dict): configs = {} for key, value in query_dict.iteritems(): if key.startswith('chkbox_'): id = key[len('chkbox_'):] split_data = value.split('_') config_change = split_data[1] configs[id] = config_change return configs def get_config_comparison(request, name, stage): configs = _parse_config_comparison(request.POST) if len(configs) > 1: ids = configs.keys() change1 = configs[ids[0]] change2 = configs[ids[1]] return HttpResponse(json.dumps({'change1': change1, 'change2': change2}), content_type="application/json") return HttpResponse("", content_type="application/json") def show_config_comparison(request, name, stage): change1 = request.GET.get('change1') change2 = request.GET.get('change2') diff_res = GenerateDiff() result = diff_res.diff_main(change1, change2) diff_res.diff_cleanupSemantic(result) old_change = diff_res.old_content(result) new_change = diff_res.new_content(result) return render(request, 'configs/env_config_comparison_result.html', { "envName": name, "stageName": stage, "oldChange": old_change, "newChange": new_change, }) def get_deploy_schedule(request, name, stage): env = environs_helper.get_env_by_stage(request, name, stage) envs = environs_helper.get_all_env_stages(request, name) schedule_id = env.get('scheduleId', None); if schedule_id != None: schedule = schedules_helper.get_schedule(request, name, stage, schedule_id) else: schedule = None agent_number = agents_helper.get_agents_total_by_env(request, env["id"]) return render(request, 'deploys/deploy_schedule.html', { "envs": envs, "env": env, "schedule": schedule, "agent_number": agent_number, }) class GenerateDiff(diff_match_patch): def old_content(self, diffs): html = [] for (flag, data) in diffs: text = (data.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\n", "<br>") .replace(",", ",<br>")) if flag == self.DIFF_DELETE: html.append("""<b style=\"background:#FFB5B5; \">%s</b>""" % text) elif flag == self.DIFF_EQUAL: html.append("<span>%s</span>" % text) return "".join(html) def new_content(self, diffs): html = [] for (flag, data) in diffs: text = (data.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\n", "<br>") .replace(",", ",<br>")) if flag == self.DIFF_INSERT: html.append("""<b style=\"background:#97f697; \">%s</b>""" % text) elif flag == self.DIFF_EQUAL: html.append("<span>%s</span>" % text) return "".join(html) def get_new_commits(request, name, stage): env = environs_helper.get_env_by_stage(request, name, stage) current_deploy = deploys_helper.get(request, env['deployId']) current_build = builds_helper.get_build(request, current_deploy['buildId']) startSha = current_build['commit'] repo = current_build['repo'] scm_url = systems_helper.get_scm_url(request) diffUrl = "%s/%s/compare/%s...%s" % (scm_url, repo, startSha, startSha) last_deploy = common.get_last_completed_deploy(request, env) if not last_deploy: return render(request, 'deploys/deploy_commits.html', { "env": env, "title": "No previous deploy found!", "startSha": startSha, "endSha": startSha, "repo": repo, "diffUrl": diffUrl, }) last_build = builds_helper.get_build(request, last_deploy['buildId']) endSha = last_build['commit'] diffUrl = "%s/%s/compare/%s...%s" % (scm_url, repo, endSha, startSha) return render(request, 'deploys/deploy_commits.html', { "env": env, "startSha": startSha, "endSha": endSha, "repo": repo, "title": "Commits since last deploy", "diffUrl": diffUrl, }) def compare_deploys(request, name, stage): start_deploy_id = request.GET.get('start_deploy', None) start_deploy = deploys_helper.get(request, start_deploy_id) start_build = builds_helper.get_build(request, start_deploy['buildId']) startSha = start_build['commit'] repo = start_build['repo'] end_deploy_id = request.GET.get('end_deploy', None) if end_deploy_id: end_deploy = deploys_helper.get(request, end_deploy_id) else: env = environs_helper.get_env_by_stage(request, name, stage) end_deploy = common.get_previous_deploy(request, env, start_deploy) if not end_deploy: end_deploy = start_deploy end_build = builds_helper.get_build(request, end_deploy['buildId']) endSha = end_build['commit'] commits, truncated, new_start_sha = common.get_commits_batch(request, repo, startSha, endSha, keep_first=True) html = render_to_string('builds/commits.tmpl', { "commits": commits, "start_sha": new_start_sha, "end_sha": endSha, "repo": repo, "truncated": truncated, "show_checkbox": False, }) return HttpResponse(html) def compare_deploys_2(request, name, stage): env = environs_helper.get_env_by_stage(request, name, stage) configs = {} for key, value in request.GET.iteritems(): if key.startswith('chkbox_'): index = key[len('chkbox_'):] configs[index] = value indexes = configs.keys() start_build_id = configs[indexes[0]] end_build_id = configs[indexes[1]] if int(indexes[0]) > int(indexes[1]): start_build_id = configs[indexes[1]] end_build_id = configs[indexes[0]] start_build = builds_helper.get_build(request, start_build_id) startSha = start_build['commit'] repo = start_build['repo'] end_build = builds_helper.get_build(request, end_build_id) endSha = end_build['commit'] scm_url = systems_helper.get_scm_url(request) diffUrl = "%s/%s/compare/%s...%s" % (scm_url, repo, endSha, startSha) return render(request, 'deploys/deploy_commits.html', { "env": env, "startSha": startSha, "endSha": endSha, "repo": repo, "title": "Commits between the two deploys", "diffUrl": diffUrl, }) def add_instance(request, name, stage): params = request.POST groupName = params['groupName'] num = int(params['instanceCnt']) subnet = None asg_status = params['asgStatus'] launch_in_asg = True if 'subnet' in params: subnet = params['subnet'] if asg_status == 'UNKNOWN': launch_in_asg = False elif 'customSubnet' in params: launch_in_asg = False try: if not launch_in_asg: if not subnet: content = 'Failed to launch hosts to group {}. Please choose subnets in' \ ' <a href="https://deploy.pinadmin.com/groups/{}/config/">group config</a>.' \ ' If you have any question, please contact your friendly Teletraan owners' \ ' for immediate assistance!'.format(groupName, groupName) messages.add_message(request, messages.ERROR, content) else: host_ids = autoscaling_groups_helper.launch_hosts(request, groupName, num, subnet) if len(host_ids) > 0: content = '{} hosts have been launched to group {} (host ids: {})'.format(num, groupName, host_ids) messages.add_message(request, messages.SUCCESS, content) else: content = 'Failed to launch hosts to group {}. Please make sure the' \ ' <a href="https://deploy.pinadmin.com/groups/{}/config/">group config</a>' \ ' is correct. If you have any question, please contact your friendly Teletraan owners' \ ' for immediate assistance!'.format(groupName, groupName) messages.add_message(request, messages.ERROR, content) else: autoscaling_groups_helper.launch_hosts(request, groupName, num, None) content = 'Capacity increased by {}'.format(num) messages.add_message(request, messages.SUCCESS, content) except: log.error(traceback.format_exc()) raise return redirect('/env/{}/{}/deploy'.format(name, stage)) def get_tag_message(request): envs_tag = tags_helper.get_latest_by_targe_id(request, 'TELETRAAN') html = render_to_string('environs/tag_message.tmpl', { 'envs_tag': envs_tag, }) return HttpResponse(html) def update_schedule(request, name, stage): post_params = request.POST data = {} data['cooldownTimes'] = post_params['cooldownTimes'] data['hostNumbers'] = post_params['hostNumbers'] data['totalSessions'] = post_params['totalSessions'] schedules_helper.update_schedule(request, name, stage, data) return HttpResponse(json.dumps('')) def delete_schedule(request, name, stage): schedules_helper.delete_schedule(request, name, stage) return HttpResponse(json.dumps('')) def override_session(request, name, stage): session_num = request.GET.get('session_num') schedules_helper.override_session(request, name, stage, session_num) return HttpResponse(json.dumps(''))
Black Hangar Studios is a self-contained Film studio based in Alton, UK. The above video work is a short presentation of the facilities and was designed for the internal entertainment displays. A series of videos edited for Brainient, about the impact of new technologies in marketing & advertising.
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2014 Joseph Blaylock <jrbl@jrbl.org> # # 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. # from wtf import wtf class Shape(object): def __init__(self, pastry=None, **kwargs): self.initialized = True wtf(to_out=False, to_err=True, wvars=['centroid']) class Square(Shape): def __init__(self, **kwargs): super(Square, self).__init__(pastry='Croissant', **kwargs) if __name__ == "__main__": square = Square(centroid=(0,9), mass=3e7)
As business activity continues to move more and more online, the demand for full-scale cloud service providers has become a vital part of a businesses framework. Here at Huber & Associates, we strive to assist in the implementation and maintenance of a variety of hosted & cloud-based services. For More info on our cloud services, including pricing, call us today at (888) 634-5000.