code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
import sys
import os
import inspect
import logging
import struct
from argparse import ArgumentParser
from elfesteem import pe
from elfesteem import *
from elfesteem.strpatchwork import StrPatchwork
from miasm2.core import asmbloc
from miasm2.arch.x86.arch import mn_x86
from miasm2.arch.x86.disasm import dis_x86_32
from miasm2.jitter.jitload import jitter_x86_32, vm_load_pe, preload_pe, libimp
from miasm2.jitter.jitload import bin_stream_vm
from miasm2.jitter.csts import *
from miasm2.jitter.os_dep import win_api_x86_32
# Debug settings #
from pdb import pm
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
#
# Handle arguments
parser = ArgumentParser(description="Sandbox a PE binary packed with UPX")
parser.add_argument("filename", help="PE binary")
parser.add_argument("-r", "--log-regs",
help="Log registers value for each instruction",
action="store_true")
parser.add_argument("-m", "--log-mn",
help="Log desassembly conversion for each instruction",
action="store_true")
parser.add_argument("-n", "--log-newbloc",
help="Log basic blocks processed by the Jitter",
action="store_true")
parser.add_argument("-j", "--jitter",
help="Jitter engine. Possible values are : tcc (default), llvm",
default="tcc")
parser.add_argument("-g", "--graph",
help="Export the CFG graph in graph.txt",
action="store_true")
parser.add_argument("-v", "--verbose",
help="Verbose mode",
action="store_true")
args = parser.parse_args()
# Verbose mode
if args.verbose is True:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
# Init arch
myjit = jitter_x86_32(jit_type=args.jitter)
myjit.init_stack()
# Log level (if available with jitter engine)
myjit.jit.log_regs = args.log_regs
myjit.jit.log_mn = args.log_mn
myjit.jit.log_newbloc = args.log_newbloc
# Load pe and get entry point address
e = vm_load_pe(myjit.vm, args.filename)
libs = libimp()
preload_pe(myjit.vm, e, libs)
if args.verbose is True:
myjit.vm.vm_dump_memory_page_pool()
ep = e.rva2virt(e.Opthdr.AddressOfEntryPoint)
# Ensure there is one and only one leave (for OEP discovering)
mdis = dis_x86_32(myjit.bs)
mdis.dont_dis_nulstart_bloc = True
ab = mdis.dis_multibloc(ep)
bb = asmbloc.basicblocs(ab)
leaves = bb.get_bad_dst()
assert(len(leaves) == 1)
l = leaves.pop()
logging.info(l)
end_label = l.label.offset
logging.info('final label')
logging.info(end_label)
# Export CFG graph (dot format)
if args.graph is True:
g = asmbloc.bloc2graph(ab)
open("graph.txt", "w").write(g)
# User defined methods
def mygetproc(myjit):
global libs
ret_ad, args = myjit.func_args_stdcall(2)
libbase, fname = args
dst_ad = myjit.cpu.EBX
logging.info('EBX ' + hex(dst_ad))
if fname < 0x10000:
fname = fname
else:
fname = myjit.get_str_ansi(fname)
logging.info(fname)
ad = libs.lib_get_add_func(libbase, fname, dst_ad)
myjit.func_ret_stdcall(ret_ad, ad)
def kernel32_GetProcAddress(myjit):
return mygetproc(myjit)
# Set libs for win_32 api
win_api_x86_32.winobjs.runtime_dll = libs
if args.verbose is True:
myjit.vm.vm_dump_memory_page_pool()
# Set up stack
myjit.vm_push_uint32_t(1) # reason code if dll
myjit.vm_push_uint32_t(1) # reason code if dll
myjit.vm_push_uint32_t(0x1337beef)
# Breakpoint callbacks
def update_binary(myjit):
e.Opthdr.AddressOfEntryPoint = e.virt2rva(myjit.pc)
logging.info('updating binary')
for s in e.SHList:
sdata = myjit.vm.vm_get_mem(e.rva2virt(s.addr), s.rawsize)
e.virt[e.rva2virt(s.addr)] = sdata
# Set callbacks
myjit.add_breakpoint(end_label, update_binary)
myjit.add_lib_handler(libs, globals())
# Run until breakpoint is reached
myjit.init_run(ep)
myjit.continue_run()
regs = myjit.cpu.vm_get_gpreg()
new_dll = []
# XXXXX
e.SHList.align_sections(0x1000, 0x1000)
logging.info(repr(e.SHList))
st = StrPatchwork()
st[0] = e.content
# get back data from emulator
for s in e.SHList:
ad1 = e.rva2virt(s.addr)
ad2 = ad1 + len(s.data)
st[s.offset] = e.virt(ad1, ad2)
# e.content = str(st)
e.DirRes = pe.DirRes(e)
e.DirImport.impdesc = None
logging.info(repr(e.DirImport.impdesc))
new_dll = libs.gen_new_lib(e)
logging.info(new_dll)
e.DirImport.impdesc = []
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
logging.info(repr(e.SHList))
e.DirImport.set_rva(s_myimp.addr)
# XXXX TODO
e.NThdr.optentries[pe.DIRECTORY_ENTRY_DELAY_IMPORT].rva = 0
e.Opthdr.AddressOfEntryPoint = e.virt2rva(end_label)
bname, fname = os.path.split(args.filename)
fname = os.path.join(bname, fname.replace('.', '_'))
open(fname + '_unupx.bin', 'w').write(str(e))
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core.bin_stream import bin_stream
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from elfesteem import *
from pdb import pm
from miasm2.core import asmbloc
import struct
e = pe_init.PE()
s_text = e.SHList.add_section(name="text", addr=0x1000, rawsize=0x1000)
s_iat = e.SHList.add_section(name="iat", rawsize=0x100)
new_dll = [({"name": "USER32.dll",
"firstthunk": s_iat.addr}, ["MessageBoxA"])]
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
e.DirImport.set_rva(s_myimp.addr)
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 32, '''
main:
PUSH 0
PUSH title
PUSH msg
PUSH 0
CALL DWORD PTR [ MessageBoxA ]
RET
title:
.string "Hello!"
msg:
.string "World!"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr))
symbol_pool.set_offset(symbol_pool.getby_name_create("MessageBoxA"),
e.DirImport.get_funcvirt('MessageBoxA'))
e.Opthdr.AddressOfEntryPoint = s_text.addr
for b in blocs[0]:
print b
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, 32, blocs[0], symbol_pool)
print patches
for offset, raw in patches.items():
e.virt[offset] = raw
open('box_x86_32.bin', 'wb').write(str(e))
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core.bin_stream import bin_stream
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from elfesteem import *
from pdb import pm
from miasm2.core import asmbloc
import struct
e = pe_init.PE()
s_text = e.SHList.add_section(name="text", addr=0x1000, rawsize=0x1000)
s_iat = e.SHList.add_section(name="iat", rawsize=0x100)
new_dll = [({"name": "USER32.dll",
"firstthunk": s_iat.addr}, ["MessageBoxA"])]
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
e.DirImport.set_rva(s_myimp.addr)
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 32, '''
main:
CALL test_automod
CALL test_automod
RET
test_automod:
PUSH EBP
MOV EBP, ESP
loop:
MOV EAX, 0
CMP EAX, 0
JMP mod_addr
mod_addr:
JNZ end
PUSH 0
PUSH title
PUSH msg
PUSH 0
CALL DWORD PTR [ MessageBoxA ]
; automodif code
MOV BYTE PTR [mod_addr], 0xEB
JMP loop
end:
MOV BYTE PTR [mod_addr], 0x75
MOV ESP, EBP
POP EBP
RET
title:
.string "Hello!"
msg:
.string "World!"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr))
symbol_pool.set_offset(symbol_pool.getby_name_create("MessageBoxA"),
e.DirImport.get_funcvirt('MessageBoxA'))
e.Opthdr.AddressOfEntryPoint = s_text.addr
for b in blocs[0]:
print b
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, 32, blocs[0], symbol_pool)
print patches
for offset, raw in patches.items():
e.virt[offset] = raw
open('box_x86_32_mod.bin', 'wb').write(str(e))
| Python |
# Minimalist Symbol Exec example
from miasm2.core.bin_stream import bin_stream_str
from miasm2.arch.x86.arch import mn_x86
from miasm2.arch.x86.ira import ir_a_x86_32
from miasm2.arch.x86.regs import all_regs_ids, all_regs_ids_init
from miasm2.ir.symbexec import symbexec
from miasm2.arch.x86.disasm import dis_x86_32 as dis_engine
import miasm2.expression.expression as m2_expr
l = mn_x86.fromstring("MOV EAX, EBX", 32)
asm = mn_x86.asm(l)[0]
bin_stream = bin_stream_str(asm)
mdis = dis_engine(bin_stream)
disasm = mdis.dis_multibloc(0)
ir = ir_a_x86_32(mdis.symbol_pool)
for bbl in disasm: ir.add_bloc(bbl)
symbols_init = {}
for i, r in enumerate(all_regs_ids):
symbols_init[r] = all_regs_ids_init[i]
symb = symbexec(mn_x86, symbols_init)
block = ir.get_bloc(0)
cur_addr = symb.emulbloc(block)
assert(symb.symbols[m2_expr.ExprId("EAX")] == symbols_init[m2_expr.ExprId("EBX")])
print 'modified registers:'
symb.dump_id()
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core.bin_stream import bin_stream
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from elfesteem import *
from pdb import pm
from miasm2.core import asmbloc
import struct
e = pe_init.PE()
s_text = e.SHList.add_section(name="text", addr=0x1000, rawsize=0x1000)
s_iat = e.SHList.add_section(name="iat", rawsize=0x100)
new_dll = [({"name": "USER32.dll",
"firstthunk": s_iat.addr}, ["MessageBoxA"])]
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
e.DirImport.set_rva(s_myimp.addr)
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 32, '''
main:
CALL cipher_code
CALL msgbox_encrypted_start
CALL cipher_code
RET
cipher_code:
PUSH EBP
MOV EBP, ESP
LEA ESI, DWORD PTR [msgbox_encrypted_start]
LEA EDI, DWORD PTR [msgbox_encrypted_stop]
loop:
XOR BYTE PTR [ESI], 0x42
INC ESI
CMP ESI, EDI
JBE loop
MOV ESP, EBP
POP EBP
RET
msgbox_encrypted_start:
PUSH 0
PUSH title
PUSH msg
PUSH 0
CALL DWORD PTR [ MessageBoxA ]
RET
.dontsplit
msgbox_encrypted_stop:
.long 0
title:
.string "Hello!"
msg:
.string "World!"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr))
symbol_pool.set_offset(symbol_pool.getby_name_create(
"MessageBoxA"), e.DirImport.get_funcvirt('MessageBoxA'))
e.Opthdr.AddressOfEntryPoint = s_text.addr
for b in blocs[0]:
print b
print "symbols"
print symbol_pool
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, 32, blocs[0], symbol_pool)
print patches
ad_start = symbol_pool.getby_name_create("msgbox_encrypted_start").offset
ad_stop = symbol_pool.getby_name_create("msgbox_encrypted_stop").offset
# cipher code
new_patches = dict(patches)
for ad, val in patches.items():
if ad_start <= ad < ad_stop:
new_patches[ad] = "".join([chr(ord(x) ^ 0x42) for x in val])
for offset, raw in new_patches.items():
e.virt[offset] = raw
open('box_x86_32_enc.bin', 'wb').write(str(e))
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core.bin_stream import bin_stream
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from elfesteem import *
from pdb import pm
from miasm2.core import asmbloc
import struct
e = pe_init.PE()
s_text = e.SHList.add_section(name="text", addr=0x1000, rawsize=0x1000)
s_iat = e.SHList.add_section(name="iat", rawsize=0x100)
new_dll = [({"name": "USER32.dll",
"firstthunk": s_iat.addr}, ["MessageBoxA"])]
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
e.DirImport.set_rva(s_myimp.addr)
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 32, '''
main:
PUSH EBP
MOV EBP, ESP
MOV BYTE PTR [myint], 0x90
myint:
INT 0x3
PUSH 0
PUSH title
PUSH msg
PUSH 0
CALL DWORD PTR [ MessageBoxA ]
MOV ESP, EBP
POP EBP
RET
title:
.string "Hello!"
msg:
.string "World!"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr))
symbol_pool.set_offset(symbol_pool.getby_name_create("MessageBoxA"),
e.DirImport.get_funcvirt('MessageBoxA'))
e.Opthdr.AddressOfEntryPoint = s_text.addr
for b in blocs[0]:
print b
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, 32, blocs[0], symbol_pool)
print patches
for offset, raw in patches.items():
e.virt[offset] = raw
open('box_x86_32_mod_self.bin', 'wb').write(str(e))
| Python |
import sys
from elfesteem import pe_init
from miasm2.arch.x86.disasm import dis_x86_32
from miasm2.core.asmbloc import bloc2graph
from miasm2.core.bin_stream import bin_stream_pe
if len(sys.argv) != 3:
print 'Example:'
print "%s box_upx.exe 0x410f90" % sys.argv[0]
sys.exit(0)
fname = sys.argv[1]
ad = int(sys.argv[2], 16)
e = pe_init.PE(open(fname).read())
bs = bin_stream_pe(e.virt)
mdis = dis_x86_32(bs)
# inform the engine not to disasm nul instructions
mdis.dont_dis_nulstart_bloc = True
blocs = mdis.dis_multibloc(ad)
g = bloc2graph(blocs)
open('graph.txt', 'w').write(g)
| Python |
from miasm2.arch.x86.arch import mn_x86
from miasm2.arch.x86.regs import *
l = mn_x86.fromstring('MOV EAX, EBX', 32)
print "instruction:", l
print "arg:", l.args[0]
x = mn_x86.asm(l)
print x
l.args[0] = EDX
y = mn_x86.asm(l)
print y
print mn_x86.dis(y[0], 32)
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.arm.arch import mn_arm, base_expr, variable
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from miasm2.core import asmbloc
from elfesteem.strpatchwork import StrPatchwork
my_mn = mn_arm
reg_and_id = dict(mn_arm.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(my_mn, "arm", '''
main:
STMFD SP!, {R4, R5, LR}
MOV R0, mystr & 0xffff
ORR R0, R0, mystr & 0xffff0000
MOV R1, mystrend & 0xffff
ORR R1, R1, mystrend & 0xffff0000
xxx:
LDR R2, [PC, key-(xxx+8)]
loop:
LDRB R3, [R0]
EOR R3, R3, R2
STRB R3, [R0], 1
CMP R0, R1
BNE loop
EOR R0, R0, R0
BNE end
EOR R1, R1, R1
EOR R2, R2, R2
EORGE R1, R1, R1
EORGE R2, R2, R2
ADDLTS R2, R2, R2
SUBEQ R2, R2, R2
end:
LDMFD SP!, {R4, R5, PC}
key:
.long 0x11223344
mystr:
.string "test string"
mystrend:
.long 0
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), 0x0)
for b in blocs[0]:
print b
# graph sc####
g = asmbloc.bloc2graph(blocs[0])
open("graph.txt", "w").write(g)
s = StrPatchwork()
print "symbols"
print symbol_pool
# dont erase from start to shell code padading
resolved_b, patches = asmbloc.asm_resolve_final(
my_mn, 'arm', blocs[0], symbol_pool)
print patches
for offset, raw in patches.items():
s[offset] = raw
open('demo_arm.bin', 'wb').write(str(s))
| Python |
from miasm2.arch.x86.disasm import dis_x86_32
from miasm2.core.asmbloc import bloc2graph
s = '\xb8\xef\xbe7\x13\xb9\x04\x00\x00\x00\xc1\xc0\x08\xe2\xfb\xc3'
mdis = dis_x86_32(s)
blocs = mdis.dis_multibloc(0)
for b in blocs:
print b
g = bloc2graph(blocs)
open('graph.txt', 'w').write(g)
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core.bin_stream import bin_stream
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from elfesteem import *
from pdb import pm
from miasm2.core import asmbloc
import struct
e = pe_init.PE(wsize=64)
s_text = e.SHList.add_section(name="text", addr=0x1000, rawsize=0x1000)
s_iat = e.SHList.add_section(name="iat", rawsize=0x100)
new_dll = [({"name": "USER32.dll",
"firstthunk": s_iat.addr}, ["MessageBoxA"])]
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
e.DirImport.set_rva(s_myimp.addr)
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt64(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=64))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 64, '''
main:
MOV R9, 0x0
MOV R8, title
MOV RDX, msg
MOV RCX, 0x0
MOV RAX, QWORD PTR [ MessageBoxA ]
CALL RAX
RET
title:
.string "Hello!"
msg:
.string "World!"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr))
symbol_pool.set_offset(symbol_pool.getby_name_create("MessageBoxA"),
e.DirImport.get_funcvirt('MessageBoxA'))
e.Opthdr.AddressOfEntryPoint = s_text.addr
for b in blocs[0]:
print b
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, 64, blocs[0], symbol_pool,
max_offset=0xFFFFFFFFFFFFFFFF)
print patches
for offset, raw in patches.items():
e.virt[offset] = raw
open('box_x86_64.bin', 'wb').write(str(e))
| Python |
#! /usr/bin/env python
# test instruction caching
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core.bin_stream import bin_stream
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from elfesteem import *
from pdb import pm
from miasm2.core import asmbloc
import struct
e = pe_init.PE()
s_text = e.SHList.add_section(name="text", addr=0x1000, rawsize=0x1000)
s_iat = e.SHList.add_section(name="iat", rawsize=0x100)
new_dll = [({"name": "USER32.dll",
"firstthunk": s_iat.addr}, ["MessageBoxA"])]
e.DirImport.add_dlldesc(new_dll)
s_myimp = e.SHList.add_section(name="myimp", rawsize=len(e.DirImport))
e.DirImport.set_rva(s_myimp.addr)
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 32, '''
main:
CALL test_automod
RET
lbl_good:
NOP
NOP
NOP
NOP
NOP
NOP
NOP
NOP
NOP
test_automod:
PUSH EBP
MOV EBP, ESP
LEA EDI, DWORD PTR [lbl_mod]
LEA ESI, DWORD PTR [lbl_good]
MOV ECX, 0x8
REPE MOVSB
lbl_mod:
XOR EAX, EAX
MOV DWORD PTR [EAX], 0xDEADC0DE
NOP
NOP
NOP
PUSH 0
PUSH title
PUSH msg
PUSH 0
CALL DWORD PTR [ MessageBoxA ]
MOV ESP, EBP
POP EBP
RET
title:
.string "Hello!"
msg:
.string "World!"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr))
symbol_pool.set_offset(symbol_pool.getby_name_create("MessageBoxA"),
e.DirImport.get_funcvirt('MessageBoxA'))
e.Opthdr.AddressOfEntryPoint = s_text.addr
for b in blocs[0]:
print b
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, 32, blocs[0], symbol_pool)
print patches
for offset, raw in patches.items():
e.virt[offset] = raw
open('box_x86_32_repmod.bin', 'wb').write(str(e))
| Python |
#! /usr/bin/env python
from miasm2.core.cpu import parse_ast
from miasm2.arch.x86.arch import mn_x86, base_expr, variable
from miasm2.core import parse_asm
from miasm2.expression.expression import *
from miasm2.core import asmbloc
from elfesteem.strpatchwork import StrPatchwork
reg_and_id = dict(mn_x86.regs.all_regs_ids_byname)
def my_ast_int2expr(a):
return ExprInt32(a)
def my_ast_id2expr(t):
return reg_and_id.get(t, ExprId(t, size=32))
my_var_parser = parse_ast(my_ast_id2expr, my_ast_int2expr)
base_expr.setParseAction(my_var_parser)
blocs, symbol_pool = parse_asm.parse_txt(mn_x86, 32, '''
main:
PUSH EBP
MOV EBP, ESP
SUB ESP, 0x100
MOV EAX, 0x1337
LEA ESI, DWORD PTR [mystr]
MOV ESP, EBP
POP EBP
RET
mystr:
.string "test string"
''')
# fix shellcode addr
symbol_pool.set_offset(symbol_pool.getby_name("main"), 0x0)
s = StrPatchwork()
resolved_b, patches = asmbloc.asm_resolve_final(
mn_x86, '32', blocs[0], symbol_pool)
for offset, raw in patches.items():
s[offset] = raw
print patches
open('demo_x86_32.bin', 'wb').write(str(s))
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from django.template.defaultfilters import slugify
class Familia(models.Model):
nom = models.CharField(u"Nom", max_length=250, help_text = u'''Nom de la família''', blank = False )
logo = models.ImageField(u"Logo", blank=True, null=True, upload_to="families", help_text = u"Logo de la família" )
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = self.slug if self.slug else slugify(self.nom)
super(Familia, self).save(*args, **kwargs)
class Cicle(models.Model):
GRAU_CHOICES = (
('M',u'Mitjà'),
('S',u'Superior'),
)
familia = models.ForeignKey(Familia)
codi = models.CharField(u"Acrònim", max_length=20, help_text = u'''Acrònim del cicle''', blank = False )
nom = models.CharField(u"Nom", max_length=250, help_text = u'''Nom del cicle''', blank = False )
nivell = models.CharField(u"Nivell", max_length=1, choices=GRAU_CHOICES, help_text = u'''Nivel del cicle''', blank = False )
logo = models.ImageField(u"Logo", blank=True, null=True, upload_to="cicles", help_text = u"Logo del cicle" )
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = self.slug if self.slug else slugify(self.nom)
super(Cicle, self).save(*args, **kwargs)
class Meta:
ordering=['familia','nivell', 'nom']
db_table = u'cicles'
verbose_name = u'Cicle Formatiu'
verbose_name_plural = u'Cicles Formatius'
def __unicode__(self):
return u"{0} - {1}".format( self.codi, self.nom )
class CiclePY_codi(Cicle):
class Meta:
proxy = True
ordering=['familia','nivell', 'codi']
def __unicode__(self):
return unicode( self.Cicle )
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fp2cat.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
# This Python file uses the following encoding: utf-8
#----write pdf-------------------------------------
from django import http
from django.template.loader import get_template
from django.template import Context
import cStringIO as StringIO
from django.utils.translation.trans_real import gettext_noop
from decimal import Decimal
#--------------------------------------------------
def decimal2( d ):
cent = Decimal( 100 )
enter = int( d * cent)
return Decimal ( enter ) / cent
def getClientAdress( request ):
#TODO: HttpRequest.get_host() at https://docs.djangoproject.com/en/dev/ref/request-response/
try:
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED_HOST',
'HTTP_X_FORWARDED_SERVER',
]
for field in FORWARDED_FOR_FIELDS:
if field in request.META:
if ',' in request.META[field]:
parts = request.META[field].split(',')
request.META[field] = parts[-1].strip()
client_address = request.META['HTTP_X_FORWARDED_FOR']
except:
client_address = request.META['REMOTE_ADDR']
return client_address
def lowpriority():
""" Set the priority of the process to below-normal."""
pass
def getSoftColor( obj ):
str = unicode( obj ) + u'con mucha marcha'
i = 0
j = 77
for s in str:
i += ( 103 * ord( s ) ) % 2001
j = j % 573 + i * 5
i = i*i
gros = 200 + i%55
mitja1 = 100 + j%155
mitja2 = 150 + (i+j)%105
color=(None,None,None)
if i%3 == 0:
if i%2 ==0:
color = ( gros, mitja1, mitja2 )
else:
color = ( gros, mitja2, mitja1 )
elif i%3 == 1:
if i%2 ==0:
color = ( mitja1, gros, mitja2 )
else:
color = ( mitja2, gros, mitja1 )
elif i%3 == 2:
if i%2 ==0:
color = ( mitja1, mitja2, gros )
else:
color = ( mitja2, mitja1, gros )
return u'#{0:02X}{1:02X}{2:02X}'.format( color[0], color[1], color[2] )
def getImpersonateUser( request ):
user = request.session['impersonacio'] if request.session.has_key('impersonacio') else request.user
l4 = request.session['l4'] if request.session.has_key('l4') else False
return ( user, l4, )
def getRealUser( request ):
return request.user
def sessioImpersonada( request ):
(user, _ ) = getImpersonateUser(request)
return request and request.user.is_authenticated() and request.user.pk != user.pk
class classebuida(object):
pass
class llista(list):
def compte(self):
return self.__len__()
def __init__(self, *args, **kwargs):
super(llista,self).__init__(*args,**kwargs)
class diccionari(dict):
def compte(self):
return self.__len__()
def itemsEnOrdre(self):
return iter(sorted(self.iteritems()))
def __init__(self, *args, **kwargs):
super(dict,self).__init__(*args,**kwargs)
def add_secs_to_time(timeval, secs_to_add):
import datetime
dummy_date = datetime.date(1, 1, 1)
full_datetime = datetime.datetime.combine(dummy_date, timeval)
added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
return added_datetime.time()
def fetch_resources(uri, rel):
import os.path
from django.conf import settings
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def supported_languages():
from rentmail.settings import SUPPORTED_LANGUAGES
from django.conf.global_settings import LANGUAGES
return [ (l[0],gettext_noop(l[1]),) for l in LANGUAGES if l[0] in SUPPORTED_LANGUAGES ]
| Python |
from django import forms
from django.forms.widgets import Widget
class ckbxForm(forms.Form):
ckbx = forms.BooleanField(required = False )
def __init__(self, *args, **kwargs):
self.label = kwargs.pop('label', None)
self.help_text = kwargs.pop('help_text', None)
super(ckbxForm,self).__init__(*args,**kwargs)
self.fields['ckbx'].label = self.label
self.fields['ckbx'].help_text = self.help_text
class dataForm(forms.Form):
data = forms.DateField( required = False ,
widget = forms.DateInput(attrs={'class':'datepicker'} ) )
def __init__(self, *args, **kwargs):
self.label = kwargs.pop('label', None)
self.help_text = kwargs.pop('help_text', None)
super(dataForm,self).__init__(*args,**kwargs)
self.fields['data'].label = self.label
self.fields['data'].help_text = self.help_text
class hiddenIntForm(forms.Form):
enter = forms.IntegerField( widget = forms.HiddenInput() )
def __init__(self, *args, **kwargs):
self.initial = kwargs.pop('initial', None)
super(hiddenIntForm,self).__init__(*args,**kwargs)
self.fields['enter'].initial = self.initial
| Python |
# This Python file uses the following encoding: utf-8
from utils import tools
from django.utils.datetime_safe import date
def dades_basiques(request):
(user, l4) = tools.getImpersonateUser(request)
sessioImpersonada = tools.sessioImpersonada(request)
return {
'data': date.today(),
'user': user,
'l4': l4,
'sessioImpersonada': sessioImpersonada,
}
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from utils.fields import CurrencyField
class Preferencies(models.Model):
codi = models.CharField(u'Codi', max_length = 20, help_text = u'''Codi de la preferència. (No canviar-lo)''', unique=True)
boolean_value = models.NullBooleanField( u"Tipus Cert o Fals" , blank = True, null = True)
integer_value = models.IntegerField( u"Número enter" , blank = True, null = True)
char_value = models.CharField( u"Text curt" , max_length=250, blank = True)
text_value = models.TextField( u"Text lliure" , blank = True)
float_value = models.FloatField( u"Número amb decimals" , blank = True, null = True)
email_value = models.EmailField( u"Adreça de correu" , max_length=250, blank = True)
currency_value = CurrencyField( u"Import" , max_digits=8, decimal_places=2, blank = True, null = True)
class Meta:
ordering=['codi']
db_table = u'preferencies'
verbose_name = u'Preferència'
verbose_name_plural = u'Preferències'
def __unicode__(self):
return u"{0}".format( self.codi)
| Python |
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from decimal import Decimal
class CurrencyField(models.DecimalField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
try:
return super(CurrencyField, self).to_python(value).quantize(Decimal("0.01"))
except AttributeError:
return None
| Python |
from django.conf.urls.defaults import patterns
urlpatterns = patterns('utils.views',
(r'^about/$', 'about') ,
(r'^preferenciesEdit/$', 'preferenciesEdit') ,
)
| Python |
import datetime
from django.contrib.auth import logout
class NoCacheMiddleware(object):
def process_response(self, request, response):
if response and type( response ) != type:
#if hasattr(request, 'session'): request.session.set_expiry(1500)
response['Pragma'] = 'no-cache'
response['Cache-Control'] = 'no-cache, must-revalidate, proxy-revalidate, no-store'
return response
class timeOutMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
if 'lastRequest' in request.session:
elapsedTime = datetime.datetime.now() - request.session['lastRequest']
if elapsedTime.seconds > 15*60:
del request.session['lastRequest']
logout(request)
request.session['lastRequest'] = datetime.datetime.now()
else:
if 'lastRequest' in request.session:
del request.session['lastRequest']
return None
class IncludeLoginInErrors(object):
#http://stackoverflow.com/questions/9294043/include-django-logged-user-in-django-traceback-error
def process_exception(self, request, exception):
"""
Process the request to add some variables to it.
"""
# Add other details about the user to the META CGI variables.
try:
if request.user.is_anonymous():
request.META['AUTH_NAME'] = "Anonymous User"
request.META['AUTH_USER'] = "Anonymous User"
request.META['AUTH_USER_EMAIL'] = ""
request.META['AUTH_USER_ID'] = 0
request.META['AUTH_USER_IS_ACTIVE'] = False
request.META['AUTH_USER_IS_SUPERUSER'] = False
request.META['AUTH_USER_IS_STAFF'] = False
request.META['AUTH_USER_LAST_LOGIN'] = ""
else:
request.META['AUTH_NAME'] = str(request.user.first_name) + " " + str(request.user.last_name)
request.META['AUTH_USER'] = str(request.user.username)
request.META['AUTH_USER_EMAIL'] = str(request.user.email)
request.META['AUTH_USER_ID'] = str(request.user.id)
request.META['AUTH_USER_IS_ACTIVE'] = str(request.user.is_active)
request.META['AUTH_USER_IS_SUPERUSER'] = str(request.user.is_superuser)
request.META['AUTH_USER_IS_STAFF'] = str(request.user.is_staff)
request.META['AUTH_USER_LAST_LOGIN'] = str(request.user.last_login)
except:
pass
| Python |
from django import template
from django.template import resolve_variable, NodeList
from django.contrib.auth.models import Group
register = template.Library()
#http://djangosnippets.org/snippets/390/
@register.tag()
def ifusergroup(parser, token):
""" Check to see if the currently logged in user belongs to a specific
group. Requires the Django authentication contrib app and middleware.
Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or
{% ifusergroup Admins %} ... {% else %} ... {% endifusergroup %}
"""
try:
_, group = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("Tag 'ifusergroup' requires 1 argument.")
nodelist_true = parser.parse(('else', 'endifusergroup'))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse(('endifusergroup',))
parser.delete_first_token()
else:
nodelist_false = NodeList()
return GroupCheckNode(group, nodelist_true, nodelist_false)
class GroupCheckNode(template.Node):
def __init__(self, group, nodelist_true, nodelist_false):
self.group = group
self.nodelist_true = nodelist_true
self.nodelist_false = nodelist_false
def render(self, context):
user = resolve_variable('user', context)
if not user.is_authenticated():
return self.nodelist_false.render(context)
#if user.is_staff:
# return self.nodelist_true.render(context)
try:
group = Group.objects.get(name=self.group)
except Group.DoesNotExist:
return self.nodelist_false.render(context)
if group in user.groups.all():
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
| Python |
#This Python file uses the following encoding: utf-8
from django.contrib.auth.models import Group
from django.http import Http404
def group_required(groups=[]):
def decorator(func):
def inner_decorator(request,*args, **kwargs):
for group in groups:
if Group.objects.get(name=group) in request.user.groups.all():
return func(request, *args, **kwargs)
raise Http404()
from django.utils.functional import wraps
return wraps(func)(inner_decorator)
return decorator
| Python |
# This Python file uses the following encoding: utf-8
#http://copiesofcopies.org/webl/2010/04/26/a-better-datetime-widget-for-django/
#from django.template.loader import render_to_string
from django.forms.widgets import Select, MultiWidget, DateInput, TextInput
from time import strftime
from django.utils.safestring import mark_safe
#-----------------------------------------------------------------------------------
# És un select per ser omplert via AJAX. Cal passar-li com a paràmetre l'script que l'omplirà
# el javascript s'invoca des d'altres widgets. Ex: attrs={'onchange':'get_curs();'}
class SelectAjax( Select ):
def __init__(self, jquery=None, attrs=None, choices=(), buit=None):
self.jquery = jquery if jquery else u''
self.buit = buit if buit else False
Select.__init__(self, attrs=attrs, choices=choices)
def render(self, name, value, attrs=None, choices=()):
script =u'<script>%s</script>'%self.jquery
output = super(SelectAjax, self).render(name, value=value, attrs=attrs, choices=choices)
return mark_safe(script) + output
def render_options(self, choices, selected_choices):
from itertools import chain
from django.utils.encoding import force_unicode
from django.utils.html import escape
selected_choices = set([force_unicode(v) for v in selected_choices])
output = []
for option_value, option_label in chain(self.choices, choices):
if (not self.buit) or (force_unicode(option_value) in selected_choices):
if isinstance(option_label, (list, tuple)):
output.append(u'<optgroup label="%s">' % escape
(force_unicode(option_value)))
for option in option_label:
output.append(self.render_option(selected_choices, *option))
output.append(u'</optgroup>')
else:
output.append(self.render_option(selected_choices,
option_value, option_label))
return u'\n'.join(output)
#-----------------------------------------------------------------------------------
from django.forms import Widget
class label(Widget):
def __init__(self, attrs=None, format=None):
super(label, self).__init__(attrs)
def render(self, name, value, attrs=None):
if value is None:
value = ''
return u'--------> %s'%value
#http://trentrichardson.com/examples/timepicker/
class JqSplitDateTimeWidget(MultiWidget):
def __init__(self, attrs=None, date_format=None, time_format=None):
attrs= attrs if attrs else {'date_class':'datepicker','time_class':'timepicker'}
date_class = attrs['date_class']
time_class = attrs['time_class']
del attrs['date_class']
del attrs['time_class']
time_attrs = attrs.copy()
time_attrs['class'] = time_class
time_attrs['size'] = '5'
time_attrs['maxlength'] = '5'
date_attrs = attrs.copy()
date_attrs['class'] = date_class
widgets = (DateInput(attrs=date_attrs, format=date_format),
TextInput(attrs=time_attrs),
)
super(JqSplitDateTimeWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
d = strftime("%Y-%m-%d", value.timetuple())
hour = strftime("%H:%M", value.timetuple())
return (d, hour)
else:
return (None, None)
def format_output(self, rendered_widgets):
"""
Given a list of rendered widgets (as strings), it inserts an HTML
linebreak between them.
Returns a Unicode string representing the HTML for the whole lot.
"""
return "Dia: %s Hora: %s" % (rendered_widgets[0], rendered_widgets[1])
| Python |
# This Python file uses the following encoding: utf-8
#templates
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.contrib.auth.models import Group
from django.forms.forms import NON_FIELD_ERRORS
#auth
from django.contrib.auth.decorators import login_required
from utils.decorators import group_required
from utils import tools
from django.utils.datetime_safe import datetime
from django.db.models import Q
from utils.models import Preferencies
from django.forms.models import modelformset_factory
def logout_page(request):
try:
del request.session['impersonacio']
except KeyError:
pass
logout(request)
return HttpResponseRedirect('/')
def menu(request):
#How do I make a variable available to all my templates?
#http://readthedocs.org/docs/django/1.2.4/faq/usage.html#how-do-i-make-a-variable-available-to-all-my-templates
if request.user.is_anonymous():
from fp2cat.settings import LOGIN_URL
return HttpResponseRedirect( LOGIN_URL )
else:
#prenc impersonate user:
(user, _) = tools.getImpersonateUser(request)
g, _ = Group.objects.get_or_create(name='lectors')
if g in user.groups.all():
return HttpResponseRedirect( 'correus/correuEdit/')
return render_to_response(
'main_page.html',
{ },
context_instance=RequestContext(request))
def about(request):
credentials = tools.getImpersonateUser(request)
(user, _ ) = credentials
report = []
taula = tools.classebuida()
taula.titol = tools.classebuida()
taula.titol.contingut = ''
taula.titol.enllac = None
taula.capceleres = []
capcelera = tools.classebuida()
capcelera.amplade = 150
capcelera.contingut = u'Informació'
capcelera.enllac = None
taula.capceleres.append(capcelera)
capcelera = tools.classebuida()
capcelera.amplade = 400
capcelera.contingut = u''
taula.capceleres.append(capcelera)
taula.fileres = []
filera = []
#-by--------------------------------------------
camp = tools.classebuida()
camp.enllac = None
camp.contingut = u'Llicència'
camp.enllac = ''
filera.append(camp)
#-tip--------------------------------------------
tip = u'''Desenvolupat per daniel herrera (ctrl.alt.d@gmail.com)
'''
camp = tools.classebuida()
camp.enllac = ''
camp.contingut = tip
filera.append(camp)
taula.fileres.append( filera )
report.append(taula)
return render_to_response(
'report.html',
{'report': report,
'head': 'About' ,
},
context_instance=RequestContext(request))
#-------------------------------------------------------------
@login_required
@group_required(['managers'])
def preferenciesEdit(request ):
credentials = tools.getImpersonateUser(request)
(user, l4 ) = credentials
if not l4:
msgs = {}
msgs['errors'] = [ u'Només es pot accedir a aquesta pantalla en mode L4' ]
msgs['url_next'] = r'/admin'
return render_to_response(
'resultat.html',
{'head': u'Modificació de paràmetres',
'''msgs''': msgs,
},
context_instance=RequestContext(request))
prm_model = Preferencies
prm_url_next = '/utils/preferenciesEdit/'
prm_head = "Manteniment de Preferències:"
prm_can_delete = True
extra = 0 if prm_model.objects.exists() else 1
#missatge = u"MSG de campings!"
formFac = modelformset_factory(prm_model, extra = extra, can_delete = prm_can_delete )
if request.method == 'POST':
formSet = formFac( request.POST )
hi_ha_errors = False
if formSet.is_valid():
for form in formSet:
if form not in formSet.deleted_forms and form.is_valid() and form.cleaned_data:
form.save()
for form in formSet.deleted_forms:
instance = form.instance
if instance.pk:
try:
instance.delete()
except Exception, e:
form._errors.setdefault(NON_FIELD_ERRORS, []).append( 'No puc esborrar aquesta dada, possiblement té altres dades associades.' )
hi_ha_errors = True
if not hi_ha_errors:
return HttpResponseRedirect( prm_url_next )
else:
formSet = formFac( )
for f in formSet:
f.formSetDelimited = True
for f in formSet:
f.fields['codi'].widget.attrs['class'] = 'curt'
return render_to_response(
'formset.html',
{'formset': formSet,
'head': prm_head,
'addMoreButton': True,
#'missatge' : missatge,
},
context_instance=RequestContext(request))
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fp2cat.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from django.contrib.auth.models import User
from curriculums.models import Cicle, ModulProfessional, UnitatFormativa, Contingut
from django.template.defaultfilters import slugify
class Post(models.Model):
TIPUS_CHOICES = (
('T', u'Teoria'),
('P', u'Pràctica'),
('P', u'Programació Curricular'),
)
titol = models.CharField(u"Títol", max_length=250, help_text = u'''Títol''', blank = False, unique = True )
cos = models.TextField(u"Cos", help_text = u'''Cos del post''', blank = False )
tipus = models.CharField(u"Tipus", max_length=1, choices = TIPUS_CHOICES, help_text = u'''Tipus''', blank = False )
moment = models.DateTimeField(u'Moment Publicació', auto_now_add = True, db_index = True, help_text = u'''Data de publicació d'aquest POST''' )
usuari_post = models.ForeignKey(User, related_name = "posts_publicats")
usuari_darrer_canvi = models.ForeignKey(User, related_name = "posts_modificats")
cicles = models.ManyToManyField( Cicle )
unitats_formatives = models.ManyToManyField( UnitatFormativa )
continguts = models.ManyToManyField( Contingut )
esborrat = models.BooleanField( u"Post Esborrat", default = False, blank = False )
nVotsPositius = models.IntegerField( u"Vots Positius", default = 0, blank = False )
nVotsNegatius = models.IntegerField( u"Vots Negatius", default = 0, blank = False )
slug = models.SlugField(db_index = True, unique = True)
def save(self, *args, **kwargs):
self.slug = self.slug if self.slug else self.my_slug()
super(Post, self).save(*args, **kwargs)
def my_slug(self):
slug_txt = self.titol
return slugify( slug_txt )
class Meta:
ordering=['-moment']
db_table = u'posts'
verbose_name = u'Post'
verbose_name_plural = u'Posts'
def __unicode__(self):
return u"{0}".format( self.titol )
class HistorialPost(models.Model):
post = models.ForeignKey( Post, db_index = True )
usuari_canvi = models.ForeignKey(User)
moment_canvi = models.DateTimeField(u'Moment Canvi', auto_now_add = True, db_index = True, help_text = u'''Data de modificació del post''' )
titol_bkup = models.CharField(u"Títol", max_length=250, help_text = u'''Títol''', blank = False, unique = True )
cos_bkup = models.TextField(u"Cos", help_text = u'''Cos del post''', blank = False )
tipus_bkup = models.CharField(u"Tipus", max_length=1, choices = Post.TIPUS_CHOICES, help_text = u'''Tipus''', blank = False )
cicles_bkup = models.ManyToManyField( Cicle )
moduls_professionals_bkup = models.ManyToManyField( ModulProfessional )
unitats_formatives_bkup = models.ManyToManyField( UnitatFormativa )
continguts_bkup = models.ManyToManyField( Contingut )
esborrat_bkup = models.BooleanField( u"Post Esborrat", default = False, blank = False )
class Meta:
ordering=['post','-moment_canvi']
db_table = u'posts_historial'
verbose_name = u'Mòdul Professional'
verbose_name_plural = u'Mòduls Professional'
def __unicode__(self):
return u"{0}".format( self.titol_bkup )
class Comentaris(models.Model):
post = models.ForeignKey( Post, db_index = True )
texte = models.TextField(u"Comentari", help_text = u'''Comentari''', blank = False )
usuari_comenta = models.ForeignKey(User)
moment_comentari = models.DateTimeField(u'Moment Comentari', auto_now_add = True, help_text = u'''Data del comentari''' )
nVotsPositius = models.IntegerField( u"Vots Positius", default = 0, blank = False )
class Meta:
ordering=['post','moment_comentari']
db_table = u'comentaris'
verbose_name = u'Comentari'
verbose_name_plural = u'Comentaris'
def __unicode__(self):
return u"{0}-{1}".format( self.usuari_comenta, self.texte )
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
| Python |
from fp2cat.settings import SITE_ROOT
DEBUG = True
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
# 'NAME': 'fp2catdb',
# 'USER': 'fp2cat',
# 'PASSWORD': 'i',
# 'HOST': '',
# 'PORT': '',
# }
#}
import os
SITE_TMP = os.path.join(SITE_ROOT, 'tmp2')
| Python |
from django.conf.urls import patterns, include
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'utils.views.about'),
(r'^about/$', 'utils.views.about'),
#(r'^correus/', include('cicles.urls')),
)
| Python |
# This Python file uses the following encoding: utf-8
DEBUG = False
TEMPLATE_DEBUG = DEBUG
import os, sys
SITE_ROOT = os.path.join( os.path.dirname(os.path.realpath(__file__)), '../')
SITE_TMP = '/tmp/'
ADMINS = (
('dani herrera', 'ctrl.alt.d@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(SITE_ROOT, 'db-test/data.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Madrid'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'ca_ES'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 't%ulqvm09*=zot14llsn@0uriiwxg^zie&_+k^yi^rc=gb4ys!'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'utils.middleware.NoCacheMiddleware',
#'utils.middleware.timeOutMiddleware',
'utils.middleware.IncludeLoginInErrors',
)
ROOT_URLCONF = 'fp2cat.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'fp2cat.wsgi.application'
TEMPLATE_DIRS = (
os.path.join( SITE_ROOT , 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'cicles',
'curriculums',
'posts',
'usuaris',
'utils',
'vots',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
#-----------------------------------------
AUTH_PROFILE_MODULE = 'usuaris.Perfil'
#------------------------------ my settings ------------------
LOGIN_URL="/usuaris/login"
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
#https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.csrf",
'utils.context_processors.dades_basiques',
)
DATE_INPUT_FORMATS=('%d/%m/%Y','%Y-%m-%d')
DATETIME_INPUT_FORMATS= ('%d/%m/%Y %H:%M','%d/%m/%Y %H:%M:%S',
'%d-%m-%Y %H:%M','%d-%m-%Y %H:%M:%S',)
#---------------------------------------------
MANAGERS = ADMINS
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='ctrl.alt.d@gmail.com'
EMAIL_HOST_PASSWORD='XXXXXXXXXXXXXXXXXX'
EMAIL_PORT=587
EMAIL_USE_TLS=True
SERVER_EMAIL='ctrl.alt.d@gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#--------------------------------------------
try:
from settings_pri import *
except ImportError:
print 'you should create your own settings_pri.py with private data'
try:
from settings_dev import *
except ImportError:
print 'en produccio'
try:
from settings_prod import *
except ImportError:
print 'ERROR: Cal entorn de desenvolupament o de producció!'
| Python |
"""
WSGI config for fp2cat project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fp2cat.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from cicles.models import Cicle
from django.template.defaultfilters import slugify
class ModulProfessional(models.Model):
cicle = models.ForeignKey( Cicle, db_index = True )
numero = models.IntegerField(u"Número", help_text = u'''Número del Mòdul Professional. Ex: 3 per a MP03''', blank = False )
nom = models.CharField(u"Nom", max_length=250, help_text = u'''Nom del MP''', blank = False )
logo = models.ImageField(u"Logo", blank=True, null=True, upload_to="moduls", help_text = u"Logo de la Unitat Formativa" )
slug = models.SlugField(db_index = True, unique = True)
def save(self, *args, **kwargs):
self.slug = self.slug if self.slug else self.my_slug()
super(ModulProfessional, self).save(*args, **kwargs)
def my_slug(self):
slug_cicle = self.cicle.codi if self.cicle else ''
slug_txt = slug_cicle + '-' + unicode( self ) if slug_cicle else ''
return slugify( slug_txt )
class Meta:
ordering=['cicle','numero']
db_table = u'moduls_professionals'
verbose_name = u'Mòdul Professional'
verbose_name_plural = u'Mòduls Professional'
def __unicode__(self):
return u"MP-{0}".format( self.numero )
class UnitatFormativa(models.Model):
modul_professional = models.ForeignKey( ModulProfessional, db_index = True )
numero = models.IntegerField(u"Número", help_text = u'''Número de Unitat Formativa. Ex: 3 per a UF3''', blank = False )
nom = models.CharField(u"Nom", max_length=250, help_text = u'''Nom de la Unitat Formativa''', blank = False )
logo = models.ImageField(u"Logo", blank=True, null=True, upload_to="unitats", help_text = u"Logo de la Unitat Formativa" )
slug = models.SlugField(db_index = True, unique = True)
def save(self, *args, **kwargs):
self.slug = self.slug if self.slug else self.my_slug()
super(UnitatFormativa, self).save(*args, **kwargs)
def my_slug(self):
slug_mp = self.modul_professional.my_slug( )
slug_txt = slug_mp + '-' + u'UF{0}'+format( self.numero ) if slug_mp else ''
return slugify( slug_txt )
class Meta:
ordering=['modul_professional','numero']
db_table = u'unitats_formatives'
verbose_name = u'Unitat Formativa'
verbose_name_plural = u'Unitats Formativa'
def __unicode__(self):
return u"UF-{0}".format( self.numero )
class Contingut(models.Model):
unitat_formativa = models.ForeignKey( UnitatFormativa, db_index = True )
codi = models.CharField(u"Codi", max_length=10, help_text = u'''Codi de contingut.''', blank = False )
descripcio = models.CharField(u"Descripció", max_length=250, help_text = u'''Descripció del contingut''', blank = False )
class Meta:
ordering=['codi']
db_table = u'continguts'
verbose_name = u'Contingut'
verbose_name_plural = u'Continguts'
def __unicode__(self):
return u"{0} - {1}".format( self.codi, self.descripcio )
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from django.contrib.auth.models import User
from cicles.models import Cicle
from curriculums.models import ModulProfessional, UnitatFormativa
class Perfil(models.Model):
usuari = models.OneToOneField( User, db_index = True )
unitats_formatives_preferides = models.ManyToManyField( UnitatFormativa )
avatar = models.URLField( u'Avatar from gravatar', max_length = 300 , blank = True)
class Meta:
db_table = u'pefils_d_usuari'
verbose_name = u'Perfil'
verbose_name_plural = u'Perfils'
#------------------------------------------------------------------------
#https://docs.djangoproject.com/en/1.4/topics/auth/#storing-additional-information-about-users
from django.db.models.signals import post_save
def crea_perfil_d_usuari(sender, instance, created, **kwargs):
if created:
Perfil.objects.create(usuari=instance)
post_save.connect(crea_perfil_d_usuari, sender=User)
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
| Python |
# This Python file uses the following encoding: utf-8
from django.db import models
from django.contrib.auth.models import User
from posts.models import Post
class VotPositiu(models.Model):
usuari = models.ForeignKey( User )
post = models.ForeignKey( Post )
data = models.DateTimeField(u'Moment votació', auto_now_add = True )
class Meta:
unique_together = (("usuari", "post"),)
db_table = u'vots_positius'
verbose_name = u'Vot+'
verbose_name_plural = u'Vots+'
class VotNegatiu(models.Model):
usuari = models.ForeignKey( User )
post = models.ForeignKey( Post )
data = models.DateTimeField(u'Moment votació', auto_now_add = True )
class Meta:
unique_together = (("usuari", "post"),)
db_table = u'vots_negatius'
verbose_name = u'Vot-'
verbose_name_plural = u'Vots-'
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
| Python |
#!/usr/bin/env python
# To run this script, use Python version 2.7 not version 3.x
import argparse
import struct
#Standard SST25VF040B FLASH size of 4Mbits
flash_size = 4*1024*1024/8
#Standard size of bitstream for a Spartan 6 LX9
bit_size = 340*1024
parser = argparse.ArgumentParser(description='Concatenates an FPGA .bit file and a user supplied binary file together.\nProduces a valid .bit file that can be written to a platform flash using\nstandard tools.')
parser.add_argument('ifile', type=argparse.FileType('rb'), help='source FPGA .bit file')
parser.add_argument('bfile', type=argparse.FileType('rb'), help='source binary file')
parser.add_argument('ofile', type=argparse.FileType('wb'), help='destination merged FPGA .bit + binary file')
args = parser.parse_args()
#seek to end
args.bfile.seek(0,2)
#get size of user binary file to merge
bsize = args.bfile.tell()
#seek to start
args.bfile.seek(0,0)
data = args.ifile.read(2)
args.ofile.write(data)
(length,) = struct.unpack(">H", data)
assert length == 9, "Invalid .bit file magic length."
#check bit file magic marker
data = args.ifile.read(length)
args.ofile.write(data)
(n1,n2,n3,n4,n5,) = struct.unpack("<HHHHB", data)
assert n1==n2==n3==n4==0xF00F, "Invalid .bit file magic marker"
data = args.ifile.read(2)
args.ofile.write(data)
(length,) = struct.unpack(">H", data)
assert length==1, "Unexpected value."
#loop through the bit file sections 'a' through 'd' and print out stats
section=""
while section != 'd':
section = args.ifile.read(1)
args.ofile.write(section)
data = args.ifile.read(2)
args.ofile.write(data)
(length,) = struct.unpack(">H", data)
desc = args.ifile.read(length)
args.ofile.write(desc)
print "Section '%c' (size %6d) '%s'" % (section, length, desc)
#process section 'e' (main bit file data)
section = args.ifile.read(1)
args.ofile.write(section)
assert section=="e", "Unexpected section"
data = args.ifile.read(4)
#this is the actual size of the FPGA bit stream contents
(length,) = struct.unpack(">L", data)
print "Section '%c' (size %6d) '%s'" % (section, length, "FPGA bitstream")
#we can't merge a "merged" file, well..., we could, but we won't
assert length<=bit_size, "Section 'e' length of %d seems unreasonably long\nCould this file have already been merged with a binary file?" %length
#check that both files will fit in flash
assert (length+bsize) <= flash_size, "Combined files sizes of %d would exceed flash capacity of %d bytes" % ((length+bsize), flash_size)
print "Merged user data begins at FLASH address 0x%06X" %length
#write recalculated section length
data = struct.pack(">L", length+bsize)
args.ofile.write(data)
#read FPGA bitstream and write to output file
data = args.ifile.read(length)
args.ofile.write(data)
#read user provided binary data and append to file
data = args.bfile.read(bsize)
args.ofile.write(data)
#close up files and exit
args.ifile.close()
args.bfile.close()
args.ofile.close()
| Python |
#!/usr/bin/env python
# To run this script, use Python version 2.7 not version 3.x
import argparse
import struct
#Standard SST25VF040B FLASH size of 4Mbits
flash_size = 4*1024*1024/8
#Standard size of bitstream for a Spartan 6 LX9
bit_size = 340*1024
parser = argparse.ArgumentParser(description='Concatenates an FPGA .bit file and a user supplied binary file together.\nProduces a valid .bit file that can be written to a platform flash using\nstandard tools.')
parser.add_argument('ifile', type=argparse.FileType('rb'), help='source FPGA .bit file')
parser.add_argument('bfile', type=argparse.FileType('rb'), help='source binary file')
parser.add_argument('ofile', type=argparse.FileType('wb'), help='destination merged FPGA .bit + binary file')
args = parser.parse_args()
#seek to end
args.bfile.seek(0,2)
#get size of user binary file to merge
bsize = args.bfile.tell()
#seek to start
args.bfile.seek(0,0)
data = args.ifile.read(2)
args.ofile.write(data)
(length,) = struct.unpack(">H", data)
assert length == 9, "Invalid .bit file magic length."
#check bit file magic marker
data = args.ifile.read(length)
args.ofile.write(data)
(n1,n2,n3,n4,n5,) = struct.unpack("<HHHHB", data)
assert n1==n2==n3==n4==0xF00F, "Invalid .bit file magic marker"
data = args.ifile.read(2)
args.ofile.write(data)
(length,) = struct.unpack(">H", data)
assert length==1, "Unexpected value."
#loop through the bit file sections 'a' through 'd' and print out stats
section=""
while section != 'd':
section = args.ifile.read(1)
args.ofile.write(section)
data = args.ifile.read(2)
args.ofile.write(data)
(length,) = struct.unpack(">H", data)
desc = args.ifile.read(length)
args.ofile.write(desc)
print "Section '%c' (size %6d) '%s'" % (section, length, desc)
#process section 'e' (main bit file data)
section = args.ifile.read(1)
args.ofile.write(section)
assert section=="e", "Unexpected section"
data = args.ifile.read(4)
#this is the actual size of the FPGA bit stream contents
(length,) = struct.unpack(">L", data)
print "Section '%c' (size %6d) '%s'" % (section, length, "FPGA bitstream")
#we can't merge a "merged" file, well..., we could, but we won't
assert length<=bit_size, "Section 'e' length of %d seems unreasonably long\nCould this file have already been merged with a binary file?" %length
#check that both files will fit in flash
assert (length+bsize) <= flash_size, "Combined files sizes of %d would exceed flash capacity of %d bytes" % ((length+bsize), flash_size)
print "Merged user data begins at FLASH address 0x%06X" %length
#write recalculated section length
data = struct.pack(">L", length+bsize)
args.ofile.write(data)
#read FPGA bitstream and write to output file
data = args.ifile.read(length)
args.ofile.write(data)
#read user provided binary data and append to file
data = args.bfile.read(bsize)
args.ofile.write(data)
#close up files and exit
args.ifile.close()
args.bfile.close()
args.ofile.close()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Inicializador del programa. Levanta la ventana principal y el entorno
necesario
"""
import wx
import sys
class main():
def __init__(self):
self.app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
self.frame_1 = MainFrame(None, -1, "")
#frame_1.actionRefreshControl(None)
#frame_1.actionRefreshStatus(None)
self.frame_1.actionRefreshAll(None)
self.app.SetTopWindow(self.frame_1)
self.frame_1.Show()
self.app.MainLoop()
if __name__ == "__main__":
try:
main()
except NameError:
print u'FPU Inspector requiere Python 2.6 o superior para funcionar'
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
>>> import wrapper
>>> w = wrapper.Wrapper()
Caso de prueba 1:
- la pila inicialmente tiene valores no númericos
>>> res = w.get_stack()
[nan, nan, nan, nan, nan, nan, nan, nan]
Caso de prueba 2:
- ingresamos algunos valores al stack mediante FLD
>>> w.FLD(3)
>>> w.FLD(5.0)
>>> w.FLD(18.3)
>>> res = w.get_stack() #doctest: +ELLIPSIS
[18.300..., 5.0, 3.0, nan, nan, nan, nan, nan]
Caso de prueba 3:
- Al pedir la pila consecutivamente los valores deben ser los mismos
>>> res = w.get_stack() #doctest: +ELLIPSIS
[18.300..., 5.0, 3.0, nan, nan, nan, nan, nan]
Caso de prueba:
- Instruccion FADD
>>> w.FADD()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[23.300..., 3.0, nan, nan, nan, nan, nan, nan]
Caso de prueba: Raiz cuadrada
>>> w.FSQRT()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[4.827..., 3.0, nan, nan, nan, nan, nan, nan]
Caso de prueba: FSUB
>>> w.FSUB()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[1.827..., nan, nan, nan, nan, nan, nan, nan]
caso de prueba: FLDxx (constantes)
>>> w.FLD1()
>>> w.FLDL2E()
>>> w.FLDL2T()
>>> w.FLDLG2()
>>> res = w.get_stack()
[0.3010299956639812, 3.3219280948873622, 1.4426950408889634, 1.0, nan, nan, nan, nan]
Caso de prueba:
- Almacenar más de 8 valores en la pila
>>> for i in range(8):
... w.FLD(1.0)
...
>>> w.FLD(2.1)
>>> res = w.get_stack() #doctest: +ELLIPSIS
[2.10..., 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
>>>
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
>>> import wrapper
>>> w = wrapper.Wrapper()
caso de prueba: FLDxx (constantes)
>>> w.FLD1()
>>> w.FLDL2E()
>>> w.FLDL2T()
>>> w.FLDLG2()
>>> w.FLDZ()
>>> w.FLDPI()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[3.14159..., 0.0, 0.30102..., 3.32192..., 1.44269..., 1.0, nan, nan]
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
>>> import wrapper
>>> w = wrapper.Wrapper()
caso de prueba: FLDxx (constantes)
>>> w.FLD1()
>>> w.FLDL2E()
>>> w.FLDL2T()
>>> w.FLDLG2()
>>> w.FLDZ()
>>> w.FLDPI()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[3.14159..., 0.0, 0.30102..., 3.32192..., 1.44269..., 1.0, nan, nan]
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Inicializador del programa. Levanta la ventana principal y el entorno
necesario
"""
import wx
import sys
class main():
def __init__(self):
self.app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
self.frame_1 = MainFrame(None, -1, "")
#frame_1.actionRefreshControl(None)
#frame_1.actionRefreshStatus(None)
self.frame_1.actionRefreshAll(None)
self.app.SetTopWindow(self.frame_1)
self.frame_1.Show()
self.app.MainLoop()
if __name__ == "__main__":
try:
main()
except NameError:
print u'FPU Inspector requiere Python 2.6 o superior para funcionar'
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
>>> import wrapper
>>> w = wrapper.Wrapper()
Caso de prueba 1:
- la pila inicialmente tiene valores no númericos
>>> res = w.get_stack()
[nan, nan, nan, nan, nan, nan, nan, nan]
Caso de prueba 2:
- ingresamos algunos valores al stack mediante FLD
>>> w.FLD(3)
>>> w.FLD(5.0)
>>> w.FLD(18.3)
>>> res = w.get_stack() #doctest: +ELLIPSIS
[18.300..., 5.0, 3.0, nan, nan, nan, nan, nan]
Caso de prueba 3:
- Al pedir la pila consecutivamente los valores deben ser los mismos
>>> res = w.get_stack() #doctest: +ELLIPSIS
[18.300..., 5.0, 3.0, nan, nan, nan, nan, nan]
Caso de prueba:
- Instruccion FADD
>>> w.FADD()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[23.300..., 3.0, nan, nan, nan, nan, nan, nan]
Caso de prueba: Raiz cuadrada
>>> w.FSQRT()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[4.827..., 3.0, nan, nan, nan, nan, nan, nan]
Caso de prueba: FSUB
>>> w.FSUB()
>>> res = w.get_stack() #doctest: +ELLIPSIS
[1.827..., nan, nan, nan, nan, nan, nan, nan]
caso de prueba: FLDxx (constantes)
>>> w.FLD1()
>>> w.FLDL2E()
>>> w.FLDL2T()
>>> w.FLDLG2()
>>> res = w.get_stack()
[0.3010299956639812, 3.3219280948873622, 1.4426950408889634, 1.0, nan, nan, nan, nan]
Caso de prueba:
- Almacenar más de 8 valores en la pila
>>> for i in range(8):
... w.FLD(1.0)
...
>>> w.FLD(2.1)
>>> res = w.get_stack() #doctest: +ELLIPSIS
[2.10..., 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
>>>
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import os
_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "A":"1010", "B":"1011",
"C":"1100", "D":"1101", "E":"1110", "F":"1111",
"-":"-"}
def toBase2(number):
"""toBase2(number): given an int/long, converts it to
a string containing the number in base 2."""
# From a suggestion by Dennis Lee Bieber.
if number == 0:
return "0"
result = [_nibbles[nibble] for nibble in "%X"%number]
result[number<0] = result[number<0].lstrip("0")
result.reverse()
return result
def int2bin(n):
'''converts denary integer n to binary list
[MSB,....,LSB]
'''
b = []
if n < 0: raise ValueError, "must be positive"
if n == 0: return [0]
while n > 0:
b.append(n % 2)
n = n >> 1
while len(b)<16:
b.append(0)
b.reverse()
return b
def get_svn_revision(path=None):
rev = None
if path is None:
path = os.path.dirname( __file__ )# __path__[0]
entries_path = '%s/.svn/entries' % path
if os.path.exists(entries_path):
entries = open(entries_path, 'r').read()
# Versions >= 7 of the entries file are flat text. The first line is
# the version number. The next set of digits after 'dir' is the revision.
if re.match('(\d+)', entries):
rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
if rev_match:
rev = rev_match.groups()[0]
# Older XML versions of the file specify revision as an attribute of
# the first entries node.
else:
from xml.dom import minidom
dom = minidom.parse(entries_path)
rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
if rev:
return u' SVN-%s' % rev
return u'1.0'
class BufferStack():
def __init__(self):
self.fhdir = u"%s/stack.tmp" % os.path.abspath(os.path.dirname(__file__))
def set_stack_from_file(self):
fh = open(self.fhdir, 'r')
stack = pickle.load(fh)
set_stack(stack)
fh.close()
def get_stack_to_file(self):
stack = [v for v in self.get_stack()]
fh = open(self.fhdir, 'w')
stack = pickle.dump(stack, fh)
fh.close()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Este módulo contiene diferentes clases que sobrecargar o agregan comportamientos
a los controles (widgets) estándar de Wx.
Por ejemplo, InstructionListCtrl incorpora métodos que manipulan el orden
de las filas (las intrucciones). También recibe un diccionario con el que asigna
un ToolTip diferente para cada fila en función de la primera palabra (la intrucción
ASM que se haya ingresado).
TextCrlAutoComplete es la clase que se instancia para la caja de texto desde
donde se ingresan las intrucciones. Fue escrito por Edward Flick y otros.
Se le asigna una lista (un diccionario en nuestro caso) de cadenas ingresadas válidas
y produce un efecto de 'autocompleción' a medida que el usuario teclea
RegisterListCtrl permite asignar tooltips diferentes por columna, para describir
la función de cada bit de los registros Control y Estado.
"""
import wx
class InstructionListCtrl(wx.ListCtrl):
"""widget List que permite seleccionar y mover filas"""
def __init__(self, parent, ID, pos=wx.DefaultPosition,size=wx.DefaultSize, style=0, tooltips=None):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
#self.statusbar = statusbar
self.Bind(wx.EVT_MOTION, self.updateToolTip)
self.tooltips = tooltips
def get_list(self):
"""devuelve una lista de items de un list control"""
list = []
row = []
for nrow in range(self.GetItemCount()):
row = []
for ncol in range(1):
row.append(self.GetItem(nrow,ncol).GetText())
list.append(row)
return list
def select_next(self, current):
next = []
if current + 1 <= self.GetItemCount():
next.append(current + 1)
self.updateList(self.get_list(), next)
def get_selected_items(self):
"""
Gets the selected items for the list control.
Selection is returned as a list of selected indices,
low to high.
"""
selection = []
# start at -1 to get the first selected item
current = -1
while True:
next = self.GetNextSelected(current)
if next == -1:
return selection
selection.append(next)
current = next
def num_selected_items(self):
return len(self.get_selected_items())
def GetNextSelected(self, current):
"""Returns next selected item, or -1 when no more"""
return self.GetNextItem(current,
wx.LIST_NEXT_ALL,
wx.LIST_STATE_SELECTED)
def updateList(self, list, selected=[]):
"""reeplaza las intrucciones dadas por list y marca como seleccionadas
las que se indiquen en selected"""
self.DeleteAllItems()
for row in list:
self.Append(row)
for sel in selected:
self.SetItemState(sel, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
def move_up(self):
"""sube un nivel las filas seleccionadas"""
selected = self.get_selected_items()
if len(selected) == 0:
self.statusbar.SetStatusText("no hay instrucciones seleccionadas", 0)
return
list = self.get_list()
for sel in selected:
if sel != 0:
item = list.pop(sel)
list.insert(sel-1,item)
newselected = [sel-1 for sel in selected if sel != 0]
self.updateList(list, newselected)
def updateToolTip(self, event):
(x,y) = event.GetPosition()
alto_fila = 22 #self.GetSize().GetHeight()/self.GetItemCount()
fila = y/alto_fila
#print y, alto_fila, fila
instruc = self.GetItem(fila,0).GetText()
try:
instruc = instruc.split()[0]
self.SetToolTipString(self.tooltips[instruc])
except:
pass
def move_top(self):
"""agrupa y sube las intrucciones al tope de la lista"""
selected = self.get_selected_items()
if len(selected) == 0:
self.statusbar.SetStatusText("no hay instrucciones seleccionadas", 0)
return
lista = self.get_list()
for sel in selected:
if sel != 0:
item = lista.pop(sel)
lista.insert(selected.index(sel),item)
newselected = [i for i in range(self.num_selected_items())]
self.updateList(lista, newselected)
def move_down(self):
"""sube un nivel las filas seleccionadas"""
selected = self.get_selected_items()
lista = self.get_list()
last = self.GetItemCount() - 1
for sel in selected:
if sel != last:
item = lista.pop(sel)
lista.insert(sel+1,item)
self.updateList(lista)
newselected = [sel+1 for sel in selected if sel != last]
self.updateList(lista, newselected)
def move_bottom(self):
"""agrupa y sube las instrucciones al tope de la lista"""
selected = self.get_selected_items()
lista = self.get_list()
last = self.GetItemCount() - 1
for sel in selected:
if sel != last:
item = lista.pop(sel)
lista.append(item)
newselected = [self.self.GetItemCount()-i for i in range(self.num_selected_items())]
self.updateList(lista, newselected)
def delete(self):
"""elimina las instrucciones seleccionadas"""
selected = self.get_selected_items()
lista = self.get_list()
for sel in selected:
lista.pop(sel)
self.updateList(lista)
class RegisterListCtrl(wx.ListCtrl):
"""widget de lista que actualiza su tooltip en función de la columna"""
def __init__(self, parent, ID, pos=wx.DefaultPosition,size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
self.Bind(wx.EVT_MOTION, self.updateToolTip)
def SetColumns(self, columnas, width=30):
columnas.reverse()
self.columnas = columnas
self.width = width
for n,col in enumerate(columnas):
self.InsertColumn(n,col[0], format=wx.LIST_FORMAT_CENTER)
self.SetColumnWidth(n,width)
def updateToolTip(self, event):
(x,y) = event.GetPosition()
col = x/self.width
self.SetToolTipString(u"%s: %s" % (self.columnas[col][1],self.columnas[col][2]))
'''
wxPython Custom Widget Collection 20060207
Written By: Edward Flick (eddy -=at=- cdf-imaging -=dot=- com)
Michele Petrazzo (michele -=dot=- petrazzo -=at=- unipex -=dot=- it)
Will Sadkin (wsadkin-=at=- nameconnector -=dot=- com)
Copyright 2006 (c) CDF Inc. ( http://www.cdf-imaging.com )
Contributed to the wxPython project under the wxPython project's license.
'''
import locale, wx, sys, cStringIO
import wx.lib.mixins.listctrl as listmix
from wx import ImageFromStream, BitmapFromImage
#----------------------------------------------------------------------
def getSmallUpArrowData():
return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00<IDAT8\x8dcddbf\xa0\x040Q\xa4{h\x18\xf0\xff\xdf\xdf\xffd\x1b\x00\xd3\
\x8c\xcf\x10\x9c\x06\xa0k\xc2e\x08m\xc2\x00\x97m\xd8\xc41\x0c \x14h\xe8\xf2\
\x8c\xa3)q\x10\x18\x00\x00R\xd8#\xec\xb2\xcd\xc1Y\x00\x00\x00\x00IEND\xaeB`\
\x82'
def getSmallUpArrowBitmap():
return BitmapFromImage(getSmallUpArrowImage())
def getSmallUpArrowImage():
stream = cStringIO.StringIO(getSmallUpArrowData())
return ImageFromStream(stream)
def getSmallDnArrowData():
return \
"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00HIDAT8\x8dcddbf\xa0\x040Q\xa4{\xd4\x00\x06\x06\x06\x06\x06\x16t\x81\
\xff\xff\xfe\xfe'\xa4\x89\x91\x89\x99\x11\xa7\x0b\x90%\ti\xc6j\x00>C\xb0\x89\
\xd3.\x10\xd1m\xc3\xe5*\xbc.\x80i\xc2\x17.\x8c\xa3y\x81\x01\x00\xa1\x0e\x04e\
?\x84B\xef\x00\x00\x00\x00IEND\xaeB`\x82"
def getSmallDnArrowBitmap():
return BitmapFromImage(getSmallDnArrowImage())
def getSmallDnArrowImage():
stream = cStringIO.StringIO(getSmallDnArrowData())
return ImageFromStream(stream)
#----------------------------------------------------------------------
class myListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent, ID=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.ListCtrlAutoWidthMixin.__init__(self)
class TextCtrlAutoComplete (wx.TextCtrl, listmix.ColumnSorterMixin ):
"""Código tomado de http://wiki.wxpython.org/TextCtrlAutoComplete"""
def __init__ ( self, parent, colNames=None, choices = None,
multiChoices=None, showHead=True, dropDownClick=True,
colFetch=-1, colSearch=0, hideOnNoMatch=True,
selectCallback=None, entryCallback=None, matchFunction=None,
**therest) :
'''
Constructor works just like wx.TextCtrl except you can pass in a
list of choices. You can also change the choice list at any time
by calling setChoices.
'''
if therest.has_key('style'):
therest['style']=wx.TE_PROCESS_ENTER | therest['style']
else:
therest['style']=wx.TE_PROCESS_ENTER
wx.TextCtrl.__init__(self, parent, **therest )
#Some variables
self._dropDownClick = dropDownClick
self._colNames = colNames
self._multiChoices = multiChoices
self._showHead = showHead
self._choices = choices.keys()
self._lastinsertionpoint = 0
self._hideOnNoMatch = hideOnNoMatch
self._selectCallback = selectCallback
self._entryCallback = entryCallback
self._matchFunction = matchFunction
self._screenheight = wx.SystemSettings.GetMetric( wx.SYS_SCREEN_Y )
#sort variable needed by listmix
self.itemDataMap = dict()
#Load and sort data
if not (self._multiChoices or self._choices):
raise ValueError, "Pass me at least one of multiChoices OR choices"
#widgets
self.dropdown = wx.PopupWindow( self )
#Control the style
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING
if not (showHead and multiChoices) :
flags = flags | wx.LC_NO_HEADER
#Create the list and bind the events
self.dropdownlistbox = myListCtrl( self.dropdown, style=flags,
pos=wx.Point( 0, 0) )
#initialize the parent
if multiChoices: ln = len(multiChoices)
else: ln = 1
#else: ln = len(choices)
listmix.ColumnSorterMixin.__init__(self, ln)
#load the data
if multiChoices: self.SetMultipleChoices (multiChoices, colSearch=colSearch, colFetch=colFetch)
else: self.SetChoices ( self._choices )
gp = self
while ( gp != None ) :
gp.Bind ( wx.EVT_MOVE , self.onControlChanged, gp )
gp.Bind ( wx.EVT_SIZE , self.onControlChanged, gp )
gp = gp.GetParent()
self.Bind( wx.EVT_KILL_FOCUS, self.onControlChanged, self )
self.Bind( wx.EVT_TEXT , self.onEnteredText, self )
self.Bind( wx.EVT_KEY_DOWN , self.onKeyDown, self )
#If need drop down on left click
if dropDownClick:
self.Bind ( wx.EVT_LEFT_DOWN , self.onClickToggleDown, self )
self.Bind ( wx.EVT_LEFT_UP , self.onClickToggleUp, self )
self.dropdown.Bind( wx.EVT_LISTBOX , self.onListItemSelected, self.dropdownlistbox )
self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.onListClick)
self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.onListDClick)
self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.onListColClick)
self.il = wx.ImageList(16, 16)
self.sm_dn = self.il.Add(getSmallDnArrowBitmap())
self.sm_up = self.il.Add(getSmallUpArrowBitmap())
self.dropdownlistbox.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
self._ascending = True
#-- methods called from mixin class
def GetSortImages(self):
return (self.sm_dn, self.sm_up)
def GetListCtrl(self):
return self.dropdownlistbox
# -- event methods
def onListClick(self, evt):
toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
#no values on poition, return
if toSel == -1: return
self.dropdownlistbox.Select(toSel)
def onListDClick(self, evt):
self._setValueFromSelected()
def onListColClick(self, evt):
col = evt.GetColumn()
#reverse the sort
if col == self._colSearch:
self._ascending = not self._ascending
self.SortListItems( evt.GetColumn(), ascending=self._ascending )
self._colSearch = evt.GetColumn()
evt.Skip()
def onEnteredText(self, event):
text = event.GetString()
if self._entryCallback:
self._entryCallback()
if not text:
# control is empty; hide dropdown if shown:
if self.dropdown.IsShown():
self._showDropDown(False)
event.Skip()
return
found = False
if self._multiChoices:
#load the sorted data into the listbox
dd = self.dropdownlistbox
choices = [dd.GetItem(x, self._colSearch).GetText()
for x in xrange(dd.GetItemCount())]
else:
choices = self._choices
for numCh, choice in enumerate(choices):
if self._matchFunction and self._matchFunction(text, choice):
found = True
elif choice.lower().startswith(text.lower()) :
found = True
if found:
self._showDropDown(True)
item = self.dropdownlistbox.GetItem(numCh)
toSel = item.GetId()
self.dropdownlistbox.Select(toSel)
break
if not found:
self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
if self._hideOnNoMatch:
self._showDropDown(False)
self._listItemVisible()
event.Skip ()
def onKeyDown ( self, event ) :
""" Do some work when the user press on the keys:
up and down: move the cursor
left and right: move the search
"""
skip = True
sel = self.dropdownlistbox.GetFirstSelected()
visible = self.dropdown.IsShown()
KC = event.GetKeyCode()
if KC == wx.WXK_DOWN :
if sel < (self.dropdownlistbox.GetItemCount () - 1) :
self.dropdownlistbox.Select ( sel+1 )
self._listItemVisible()
self._showDropDown ()
skip = False
elif KC == wx.WXK_UP :
if sel > 0 :
self.dropdownlistbox.Select ( sel - 1 )
self._listItemVisible()
self._showDropDown ()
skip = False
elif KC == wx.WXK_LEFT :
if not self._multiChoices: return
if self._colSearch > 0:
self._colSearch -=1
self._showDropDown ()
elif KC == wx.WXK_RIGHT:
if not self._multiChoices: return
if self._colSearch < self.dropdownlistbox.GetColumnCount() -1:
self._colSearch += 1
self._showDropDown()
if visible :
if event.GetKeyCode() == wx.WXK_RETURN :
self._setValueFromSelected()
skip = False
if event.GetKeyCode() == wx.WXK_ESCAPE :
self._showDropDown( False )
skip = False
if skip :
event.Skip()
def onListItemSelected (self, event):
self._setValueFromSelected()
event.Skip()
def onClickToggleDown(self, event):
self._lastinsertionpoint = self.GetInsertionPoint()
event.Skip ()
def onClickToggleUp ( self, event ) :
if ( self.GetInsertionPoint() == self._lastinsertionpoint ) :
self._showDropDown ( not self.dropdown.IsShown() )
event.Skip ()
def onControlChanged(self, event):
self._showDropDown( False )
event.Skip()
# -- Interfaces methods
def SetMultipleChoices(self, choices, colSearch=0, colFetch=-1):
''' Set multi-column choice
'''
self._multiChoices = choices
self._choices = None
if not isinstance(self._multiChoices, list):
self._multiChoices = [ x for x in self._multiChoices]
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING
if not self._showHead:
flags |= wx.LC_NO_HEADER
self.dropdownlistbox.SetWindowStyleFlag(flags)
#prevent errors on "old" systems
if sys.version.startswith("2.3"):
self._multiChoices.sort(lambda x, y: cmp(x[0].lower(), y[0].lower()))
else:
self._multiChoices.sort(key=lambda x: locale.strxfrm(x[0]).lower() )
self._updateDataList(self._multiChoices)
lChoices = len(choices)
if lChoices < 2:
raise ValueError, "You have to pass me a multi-dimension list"
for numCol, rowValues in enumerate(choices[0]):
if self._colNames: colName = self._colNames[numCol]
else: colName = "Select %i" % numCol
self.dropdownlistbox.InsertColumn(numCol, colName)
for numRow, valRow in enumerate(choices):
for numCol, colVal in enumerate(valRow):
if numCol == 0:
index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
self.dropdownlistbox.SetStringItem(index, numCol, colVal)
self.dropdownlistbox.SetItemData(index, numRow)
self._setListSize()
self._colSearch = colSearch
self._colFetch = colFetch
def SetChoices(self, choices):
'''
Sets the choices available in the popup wx.ListBox.
The items will be sorted case insensitively.
'''
self._choices = choices
self._multiChoices = None
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER
self.dropdownlistbox.SetWindowStyleFlag(flags)
if not isinstance(choices, list):
self._choices = [ x for x in choices]
#prevent errors on "old" systems
if sys.version.startswith("2.3"):
self._choices.sort(lambda x, y: cmp(x.lower(), y.lower()))
else:
self._choices.sort(key=lambda x: locale.strxfrm(x).lower())
self._updateDataList(self._choices)
self.dropdownlistbox.InsertColumn(0, "")
for num, colVal in enumerate(self._choices):
index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
self.dropdownlistbox.SetStringItem(index, 0, colVal)
self.dropdownlistbox.SetItemData(index, num)
self._setListSize()
# there is only one choice for both search and fetch if setting a single column:
self._colSearch = 0
self._colFetch = -1
def GetChoices(self):
if self._choices:
return self._choices
else:
return self._multiChoices
def SetSelectCallback(self, cb=None):
self._selectCallback = cb
def SetEntryCallback(self, cb=None):
self._entryCallback = cb
def SetMatchFunction(self, mf=None):
self._matchFunction = mf
#-- Internal methods
def _setValueFromSelected( self ) :
'''
Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
Will do nothing if no item is selected in the wx.ListCtrl.
'''
sel = self.dropdownlistbox.GetFirstSelected()
if sel > -1:
if self._colFetch != -1: col = self._colFetch
else: col = self._colSearch
itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
if self._selectCallback:
dd = self.dropdownlistbox
values = [dd.GetItem(sel, x).GetText()
for x in xrange(dd.GetColumnCount())]
self._selectCallback( values )
self.SetValue (itemtext)
self.SetInsertionPointEnd ()
self.SetSelection ( -1, -1 )
self._showDropDown ( False )
def _showDropDown ( self, show = True ) :
'''
Either display the drop down list (show = True) or hide it (show = False).
'''
if show :
size = self.dropdown.GetSize()
width, height = self . GetSizeTuple()
x, y = self . ClientToScreenXY ( 0, height )
if size.GetWidth() != width :
size.SetWidth(width)
self.dropdown.SetSize(size)
self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
if (y + size.GetHeight()) < self._screenheight :
self.dropdown . SetPosition ( wx.Point(x, y) )
else:
self.dropdown . SetPosition ( wx.Point(x, y - height - size.GetHeight()) )
self.dropdown.Show ( show )
def _listItemVisible( self ) :
'''
Moves the selected item to the top of the list ensuring it is always visible.
'''
toSel = self.dropdownlistbox.GetFirstSelected ()
if toSel == -1: return
self.dropdownlistbox.EnsureVisible( toSel )
def _updateDataList(self, choices):
#delete, if need, all the previous data
if self.dropdownlistbox.GetColumnCount() != 0:
self.dropdownlistbox.DeleteAllColumns()
self.dropdownlistbox.DeleteAllItems()
#and update the dict
if choices:
for numVal, data in enumerate(choices):
self.itemDataMap[numVal] = data
else:
numVal = 0
self.SetColumnCount(numVal)
def _setListSize(self):
if self._multiChoices:
choices = self._multiChoices
else:
choices = self._choices
longest = 0
for choice in choices :
longest = max(len(choice), longest)
longest += 3
itemcount = min( len( choices ) , 7 ) + 2
charheight = self.dropdownlistbox.GetCharHeight()
charwidth = self.dropdownlistbox.GetCharWidth()
self.popupsize = wx.Size( charwidth*longest, charheight*itemcount )
self.dropdownlistbox.SetSize ( self.popupsize )
self.dropdown.SetClientSize( self.popupsize )
if __name__ == '__main__':
pass
| Python |
# -*- coding: utf-8 -*-
"""
Interfaz con la biblioteca dinámica C que es un intermediario hacia rutinas de ensamblador
Cada instrucción de FPU implementada en bajo nivel tiene su acceso desde un objeto Wrapper
Desacople en dos procesos
-------------------------
Para mantener la coherencia del estado interno del procesador, un objeto Wrapper()
se gestiona a través de un proxy de multiproceso, del paquete multiproccess
incorporado en Python 2.6
Del módulo MainFrame podemos ver:
``
import Wrapper
from multiprocessing.managers import BaseManager
class MyManager(BaseManager):
pass
MyManager.register('Wrapper', Wrapper)
manager = MyManager()
manager.start()
lib = self.manager.Wrapper() ``
self.lib es un objeto wrapper, que tiene acceso a todo los métodos de este objeto
pero interfaseado por el objeto manager, que es, en efecto, otro proceso.
De esta manera el objeto wrapper mantiene una coherencia persistente del estado
del FPU y el programa en general (con su GUI, que al menos en linux realiza numerosos cálculos
de punto flotante) otro.
Es el sistema operativo el encargado de entregar a cada proceso su estado previo
cuando el CPU le es asignado, permaneciendo inmune a la interferencia que producen
dos tareas de un mismo proceso.
Brillante esta tarjeta!
Introspección
-------------
Python es un lenguaje interpretado por lo que va 'compilando' a medida que necesita
Esto le permite maneter un total conocimiento de qué es lo que está ejecutando
porque conoce el código.
También hay una distinción entre cadenas de documentación (en general, cada entididad
como Clase, método o función debería tener un string inmediatamente después que la
describa).
A través de la introspección se puede conocer cuales son los métodos que efectivamente
existen en el código y recuperar sus cadenas de documentación.
Eso es lo que hace el método get_valid_instructions(): devuelve todos los métodos
que comienzan con *F* (efe mayúscula, como empiezan todas las instrucciones
de ensamblador de la FPU) y su descripción, que es la línea
entre comilla justo debajo de la definición de cada una.
Esta lista de instrucciones es la que se despliega al usuario como opciones
válidas para que este ingrese y ejecute. A su vez, su descripción (la cadena
de documentación) se asocia en la interfaz como ToolTip de cada fila de la
lista de instrucciones
Con esto tenemos al menos dos ventajas: manetenemos homogeneidad total entre
lo que se mostrará al usuario (la lista de instrucciones válidas implementadas)
con lo que verdaderamente está disponible en el código, y por otro lado
manetenemos el código debidamente comentado y brindamos mejor usabilidad al usuario
sin doble trabajo!
Validación de Instrucciones
---------------------------
El método *run_or_test_instruction* verifica que la intrucción que el usuario
ingresa y posteriormente se ejecutará (se enviará a C y a través de este a ASM)
sea válida.
Para eso utiliza una forma, no poco ingeniosa, idea de Leonardo Rocha en su
_fpu8087sim
Se basa en la sentencia `exec` que permite recibir una "cadena de caracteres"
y la intenta ejecutar como código python. Si la ejecución es exitosa, quiere
decir que lo que el usuario ingresó es válido.
Para evitar que efectivamente se ejecute sobre la FPU una intrucción cuando se
ingresa, en modo Test se agrega una bandera `run=False`. Cada método de intrucción
verifica esta bandera y en caso de ser falso, no realiza ninguna operación.
Ejemplo de flujo:
#. El usuario ingresa 'FINIT'
#. El método convierte esta cadena a `self.FINIT( run=False)` e intenta ejecutarlo
#. Como el metodo FINIT(run=False) no existe en el contexto de la clase Wrapper
el resultado de la ejecución desencadenará una excepción que se canaliza
en el `except` y devuelve False, indicando que la intrucción no es válida
Otro ejemplo:
#. El usuario ingresa 'FLD 3.1416'
#. El método convierte la cadena a `self.FLD(3.1416, run=False)` y ejecuta
#. Como el método está definido y los parámetros son válidos, el resultado es
verdadero.
Este mismo método es el que invoca actionRunNext (en MainFrame.py) pero con
run=True para ejecutar efectivamente las intrucciones.
.. _fpu8087sim : http://code.google.com/p/fpu8087sim
"""
from ctypes import * #para interfaz con C
import platform #para detectar sistema operativo
import inspect #para generar las instrucciones válidas
import os
import pickle
class Wrapper:
def __init__(self):
if platform.system()=='Linux':
self.lib = cdll.LoadLibrary('%s/libfpu.so.1.0' % os.path.abspath(os.path.dirname(__file__)) ) # % os.path.dirname( __file__ ))
elif platform.system()=='Windows':
self.lib = cdll.WinDLL('%s/libfpu.dll' % os.path.abspath(os.path.dirname(__file__)) ) #TODO
def get_control(self):
return self.lib.get_control()
def get_estado(self):
return self.lib.get_estado()
def set_stack_from_file(self):
fh = open('stack.tmp', 'r')
stack = pickle.load(fh)
set_stack(stack)
fh.close()
def get_stack_to_file(self):
stack = [v for v in self.get_stack()]
fh = open('stack.tmp', 'w')
stack = pickle.dump(stack, fh)
fh.close()
def get_stack(self):
"""retorna un array con los valores del stack"""
space = c_double * 8
pila = space()
ok = self.lib.get_pila(pila)
self.set_stack(pila)
return [val for val in pila]
def set_stack(self, stack):
pila_al_vesre = []
for valor in stack:
#print valor
pila_al_vesre.insert(0,valor) #invierto el iterable en una lista
for valor in pila_al_vesre:
self.FLD(valor)
def reset(self):
self.lib.reset()
##### INSTRUCCIONES IMPLEMENTADAS ######
def _FINIT(self,run=True):
#not necessary
"""initialises the FPU to its default state. It flags all registers as empty, although it does not actually change their values. """
if run:
self.lib.finit()
def FFREE(self, n=0, run=True):
"""FFREE marks the given register as being empty."""
if run:
self.lib.ffree(n)
def FLD(self, n=0.0, run=True):
"""loads a floating-point value out of the given register or memory location, and pushes it on the FPU register stack"""
if run:
self.lib.fld(c_double(n))
def _FLDCW(self, n, run=True):
#no devuelve el valor esperado
"""FLDCW loads a 16-bit value out of memory and stores it into the FPU control word (governing things like the rounding mode, the precision, and the exception masks)."""
if run:
self.lib.fldcw(c_int(n))
def FLD1(self, run=True):
if run:
self.lib.fld1()
def FLDL2E(self, run=True):
if run:
self.lib.fldl2e()
def FLDL2T(self, run=True):
if run:
self.lib.fldl2t()
def FLDLG2(self, run=True):
if run:
self.lib.fldlg2()
def FLDLN2(self, run=True):
if run:
self.lib.fldln2()
def FLDPI(self, run=True):
if run:
self.lib.fldpi()
def FLDZ(self, run=True):
if run:
self.lib.fldz()
def FCOM(self, n=0, run=True):
"""FCOM compares ST0 with the given operand, and sets the FPU flags accordingly. ST0 is treated as the left-hand side of the comparison, so that the carry flag is set (for a "less-than" result) if ST0 is less than the given operand. """
if run:
self.lib.fcom(n)
def FXCH(self, n=0, run=True):
"""FXCH exchanges ST0 with a given FPU register. The no-operand form exchanges ST0 with ST1."""
if run:
self.lib.fxch(n)
def FCLEX(self, run=True):
"""FCLEX clears any floating-point exceptions which may be pending."""
if run:
self.lib.fclex()
def FCHS(self, run=True):
"""FCHS negates the number in ST0: negative numbers become positive, and vice versa. """
if run:
self.lib.fabs_()
def FABS(self, run=True):
"""FABS computes the absolute value of ST0, storing the result back in ST0. """
if run:
self.lib.fabs()
def FPREM(self, run=True):
"""FPREM produce the remainder obtained by dividing ST0 by ST1. """
if run:
self.lib.fprem()
def FSCALE(self, run=True):
"""FSCALE scales a number by a power of two: it rounds ST1 towards zero
to obtain an integer, then multiplies ST0 by two to the power of that integer,
and stores the result in ST0. """
if run:
self.lib.fscale()
def FADD(self, n=1, run=True):
"""performs the sum between st0 and st1 and stores the result in st0"""
if run:
self.lib.fadd()
def FXTRACT(self, run=True):
"""FXTRACT separates the number in ST0 into its exponent and significand
(mantissa), stores the exponent back into ST0, and then pushes the significand
on the register stack
(so that the significand ends up in ST0, and the exponent in ST1). """
if run:
self.lib.fxtract()
def _FADDP(self, n=1, run=True):
#not yet implemented
"""performs the same function as FADD, but pops the register stack after storing the result."""
if run:
self.lib.faddp(n)
def FSUB(self, run=True):
"""performs the rest between st0 and st1 and stores the result in st0"""
if run:
self.lib.fsub()
def FMUL(self, run=True):
"""FMUL multiplies ST0 by the given operand, and stores the result in ST0"""
if run:
self.lib.fmul()
def FDIV(self, run=True):
"""FDIV divides ST0 by the given operand and stores the result back in ST0,"""
if run:
self.lib.fdiv()
def _FSUBP(self, n=1, run=True):
#not yet implemented
"""performs the same function as FSUB, but pops the register stack after storing the result."""
if run:
self.lib.fsubp(n)
def FSINCOS(self, run=True):
"""FSINCOS does the same, but then pushes the cosine of the same value on the register stack, so that the sine ends up in ST1 and the cosine in ST0."""
if run:
self.lib.fsincos()
def FSIN(self, run=True):
"""FSIN calculates the sine of ST0 (in radians) and stores the result in ST0"""
if run:
self.lib.fsin()
def FCOS(self, run=True):
"""FCOS calculates the cosine of ST0 (in radians) and stores the result in ST0"""
if run:
self.lib.fcos()
def FPTAN(self, run=True):
"""FPTAN computes the tangent of the value in ST0 (in radians), and stores the result back into ST0. """
if run:
self.lib.fptan()
def FPATAN(self, run=True):
"""FPATAN computes the arctangent, in radians, of the result of dividing ST1 by ST0, stores the result in ST1, and pops the register stack"""
if run:
self.lib.fpatan()
def FRNDINT(self, run=True):
"""FRNDINT rounds the contents of ST0 to an integer, according to the current rounding mode set in the FPU control word, and stores the result back in ST0. """
if run:
self.lib.frndint()
def FYL2X(self, run=True):
"""FYL2X multiplies ST1 by the base-2 logarithm of ST0, stores the result in ST1, and pops the register stack (so that the result ends up in ST0). ST0 must be non-zero and positive."""
if run:
self.lib.fyl2x()
def FSQRT(self, run=True):
"""FSQRT calculates the square root of ST0 and stores the result in ST0."""
if run:
self.lib.fsqrt()
##### FIN INSTRUCCIONES IMPLEMENTADAS ######
def get_valid_instructions(self):
"""
devuelve un diccionario {instrucción=docstring} para instrucciones
válidas basado en la instrospección de los métodos de la clase
"""
valid_instructions = dict([(a,inspect.getdoc(b)) for (a,b)
in inspect.getmembers(Wrapper,inspect.ismethod)
if a[0] == 'F'])
return valid_instructions
#HELPERS
def run_or_test_instruction(self,line, run=False):
"""
En modo run=False se fija si la instrucción ingresada es válida
En modo run=True ejecuta la instrucción.
"""
line = line.replace(',',' ')
commlista = line.split()
comm = commlista[0]
params = [c+", " for c in commlista[1:]]
commline = "self.%s(%s run=%s)" % (comm, "".join(params), run)
print commline
try:
#run=False just check the call is right but do nothing
exec commline
return True
except:
return False
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Este módulo contiene diferentes clases que sobrecargar o agregan comportamientos
a los controles (widgets) estándar de Wx.
Por ejemplo, InstructionListCtrl incorpora métodos que manipulan el orden
de las filas (las intrucciones). También recibe un diccionario con el que asigna
un ToolTip diferente para cada fila en función de la primera palabra (la intrucción
ASM que se haya ingresado).
TextCrlAutoComplete es la clase que se instancia para la caja de texto desde
donde se ingresan las intrucciones. Fue escrito por Edward Flick y otros.
Se le asigna una lista (un diccionario en nuestro caso) de cadenas ingresadas válidas
y produce un efecto de 'autocompleción' a medida que el usuario teclea
RegisterListCtrl permite asignar tooltips diferentes por columna, para describir
la función de cada bit de los registros Control y Estado.
"""
import wx
class InstructionListCtrl(wx.ListCtrl):
"""widget List que permite seleccionar y mover filas"""
def __init__(self, parent, ID, pos=wx.DefaultPosition,size=wx.DefaultSize, style=0, tooltips=None):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
#self.statusbar = statusbar
self.Bind(wx.EVT_MOTION, self.updateToolTip)
self.tooltips = tooltips
def get_list(self):
"""devuelve una lista de items de un list control"""
list = []
row = []
for nrow in range(self.GetItemCount()):
row = []
for ncol in range(1):
row.append(self.GetItem(nrow,ncol).GetText())
list.append(row)
return list
def select_next(self, current):
next = []
if current + 1 <= self.GetItemCount():
next.append(current + 1)
self.updateList(self.get_list(), next)
def get_selected_items(self):
"""
Gets the selected items for the list control.
Selection is returned as a list of selected indices,
low to high.
"""
selection = []
# start at -1 to get the first selected item
current = -1
while True:
next = self.GetNextSelected(current)
if next == -1:
return selection
selection.append(next)
current = next
def num_selected_items(self):
return len(self.get_selected_items())
def GetNextSelected(self, current):
"""Returns next selected item, or -1 when no more"""
return self.GetNextItem(current,
wx.LIST_NEXT_ALL,
wx.LIST_STATE_SELECTED)
def updateList(self, list, selected=[]):
"""reeplaza las intrucciones dadas por list y marca como seleccionadas
las que se indiquen en selected"""
self.DeleteAllItems()
for row in list:
self.Append(row)
for sel in selected:
self.SetItemState(sel, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
def move_up(self):
"""sube un nivel las filas seleccionadas"""
selected = self.get_selected_items()
if len(selected) == 0:
self.statusbar.SetStatusText("no hay instrucciones seleccionadas", 0)
return
list = self.get_list()
for sel in selected:
if sel != 0:
item = list.pop(sel)
list.insert(sel-1,item)
newselected = [sel-1 for sel in selected if sel != 0]
self.updateList(list, newselected)
def updateToolTip(self, event):
(x,y) = event.GetPosition()
alto_fila = 22 #self.GetSize().GetHeight()/self.GetItemCount()
fila = y/alto_fila
#print y, alto_fila, fila
instruc = self.GetItem(fila,0).GetText()
try:
instruc = instruc.split()[0]
self.SetToolTipString(self.tooltips[instruc])
except:
pass
def move_top(self):
"""agrupa y sube las intrucciones al tope de la lista"""
selected = self.get_selected_items()
if len(selected) == 0:
self.statusbar.SetStatusText("no hay instrucciones seleccionadas", 0)
return
lista = self.get_list()
for sel in selected:
if sel != 0:
item = lista.pop(sel)
lista.insert(selected.index(sel),item)
newselected = [i for i in range(self.num_selected_items())]
self.updateList(lista, newselected)
def move_down(self):
"""sube un nivel las filas seleccionadas"""
selected = self.get_selected_items()
lista = self.get_list()
last = self.GetItemCount() - 1
for sel in selected:
if sel != last:
item = lista.pop(sel)
lista.insert(sel+1,item)
self.updateList(lista)
newselected = [sel+1 for sel in selected if sel != last]
self.updateList(lista, newselected)
def move_bottom(self):
"""agrupa y sube las instrucciones al tope de la lista"""
selected = self.get_selected_items()
lista = self.get_list()
last = self.GetItemCount() - 1
for sel in selected:
if sel != last:
item = lista.pop(sel)
lista.append(item)
newselected = [self.self.GetItemCount()-i for i in range(self.num_selected_items())]
self.updateList(lista, newselected)
def delete(self):
"""elimina las instrucciones seleccionadas"""
selected = self.get_selected_items()
lista = self.get_list()
for sel in selected:
lista.pop(sel)
self.updateList(lista)
class RegisterListCtrl(wx.ListCtrl):
"""widget de lista que actualiza su tooltip en función de la columna"""
def __init__(self, parent, ID, pos=wx.DefaultPosition,size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
self.Bind(wx.EVT_MOTION, self.updateToolTip)
def SetColumns(self, columnas, width=30):
columnas.reverse()
self.columnas = columnas
self.width = width
for n,col in enumerate(columnas):
self.InsertColumn(n,col[0], format=wx.LIST_FORMAT_CENTER)
self.SetColumnWidth(n,width)
def updateToolTip(self, event):
(x,y) = event.GetPosition()
col = x/self.width
self.SetToolTipString(u"%s: %s" % (self.columnas[col][1],self.columnas[col][2]))
'''
wxPython Custom Widget Collection 20060207
Written By: Edward Flick (eddy -=at=- cdf-imaging -=dot=- com)
Michele Petrazzo (michele -=dot=- petrazzo -=at=- unipex -=dot=- it)
Will Sadkin (wsadkin-=at=- nameconnector -=dot=- com)
Copyright 2006 (c) CDF Inc. ( http://www.cdf-imaging.com )
Contributed to the wxPython project under the wxPython project's license.
'''
import locale, wx, sys, cStringIO
import wx.lib.mixins.listctrl as listmix
from wx import ImageFromStream, BitmapFromImage
#----------------------------------------------------------------------
def getSmallUpArrowData():
return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00<IDAT8\x8dcddbf\xa0\x040Q\xa4{h\x18\xf0\xff\xdf\xdf\xffd\x1b\x00\xd3\
\x8c\xcf\x10\x9c\x06\xa0k\xc2e\x08m\xc2\x00\x97m\xd8\xc41\x0c \x14h\xe8\xf2\
\x8c\xa3)q\x10\x18\x00\x00R\xd8#\xec\xb2\xcd\xc1Y\x00\x00\x00\x00IEND\xaeB`\
\x82'
def getSmallUpArrowBitmap():
return BitmapFromImage(getSmallUpArrowImage())
def getSmallUpArrowImage():
stream = cStringIO.StringIO(getSmallUpArrowData())
return ImageFromStream(stream)
def getSmallDnArrowData():
return \
"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00HIDAT8\x8dcddbf\xa0\x040Q\xa4{\xd4\x00\x06\x06\x06\x06\x06\x16t\x81\
\xff\xff\xfe\xfe'\xa4\x89\x91\x89\x99\x11\xa7\x0b\x90%\ti\xc6j\x00>C\xb0\x89\
\xd3.\x10\xd1m\xc3\xe5*\xbc.\x80i\xc2\x17.\x8c\xa3y\x81\x01\x00\xa1\x0e\x04e\
?\x84B\xef\x00\x00\x00\x00IEND\xaeB`\x82"
def getSmallDnArrowBitmap():
return BitmapFromImage(getSmallDnArrowImage())
def getSmallDnArrowImage():
stream = cStringIO.StringIO(getSmallDnArrowData())
return ImageFromStream(stream)
#----------------------------------------------------------------------
class myListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent, ID=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.ListCtrlAutoWidthMixin.__init__(self)
class TextCtrlAutoComplete (wx.TextCtrl, listmix.ColumnSorterMixin ):
"""Código tomado de http://wiki.wxpython.org/TextCtrlAutoComplete"""
def __init__ ( self, parent, colNames=None, choices = None,
multiChoices=None, showHead=True, dropDownClick=True,
colFetch=-1, colSearch=0, hideOnNoMatch=True,
selectCallback=None, entryCallback=None, matchFunction=None,
**therest) :
'''
Constructor works just like wx.TextCtrl except you can pass in a
list of choices. You can also change the choice list at any time
by calling setChoices.
'''
if therest.has_key('style'):
therest['style']=wx.TE_PROCESS_ENTER | therest['style']
else:
therest['style']=wx.TE_PROCESS_ENTER
wx.TextCtrl.__init__(self, parent, **therest )
#Some variables
self._dropDownClick = dropDownClick
self._colNames = colNames
self._multiChoices = multiChoices
self._showHead = showHead
self._choices = choices.keys()
self._lastinsertionpoint = 0
self._hideOnNoMatch = hideOnNoMatch
self._selectCallback = selectCallback
self._entryCallback = entryCallback
self._matchFunction = matchFunction
self._screenheight = wx.SystemSettings.GetMetric( wx.SYS_SCREEN_Y )
#sort variable needed by listmix
self.itemDataMap = dict()
#Load and sort data
if not (self._multiChoices or self._choices):
raise ValueError, "Pass me at least one of multiChoices OR choices"
#widgets
self.dropdown = wx.PopupWindow( self )
#Control the style
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING
if not (showHead and multiChoices) :
flags = flags | wx.LC_NO_HEADER
#Create the list and bind the events
self.dropdownlistbox = myListCtrl( self.dropdown, style=flags,
pos=wx.Point( 0, 0) )
#initialize the parent
if multiChoices: ln = len(multiChoices)
else: ln = 1
#else: ln = len(choices)
listmix.ColumnSorterMixin.__init__(self, ln)
#load the data
if multiChoices: self.SetMultipleChoices (multiChoices, colSearch=colSearch, colFetch=colFetch)
else: self.SetChoices ( self._choices )
gp = self
while ( gp != None ) :
gp.Bind ( wx.EVT_MOVE , self.onControlChanged, gp )
gp.Bind ( wx.EVT_SIZE , self.onControlChanged, gp )
gp = gp.GetParent()
self.Bind( wx.EVT_KILL_FOCUS, self.onControlChanged, self )
self.Bind( wx.EVT_TEXT , self.onEnteredText, self )
self.Bind( wx.EVT_KEY_DOWN , self.onKeyDown, self )
#If need drop down on left click
if dropDownClick:
self.Bind ( wx.EVT_LEFT_DOWN , self.onClickToggleDown, self )
self.Bind ( wx.EVT_LEFT_UP , self.onClickToggleUp, self )
self.dropdown.Bind( wx.EVT_LISTBOX , self.onListItemSelected, self.dropdownlistbox )
self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.onListClick)
self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.onListDClick)
self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.onListColClick)
self.il = wx.ImageList(16, 16)
self.sm_dn = self.il.Add(getSmallDnArrowBitmap())
self.sm_up = self.il.Add(getSmallUpArrowBitmap())
self.dropdownlistbox.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
self._ascending = True
#-- methods called from mixin class
def GetSortImages(self):
return (self.sm_dn, self.sm_up)
def GetListCtrl(self):
return self.dropdownlistbox
# -- event methods
def onListClick(self, evt):
toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
#no values on poition, return
if toSel == -1: return
self.dropdownlistbox.Select(toSel)
def onListDClick(self, evt):
self._setValueFromSelected()
def onListColClick(self, evt):
col = evt.GetColumn()
#reverse the sort
if col == self._colSearch:
self._ascending = not self._ascending
self.SortListItems( evt.GetColumn(), ascending=self._ascending )
self._colSearch = evt.GetColumn()
evt.Skip()
def onEnteredText(self, event):
text = event.GetString()
if self._entryCallback:
self._entryCallback()
if not text:
# control is empty; hide dropdown if shown:
if self.dropdown.IsShown():
self._showDropDown(False)
event.Skip()
return
found = False
if self._multiChoices:
#load the sorted data into the listbox
dd = self.dropdownlistbox
choices = [dd.GetItem(x, self._colSearch).GetText()
for x in xrange(dd.GetItemCount())]
else:
choices = self._choices
for numCh, choice in enumerate(choices):
if self._matchFunction and self._matchFunction(text, choice):
found = True
elif choice.lower().startswith(text.lower()) :
found = True
if found:
self._showDropDown(True)
item = self.dropdownlistbox.GetItem(numCh)
toSel = item.GetId()
self.dropdownlistbox.Select(toSel)
break
if not found:
self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
if self._hideOnNoMatch:
self._showDropDown(False)
self._listItemVisible()
event.Skip ()
def onKeyDown ( self, event ) :
""" Do some work when the user press on the keys:
up and down: move the cursor
left and right: move the search
"""
skip = True
sel = self.dropdownlistbox.GetFirstSelected()
visible = self.dropdown.IsShown()
KC = event.GetKeyCode()
if KC == wx.WXK_DOWN :
if sel < (self.dropdownlistbox.GetItemCount () - 1) :
self.dropdownlistbox.Select ( sel+1 )
self._listItemVisible()
self._showDropDown ()
skip = False
elif KC == wx.WXK_UP :
if sel > 0 :
self.dropdownlistbox.Select ( sel - 1 )
self._listItemVisible()
self._showDropDown ()
skip = False
elif KC == wx.WXK_LEFT :
if not self._multiChoices: return
if self._colSearch > 0:
self._colSearch -=1
self._showDropDown ()
elif KC == wx.WXK_RIGHT:
if not self._multiChoices: return
if self._colSearch < self.dropdownlistbox.GetColumnCount() -1:
self._colSearch += 1
self._showDropDown()
if visible :
if event.GetKeyCode() == wx.WXK_RETURN :
self._setValueFromSelected()
skip = False
if event.GetKeyCode() == wx.WXK_ESCAPE :
self._showDropDown( False )
skip = False
if skip :
event.Skip()
def onListItemSelected (self, event):
self._setValueFromSelected()
event.Skip()
def onClickToggleDown(self, event):
self._lastinsertionpoint = self.GetInsertionPoint()
event.Skip ()
def onClickToggleUp ( self, event ) :
if ( self.GetInsertionPoint() == self._lastinsertionpoint ) :
self._showDropDown ( not self.dropdown.IsShown() )
event.Skip ()
def onControlChanged(self, event):
self._showDropDown( False )
event.Skip()
# -- Interfaces methods
def SetMultipleChoices(self, choices, colSearch=0, colFetch=-1):
''' Set multi-column choice
'''
self._multiChoices = choices
self._choices = None
if not isinstance(self._multiChoices, list):
self._multiChoices = [ x for x in self._multiChoices]
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING
if not self._showHead:
flags |= wx.LC_NO_HEADER
self.dropdownlistbox.SetWindowStyleFlag(flags)
#prevent errors on "old" systems
if sys.version.startswith("2.3"):
self._multiChoices.sort(lambda x, y: cmp(x[0].lower(), y[0].lower()))
else:
self._multiChoices.sort(key=lambda x: locale.strxfrm(x[0]).lower() )
self._updateDataList(self._multiChoices)
lChoices = len(choices)
if lChoices < 2:
raise ValueError, "You have to pass me a multi-dimension list"
for numCol, rowValues in enumerate(choices[0]):
if self._colNames: colName = self._colNames[numCol]
else: colName = "Select %i" % numCol
self.dropdownlistbox.InsertColumn(numCol, colName)
for numRow, valRow in enumerate(choices):
for numCol, colVal in enumerate(valRow):
if numCol == 0:
index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
self.dropdownlistbox.SetStringItem(index, numCol, colVal)
self.dropdownlistbox.SetItemData(index, numRow)
self._setListSize()
self._colSearch = colSearch
self._colFetch = colFetch
def SetChoices(self, choices):
'''
Sets the choices available in the popup wx.ListBox.
The items will be sorted case insensitively.
'''
self._choices = choices
self._multiChoices = None
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER
self.dropdownlistbox.SetWindowStyleFlag(flags)
if not isinstance(choices, list):
self._choices = [ x for x in choices]
#prevent errors on "old" systems
if sys.version.startswith("2.3"):
self._choices.sort(lambda x, y: cmp(x.lower(), y.lower()))
else:
self._choices.sort(key=lambda x: locale.strxfrm(x).lower())
self._updateDataList(self._choices)
self.dropdownlistbox.InsertColumn(0, "")
for num, colVal in enumerate(self._choices):
index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
self.dropdownlistbox.SetStringItem(index, 0, colVal)
self.dropdownlistbox.SetItemData(index, num)
self._setListSize()
# there is only one choice for both search and fetch if setting a single column:
self._colSearch = 0
self._colFetch = -1
def GetChoices(self):
if self._choices:
return self._choices
else:
return self._multiChoices
def SetSelectCallback(self, cb=None):
self._selectCallback = cb
def SetEntryCallback(self, cb=None):
self._entryCallback = cb
def SetMatchFunction(self, mf=None):
self._matchFunction = mf
#-- Internal methods
def _setValueFromSelected( self ) :
'''
Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
Will do nothing if no item is selected in the wx.ListCtrl.
'''
sel = self.dropdownlistbox.GetFirstSelected()
if sel > -1:
if self._colFetch != -1: col = self._colFetch
else: col = self._colSearch
itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
if self._selectCallback:
dd = self.dropdownlistbox
values = [dd.GetItem(sel, x).GetText()
for x in xrange(dd.GetColumnCount())]
self._selectCallback( values )
self.SetValue (itemtext)
self.SetInsertionPointEnd ()
self.SetSelection ( -1, -1 )
self._showDropDown ( False )
def _showDropDown ( self, show = True ) :
'''
Either display the drop down list (show = True) or hide it (show = False).
'''
if show :
size = self.dropdown.GetSize()
width, height = self . GetSizeTuple()
x, y = self . ClientToScreenXY ( 0, height )
if size.GetWidth() != width :
size.SetWidth(width)
self.dropdown.SetSize(size)
self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
if (y + size.GetHeight()) < self._screenheight :
self.dropdown . SetPosition ( wx.Point(x, y) )
else:
self.dropdown . SetPosition ( wx.Point(x, y - height - size.GetHeight()) )
self.dropdown.Show ( show )
def _listItemVisible( self ) :
'''
Moves the selected item to the top of the list ensuring it is always visible.
'''
toSel = self.dropdownlistbox.GetFirstSelected ()
if toSel == -1: return
self.dropdownlistbox.EnsureVisible( toSel )
def _updateDataList(self, choices):
#delete, if need, all the previous data
if self.dropdownlistbox.GetColumnCount() != 0:
self.dropdownlistbox.DeleteAllColumns()
self.dropdownlistbox.DeleteAllItems()
#and update the dict
if choices:
for numVal, data in enumerate(choices):
self.itemDataMap[numVal] = data
else:
numVal = 0
self.SetColumnCount(numVal)
def _setListSize(self):
if self._multiChoices:
choices = self._multiChoices
else:
choices = self._choices
longest = 0
for choice in choices :
longest = max(len(choice), longest)
longest += 3
itemcount = min( len( choices ) , 7 ) + 2
charheight = self.dropdownlistbox.GetCharHeight()
charwidth = self.dropdownlistbox.GetCharWidth()
self.popupsize = wx.Size( charwidth*longest, charheight*itemcount )
self.dropdownlistbox.SetSize ( self.popupsize )
self.dropdown.SetClientSize( self.popupsize )
if __name__ == '__main__':
pass
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import os
_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "A":"1010", "B":"1011",
"C":"1100", "D":"1101", "E":"1110", "F":"1111",
"-":"-"}
def toBase2(number):
"""toBase2(number): given an int/long, converts it to
a string containing the number in base 2."""
# From a suggestion by Dennis Lee Bieber.
if number == 0:
return "0"
result = [_nibbles[nibble] for nibble in "%X"%number]
result[number<0] = result[number<0].lstrip("0")
result.reverse()
return result
def int2bin(n):
'''converts denary integer n to binary list
[MSB,....,LSB]
'''
b = []
if n < 0: raise ValueError, "must be positive"
if n == 0: return [0]
while n > 0:
b.append(n % 2)
n = n >> 1
while len(b)<16:
b.append(0)
b.reverse()
return b
def get_svn_revision(path=None):
rev = None
if path is None:
path = os.path.dirname( __file__ )# __path__[0]
entries_path = '%s/.svn/entries' % path
if os.path.exists(entries_path):
entries = open(entries_path, 'r').read()
# Versions >= 7 of the entries file are flat text. The first line is
# the version number. The next set of digits after 'dir' is the revision.
if re.match('(\d+)', entries):
rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
if rev_match:
rev = rev_match.groups()[0]
# Older XML versions of the file specify revision as an attribute of
# the first entries node.
else:
from xml.dom import minidom
dom = minidom.parse(entries_path)
rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
if rev:
return u' SVN-%s' % rev
return u'1.0'
class BufferStack():
def __init__(self):
self.fhdir = u"%s/stack.tmp" % os.path.abspath(os.path.dirname(__file__))
def set_stack_from_file(self):
fh = open(self.fhdir, 'r')
stack = pickle.load(fh)
set_stack(stack)
fh.close()
def get_stack_to_file(self):
stack = [v for v in self.get_stack()]
fh = open(self.fhdir, 'w')
stack = pickle.dump(stack, fh)
fh.close()
| Python |
# -*- coding: utf-8 -*-
"""
Este es el código de la ventana principal, y el verdadero controlador del programa
Contiene diferentes "widgets" (listas, cajas de texto, botones, menúes,...) que pueden producir eventos.
Un evento es un click, la presión de una tecla, etc. Los eventos se asociacion
a uno (o más) métodos de respuesta a través del método Bind() que provee wx.
La aplicación de escritorio se convierte en una "aplicación orientada a eventos"
ya que un hilo principal (el mainloop() que se ejecuta en app.py) está todo el
tiempo escuchando eventos y despachando al método encargado de hacer algo en
consecuencia (es simular a las interrupciones del procesador).
Los métodos que comienzan con *action* son los que responden a eventos. Hay
dos grupos: los que actuan sobre la lista de intrucciones (abrir, guardar, mover
o quitar instrucciones de la lista, etc) y los que actuan sobre la libreria FPU
(refrescar pila, refrescar registros, ejecutar siguiente instruccion).
El método __init__ , como en cualquier clase de Python, es el inicializador.
Cuando se crea un objeto MainFrame() (como el que se crea en app.py),
automáticamente se ejecuta este método que es el encargado de crear los elementos
de la ventana, ubicarlos en diferentes 'sizer' (que son divisiones de la ventana,
la manera que tiene WX de distribuir los objetos en la ventana), y darle las
propiedades. Para una cuestión de claridad, esas tareas se separan en dos métodos
completarios (que hacen las veces de subrutinas): son _do_layout() y _set_properties()
La mayoría de este código lo produjo la herramienta wxGlade, que sirve para
diseñar la ventana visualmente, como en los IDEs de Java o Visual Basic.
Con la ventaja que al producir código, luego se puede modificar a mano.
Dos objetos importantes se instancian como atributos de un objeto MainFrame
Estos son self.manager y self.lib . El primero es un manejador del proxy
que separa una parte del programa (el objeto lib) en un proceso hijo.
self.lib es un objeto Wrapper() (ver `wrapper.py`) instanciado a través del
manejador.
La gestión de archivos utiliza el módulo Pickle, que es la herramienta para
serializar objetos de (casi) cualquier índole. En vez de tener que definir
una estructura para el archivo, y luego tener que decodificarla, simplemente
serializamos el contenido a guardar (los elementos de la lista de instrucciones)
y dejamos que Pickle se encargue de escribir y de leer el archivo.
Hay abundantes comentarios en el código. Espero sea de utilidad!
"""
import wx #nuestra biblioteca GUI
import os # vamos a manejar archivos y directorios
import pickle # serialización de datos para guardar y leer objetos a un archivo
from multiprocessing.managers import BaseManager #la magia que crea un proceso nuevo
#y lo maneja como si fuera uno sólo
from AboutFrame import AboutFrame #la ventana de "Acerca de" donde estamos nosotros
#algunos widgets están 'mejorados' ver docu de `myWidgets.py`
from myWidgets import InstructionListCtrl, RegisterListCtrl, TextCtrlAutoComplete
from helpers import * #funciones de formateo, etc.
from wrapper import Wrapper #la interfaz con C!
class MyManager(BaseManager):
"""MyManager simplemente hereda de BaseManager. Es el manejador de proxy
que sabe crear y comunicarse con otro proceso"""
pass
#hay que decirle al manejador qué tipo de objetos va a separar en otro proceso.
#el primer parámetro es la identificación de ese tipo de objetos a través
#del wrapper. Para no complicar las cosas, se llama igual.
MyManager.register('Wrapper', Wrapper)
_path = os.path.abspath(os.path.dirname(__file__)) #la ruta desde donde se ejecuta el programa
class MainFrame(wx.Frame):
def __init__(self, *args, **kwds):
"""inicializador. Dibuja los elementos en la ventana y le asigna propiedades"""
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.sizer_12_staticbox = wx.StaticBox(self, -1, "Pila")
self.sizer_7_staticbox = wx.StaticBox(self, -1, "Registro de Control")
self.sizer_8_staticbox = wx.StaticBox(self, -1, "Registro de Estado")
self.sizer_3_staticbox = wx.StaticBox(self, -1, "Instrucciones")
# Menu Bar
menues_ids = [wx.NewId() for i in range(7)]
self.frame_1_menubar = wx.MenuBar()
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(menues_ids[0], "&Nuevo", "", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(menues_ids[1], "&Abrir", "", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(menues_ids[2], "&Guardar", "", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(menues_ids[3], "Guardar como...", "", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(menues_ids[4], "&Salir", "", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, "&Archivo")
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(menues_ids[5], u"Índ&ice", "", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(menues_ids[6], "&Acerca de..", "", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, "A&yuda")
self.SetMenuBar(self.frame_1_menubar)
# Menu Bar end
self.statusbar = self.CreateStatusBar(1, 0)
# Tool Bar
tools_ids = [wx.NewId() for i in range(11)]
self.frame_1_toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL|wx.TB_DOCKABLE)
self.SetToolBar(self.frame_1_toolbar)
self.frame_1_toolbar.AddLabelTool(tools_ids[0], "Nuevo", wx.Bitmap("%s/icons/document-new.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Nuevo archivo", "Crea una nueva secuencia de instrucciones")
self.frame_1_toolbar.AddLabelTool(tools_ids[1], "Abrir", wx.Bitmap("%s/icons/document-open.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Abrir archivo", "Abre una secuencia de instrucciones de un archivo")
self.frame_1_toolbar.AddLabelTool(tools_ids[2], "Guardar", wx.Bitmap("%s/icons/document-save.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Guardar", "Guarda la secuencia de instrucciones actual")
self.frame_1_toolbar.AddLabelTool(tools_ids[3], "Guardar como...", wx.Bitmap("%s/icons/document-save-as.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Guardar como...", "Guarda la secuencia en un nuevo archivo")
self.frame_1_toolbar.AddSeparator()
self.frame_1_toolbar.AddLabelTool(tools_ids[4], "Arriba", wx.Bitmap("%s/icons/go-top.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Subir al tope", "Agrupa y sube las intrucciones selecciones al principio")
self.frame_1_toolbar.AddLabelTool(tools_ids[5], "Subir", wx.Bitmap("%s/icons/go-up.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Subir una intrucción", "Sube las instrucciones seleccionadas un paso")
self.frame_1_toolbar.AddLabelTool(tools_ids[6], "Bajar", wx.Bitmap("%s/icons/go-down.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Bajar una instrucción", "Baja las intrucciones seleccionadas un paso")
self.frame_1_toolbar.AddLabelTool(tools_ids[7], "Abajo", wx.Bitmap("%s/icons/go-bottom.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Bajar al final", "Agrupa y baja las instrucciones seleccionadas al final")
self.frame_1_toolbar.AddLabelTool(tools_ids[8], "Borrar", wx.Bitmap("%s/icons/list-remove.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Borrar", "Borra las instrucciones seleccionadas")
self.frame_1_toolbar.AddSeparator()
self.frame_1_toolbar.AddLabelTool(tools_ids[9], "Ejecutar", wx.Bitmap("%s/icons/go-next.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Ejecutar instrucción", "Ejecuta la siguiente instrucción de la secuencia")
self.frame_1_toolbar.AddLabelTool(tools_ids[10], "Actualizar", wx.Bitmap("%s/icons/view-refresh.png" % _path, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Actualizar entorno", "Actualiza los registros y el estado de la pila")
# Tool Bar end
#libreria de interfaz con C. la gran magia.
self.manager = MyManager() #mediante un proxy que desacopla el wrapper en otro proceso (¡Viva python!)
self.manager.start()
self.lib = self.manager.Wrapper()
implementadas = self.lib.get_valid_instructions()
#input de instrucciones
self.instructionInput = TextCtrlAutoComplete(self, "", style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB, choices=implementadas)
self.bitmap_button_1 = wx.BitmapButton(self, -1, wx.Bitmap("%s/icons/list-add.png" % _path, wx.BITMAP_TYPE_ANY))
self.instructionsList = InstructionListCtrl(self, -1, style=wx.LC_REPORT| wx.LC_NO_HEADER|wx.LC_HRULES|wx.SUNKEN_BORDER, tooltips=implementadas)
self.stackList = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
#listas que muestran flags binarios
self.controlList = RegisterListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.statusList = RegisterListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_MENU, self.actionNew, id=menues_ids[0])
self.Bind(wx.EVT_MENU, self.actionOpen, id=menues_ids[1])
self.Bind(wx.EVT_MENU, self.actionSave, id=menues_ids[2])
self.Bind(wx.EVT_MENU, self.actionSaveAs, id=menues_ids[3])
self.Bind(wx.EVT_MENU, self.actionExit, id=menues_ids[4])
self.Bind(wx.EVT_MENU, self.actionShowHelp, id=menues_ids[5])
self.Bind(wx.EVT_MENU, self.actionShowAbout, id=menues_ids[6])
self.Bind(wx.EVT_CLOSE, self.onCloseWindow)
self.Bind(wx.EVT_TOOL, self.actionNew, id=tools_ids[0])
self.Bind(wx.EVT_TOOL, self.actionOpen, id=tools_ids[1])
self.Bind(wx.EVT_TOOL, self.actionSave, id=tools_ids[2])
self.Bind(wx.EVT_TOOL, self.actionSaveAs, id=tools_ids[3])
self.Bind(wx.EVT_TOOL, self.actionGoTop, id=tools_ids[4])
self.Bind(wx.EVT_TOOL, self.actionUp, id=tools_ids[5])
self.Bind(wx.EVT_TOOL, self.actionDown, id=tools_ids[6])
self.Bind(wx.EVT_TOOL, self.actionBottom, id=tools_ids[7])
self.Bind(wx.EVT_TOOL, self.actionDelete, id=tools_ids[8])
self.Bind(wx.EVT_TOOL, self.actionRunNext, id=tools_ids[9])
self.Bind(wx.EVT_TOOL, self.actionRefreshAll, id=tools_ids[10])
self.Bind(wx.EVT_TEXT_ENTER, self.actionAdd, self.instructionInput)
self.Bind(wx.EVT_BUTTON, self.actionAdd, self.bitmap_button_1)
# end wxGlade
self.doiexit = wx.MessageDialog( self, u'Desea salir? \n',
"Saliendo...", wx.YES_NO)
self.dirname = ''
self.filename = None
self.modificado = False
def __set_properties(self):
"""asignación de propiedades iniciales a los distintos widgets"""
self.titulo = "FPU Inspector"
self.SetTitle(self.titulo)
_icon = wx.EmptyIcon()
_icon.CopyFromBitmap(wx.Bitmap("%s/icons/icon.jpg" % _path, wx.BITMAP_TYPE_ANY))
self.SetIcon(_icon)
self.statusbar.SetStatusWidths([-1])
# statusbar fields
self.updateStatusBar()
self.frame_1_toolbar.Realize()
self.instructionInput.SetMinSize((200, 27))
self.instructionInput.SetToolTipString(u"Ingrese una instrucción de FPU aquí")
self.instructionInput.SetFocus()
self.bitmap_button_1.SetSize(self.bitmap_button_1.GetBestSize())
# end wxGlade
self.instructionsList.InsertColumn(0,u'Código')
self.instructionsList.SetColumnWidth(0,220)
registro_estado = [('IE',u'Bit de error de operación inválida',
u'Indica una operación inválida: desbordamiento '
u'de la pila, un valor indeterminado, raíz '
u'cuadrada de número negativo,..'),
('DE',u'Bit de error de operando no normalizado',
u'Indica que al menos uno de los operandos no está normalizado.'),
('ZE',u'Bit de error de división por cero',
u'Indica una división por cero.'),
('OE',
u'Bit de error de overflow',
u'Indica un error de desbordamiento (resultado demasiado'
u' grande para ser representado).'),
('UE',
u'Bit de erro de underflow',
u'Indica un error de subflujo (resultado diferente a 0 '
u'que es demasiado pequeño para ser representado '
u'con la precisión actual seleccionada por la palabra de control).'),
('PE',
u'Bit de error de precisión',
u'Indica que el resultado o los operandos exceden '
u'la precisión seleccionada.'),
('SF',
u'Bit de operación inválida',
u'Diferencia entre las operaciones inválidas al '
u'interpretar los bits del código de condición.'),
('ES',
u'Bit de resumen de errores',
u'Si está a 1, indica que cualquiera de los bits de '
u'error no enmascarado está a 1.'),
('C0',
u'Bits del código de condición',
u'indican condiciones del coprocesador, '
u'resultado de operaciones aritméticas y de comparación '
u'en punto flotante. Utilizados para el tratamiento '
u'de excepciones.'),
('C1',
u'Bits del código de condición',
u'indican condiciones del coprocesador, resultado '
u'de operaciones aritméticas y de comparación '
u'en coma flotante. Utilizados para el tratamiento '
u'de excepciones.'),
('C2',
u'Bits del código de condición',
u'indican condiciones del coprocesador, resultado '
u'de operaciones aritméticas y de comparación en punto '
u'flotante. Utilizados para el tratamiento de excepciones.'),
('TOP0',
u'Campo de tope o cima de pila',
u'Muestra el primer registro activo de la pila '
u'(registro actualmente diseccionado como registro '
u'superior de la pila (ST)).'),
('TOP1',
u'Campo de tope o cima de pila',
u'Muestra el primer registro activo de la pila '
u'(registro actualmente diseccionado como registro '
u'superior de la pila (ST)).'),
('TOP2',
u'Campo de tope o cima de pila',
u'Muestra el primer registro activo de la pila '
u'(registro actualmente diseccionado como registro '
u'superior de la pila (ST)).'),
('C3',
u'Bits del código de condición',
u'indican condiciones del coprocesador, resultado '
u'de operaciones aritméticas y de comparación en punto'
u'flotante. Utilizados para el tratamiento de excepciones.'),
('B',
u'Bit de ocupado',
u'Indica que el coprocesado está ocupado realizando '
u'una tarea. Los coprocesadores actuales no necesitan '
u'verificar este bit, ya que se sincronizan automáticamente '
u'con el microprocesador.'),]
registro_control = [('IM',u'Máscara de operación inválida',''),
('DM',u'Máscara de operando no normalizado',''),
('ZM',u'Máscara de división por cero',''),
('OM',u'Máscara de overflow',''),
('UM', u'Máscara de underflow', ''),
('PE', u'Máscara de error de precisión', ''),
('', '', ''),
('', '', ''),
('PC0', u'Control de precisión', u'\n00: precisión sencilla\n'
u'01:Reservado\n10:Doble precisión (largo)\n'
u'11: Precisión extendida (temporal)'),
('PC1', u'Control de precisión', u'\n00: precisión sencilla\n'
u'01:Reservado\n10:Doble precisión (largo)\n'
u'11: Precisión extendida (temporal)'),
('RC0', u'Control de redondeo', u'\n00:redondeo al más cercano o par\n'
u'01:Redondeo hacia abajo\n10:Redondeo hacia arriba\n'
u'11: Trunca'),
('RC1', u'Control de redondeo', u'\n00:redondeo al más cercano o par\n'
u'01:Redondeo hacia abajo\n10:Redondeo hacia arriba\n'
u'11: Trunca'),
('IC', u'Control de infinito', u'\n0: Proyectivo\n1: Afin'),
('', '', ''),
('', '', ''),
('', '', ''),
]
#Configuro las columnas para los registros
self.controlList.SetColumns(registro_control)
self.statusList.SetColumns(registro_estado)
#Lista de pila
stack_cols = ('ST', 'Float', 'Etiqueta')
for n,col in enumerate(stack_cols):
self.stackList.InsertColumn(n,col)
self.stackList.SetColumnWidth(0,30)
self.stackList.SetColumnWidth(1,100)
self.stackList.SetColumnWidth(2,100)
def __do_layout(self):
"""genera las divisiones y las ubicaciones de cada elemento en la ventana"""
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_6 = wx.BoxSizer(wx.VERTICAL)
sizer_8 = wx.StaticBoxSizer(self.sizer_8_staticbox, wx.HORIZONTAL)
sizer_7 = wx.StaticBoxSizer(self.sizer_7_staticbox, wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_12 = wx.StaticBoxSizer(self.sizer_12_staticbox, wx.HORIZONTAL)
sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.VERTICAL)
sizer_4 = wx.FlexGridSizer(1, 3, 0, 0)
sizer_4.Add(self.instructionInput, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_4.Add(self.bitmap_button_1, 0, 0, 0)
sizer_3.Add(sizer_4, 0, wx.EXPAND, 0)
sizer_3.Add(self.instructionsList, 1, wx.EXPAND, 0)
sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
sizer_12.Add(self.stackList, 1, wx.LEFT|wx.EXPAND, 0)
sizer_2.Add(sizer_12, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
sizer_7.Add(self.controlList, 1, wx.EXPAND|wx.FIXED_MINSIZE, 0)
sizer_6.Add(sizer_7, 1, wx.EXPAND, 0)
sizer_8.Add(self.statusList, 1, wx.EXPAND|wx.FIXED_MINSIZE, 0)
sizer_6.Add(sizer_8, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_6, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
self.Centre()
# end wxGlade
def actionExit(self, event):
"""Salir y cerrar la puerta"""
self.Close(True)
def onCloseWindow(self, event):
"""al salir se ejecuta este método que verifica el estado del archivo"""
if self.modificado:
#self.actionSave(event)
dlg = wx.MessageDialog(self, "El archivo no se ha guardado\nDesea guardarlo?", "Salir", wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
answer = dlg.ShowModal()
dlg.Destroy()
if answer == wx.ID_YES:
self.actionSave(event)
elif answer == wx.ID_NO:
self.Destroy() # frame
else:
dlg = wx.MessageDialog(self, "Desea salir?", "Salir", wx.YES_NO | wx.ICON_QUESTION)
answer = dlg.ShowModal()
dlg.Destroy()
if answer == wx.ID_YES:
self.Destroy()
def actionShowHelp(self, event): # wxGlade: MainFrame.<event_handler>
print "Event handler `actionShowHelp' not implemented!"
def actionShowAbout(self, event): # wxGlade: MainFrame.<event_handler>
self.about = AboutFrame(None, -1, "")
self.about.Show(True)
def actionGoTop(self, event): # wxGlade: MainFrame.<event_handler>
num = self.instructionsList.num_selected_items()
if num > 0:
self.instructionsList.move_top()
self.modificado = True
self.updateStatusBar(u"%i instrucciones movidas al inicio de la sencuencia" % num)
else:
self.updateStatusBar(u"No hay instrucciones seleccionadas")
def actionUp(self, event): # wxGlade: MainFrame.<event_handler>
num = self.instructionsList.num_selected_items()
if num > 0:
self.instructionsList.move_up()
self.modificado = True
self.updateStatusBar(u"%i instrucciones subidas un paso" % num)
else:
self.updateStatusBar(u"No hay instrucciones seleccionadas")
def actionDown(self, event): # wxGlade: MainFrame.<event_handler>
num = self.instructionsList.num_selected_items()
if num > 0:
self.instructionsList.move_down()
self.modificado = True
self.updateStatusBar(u"%i instrucciones bajadas un paso" % num)
else:
self.updateStatusBar(u"No hay instrucciones seleccionadas")
def actionBottom(self, event): # wxGlade: MainFrame.<event_handler>
num = self.instructionsList.num_selected_items()
if num > 0:
self.instructionsList.move_bottom()
self.modificado = True
self.updateStatusBar(u"%i instrucciones movidas al final de la secuencia" % num)
else:
self.updateStatusBar(u"No hay instrucciones seleccionadas")
def actionDelete(self, event): # wxGlade: MainFrame.<event_handler>
num = self.instructionsList.num_selected_items()
if num > 0:
self.instructionsList.delete()
self.modificado = True
self.updateStatusBar(u"%i instrucciones eliminadas" % num)
else:
self.updateStatusBar(u"No hay instrucciones seleccionadas")
def actionRunNext(self, event): # wxGlade: MainFrame.<event_handler>
"""ejecuta desde la primera instrucción seleccionada o desde el inicio"""
sel_items = self.instructionsList.get_selected_items()
if len(sel_items)>0:
run_from = sel_items[0]
else:
run_from = 0
instruction = self.instructionsList.get_list()[run_from][0]
self.lib.run_or_test_instruction(instruction, True)
self.actionRefreshAll(event)
self.instructionsList.select_next(run_from)
def actionRefreshAll(self, event=None): # wxGlade: MainFrame.<event_handler>
self.actionRefreshControl(event)
self.actionRefreshStatus(event)
self.actionRefreshStack(event)
self.updateStatusBar(u"Registros y pila actualizados")
def actionRefreshControl(self, event):
control_val = self.lib.get_control()
print "control: " + str(control_val)
self.controlList.DeleteAllItems()
self.controlList.Append(int2bin(control_val))
def actionRefreshStatus(self, event):
status_val = self.lib.get_estado()
print "estado: " + str(status_val)
self.statusList.DeleteAllItems()
self.statusList.Append(int2bin(status_val))
def actionRefreshStack(self, event=None):
stack = self.lib.get_stack()
self.stackList.DeleteAllItems()
#stack = [10.8, 10, 0, 0, 0, 0, 0, 1]
for n,val in enumerate(stack):
self.stackList.Append([u'%i' % n, unicode(val), u''])
#self.lib.set_stack(stack)
def actionAdd(self, event): # wxGlade: MainFrame.<event_handler>
instruccion = self.instructionInput.GetValue().upper()
if self.lib.run_or_test_instruction(instruccion):
self.instructionsList.Append([instruccion])
self.instructionInput.SetValue('')
self.instructionInput.SetFocus()
self.updateStatusBar(u"Instrucción '%s' agregada" % instruccion)
self.modificado = True
else:
self.updateStatusBar(u"Instrucción incorrecta")
def actionOpen(self,event):
# In this case, the dialog is created within the method because
# the directory name, etc, may be changed during the running of the
# application. In theory, you could create one earlier, store it in
# your frame object and change it when it was called to reflect
# current parameters / values
dlg = wx.FileDialog(self, "Elija un archivo", self.dirname, "", "*.fpu", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename=dlg.GetFilename()
self.dirname=dlg.GetDirectory()
# Open the file, read the contents and set them into
# the text edit window
filehandle=open(os.path.join(self.dirname, self.filename),'r')
lista = pickle.load(filehandle)
#update list
self.instructionsList.updateList(lista)
filehandle.close()
# Report on name of latest file read
self.SetTitle("%s <%s>" % (self.titulo, self.filename))
self.modificado = False
self.updateStatusBar(u"Archivo %s abierto correctamente" % self.filename)
dlg.Destroy()
def actionNew(self, event): # wxGlade: MainFrame.<event_handler>
if self.modificado:
dlg = wx.MessageDialog(None, u'Si no guarda, se perderán permanentemente los cambios realizados\n¿Desea guardar antes?',
u'Los cambios no ha sido guardados',
style=wx.YES_NO | wx.CANCEL | wx.ICON_EXCLAMATION | wx.STAY_ON_TOP)
selection = dlg.ShowModal()
if selection == wx.ID_YES:
self.actionSave(event)
elif selection == wx.ID_CANCEL:
evtent.Skip()
dlg.Destroy()
self.instructionsList.DeleteAllItems()
self.filename = None
self.SetTitle(self.titulo)
def actionSaveAs(self,event):
"""guarda la lista de intrucciones actual dando un nombre nuevo"""
dlg = wx.FileDialog(self, "Elija un archivo", self.dirname, "", "*.fpu", \
wx.SAVE | wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
# Open the file for write, write, close
self.filename=dlg.GetFilename()
self.dirname=dlg.GetDirectory()
self.actionSave(event)
# Get rid of the dialog to keep things tidy
dlg.Destroy()
def actionSave(self,event):
"""guarda la lista de instrucciones en el archivo abierto. Si no existe,
abre el dialogo Guardar como"""
print event
if self.filename is None:
self.actionSaveAs(event)
else:
list = self.instructionsList.get_list()
filehandle=open(os.path.join(self.dirname, self.filename),'w')
pickle.dump(list,filehandle)
filehandle.close()
self.SetTitle("%s <%s>" % (self.titulo, self.filename))
self.modificado = False
self.updateStatusBar(u"Archivo %s guardado" % filename)
return
def updateStatusBar(self, msg=u'Agregue una instrucción'):
statusbar_fields = []
if isinstance(msg,str):
statusbar_fields.append(msg)
elif hasattr(msg,'__iter__'):
statusbar_fields = msg
for i in range(len(statusbar_fields)):
self.statusbar.SetStatusText(str(statusbar_fields[i]), i)
# end of class MainFrame
| Python |
#!/usr/bin/env python
#
# Copyright 2004 Matt Mackall <mpm@selenic.com>
#
# Inspired by perl Bloat-O-Meter (c) 1997 by Andi Kleen
#
# This software may be used and distributed according to the terms
# of the GNU General Public License, incorporated herein by reference.
import sys, os#, re
def usage():
sys.stderr.write("usage: %s [-t] file1 file2\n" % sys.argv[0])
sys.exit(-1)
f1, f2 = (None, None)
flag_timing, dashes = (False, False)
for f in sys.argv[1:]:
if f.startswith("-"):
if f == "--": # sym_args
dashes = True
break
if f == "-t": # timings
flag_timing = True
else:
if not os.path.exists(f):
sys.stderr.write("Error: file '%s' does not exist\n" % f)
usage()
if f1 is None:
f1 = f
elif f2 is None:
f2 = f
if flag_timing:
import time
if f1 is None or f2 is None:
usage()
sym_args = " ".join(sys.argv[3 + flag_timing + dashes:])
def getsizes(file):
sym, alias, lut = {}, {}, {}
for l in os.popen("readelf -W -s %s %s" % (sym_args, file)).readlines():
l = l.strip()
if not (len(l) and l[0].isdigit() and len(l.split()) == 8):
continue
num, value, size, typ, bind, vis, ndx, name = l.split()
if ndx == "UND": continue # skip undefined
if typ in ["SECTION", "FILES"]: continue # skip sections and files
if "." in name: name = "static." + name.split(".")[0]
value = int(value, 16)
size = int(size, 16) if size.startswith('0x') else int(size)
if vis != "DEFAULT" and bind != "GLOBAL": # see if it is an alias
alias[(value, size)] = {"name" : name}
else:
sym[name] = {"addr" : value, "size": size}
lut[(value, size)] = 0
for addr, sz in iter(alias.keys()):
# If the non-GLOBAL sym has an implementation elsewhere then
# it's an alias, disregard it.
if not (addr, sz) in lut:
# If this non-GLOBAL sym does not have an implementation at
# another address, then treat it as a normal symbol.
sym[alias[(addr, sz)]["name"]] = {"addr" : addr, "size": sz}
for l in os.popen("readelf -W -S " + file).readlines():
x = l.split()
if len(x)<6: continue
# Should take these into account too!
#if x[1] not in [".text", ".rodata", ".symtab", ".strtab"]: continue
if x[1] not in [".rodata"]: continue
sym[x[1]] = {"addr" : int(x[3], 16), "size" : int(x[5], 16)}
return sym
if flag_timing:
start_t1 = int(time.time() * 1e9)
old = getsizes(f1)
if flag_timing:
end_t1 = int(time.time() * 1e9)
start_t2 = int(time.time() * 1e9)
new = getsizes(f2)
if flag_timing:
end_t2 = int(time.time() * 1e9)
start_t3 = int(time.time() * 1e9)
grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
delta, common = [], {}
for name in iter(old.keys()):
if name in new:
common[name] = 1
for name in old:
if name not in common:
remove += 1
sz = old[name]["size"]
down += sz
delta.append((-sz, name))
for name in new:
if name not in common:
add += 1
sz = new[name]["size"]
up += sz
delta.append((sz, name))
for name in common:
d = new[name].get("size", 0) - old[name].get("size", 0)
if d>0: grow, up = grow+1, up+d
elif d<0: shrink, down = shrink+1, down-d
else:
continue
delta.append((d, name))
delta.sort()
delta.reverse()
if flag_timing:
end_t3 = int(time.time() * 1e9)
print("%-48s %7s %7s %+7s" % ("function", "old", "new", "delta"))
for d, n in delta:
if d:
old_sz = old.get(n, {}).get("size", "-")
new_sz = new.get(n, {}).get("size", "-")
print("%-48s %7s %7s %+7d" % (n, old_sz, new_sz, d))
print("-"*78)
total="(add/remove: %s/%s grow/shrink: %s/%s up/down: %s/%s)%%sTotal: %s bytes"\
% (add, remove, grow, shrink, up, -down, up-down)
print(total % (" "*(80-len(total))))
if flag_timing:
print("\n%d/%d; %d Parse origin/new; processing nsecs" %
(end_t1-start_t1, end_t2-start_t2, end_t3-start_t3))
print("total nsecs: %d" % (end_t3-start_t1))
| Python |
import sys
import re
start_re = "(^.*released under the GPL version 2 \(see below\)).*however due"
skip = 0
while True:
line = sys.stdin.readline()
if not line:
break
m = re.match (start_re, line)
if m:
g = m.groups()
print g[0] + '.'
skip = 5
if skip > 0:
skip -= 1
else:
print line,
sys.exit(0)
| Python |
import sys
from PySide import QtCore, QtGui
from tools import add_color_diff, color_diff
class Grapher(QtGui.QWidget):
def __init__(self, parent = None):
super(Grapher, self).__init__()
self.generate = False
self.fractal_color = QtGui.QColor(0, 0, 0)
self.outer_color = QtGui.QColor(0, 0, 0)
self.middle_color = QtGui.QColor(255, 0, 0)
self.inner_color = QtGui.QColor(255, 255, 255)
self.mid_color_diff = color_diff(self.middle_color, self.outer_color)
self.inner_color_diff = color_diff(self.inner_color, self.middle_color)
# The bounds of the complex plane that is being viewed.
# comp_y_max, or the upper imaginary-axis bound, is dynamically generated
# based on the other 3 bounds and the aspect ratio of the window. This prevents stretching.
self.comp_x_min = -2
self.comp_x_max = 1
self.comp_y_min = -1.2
# The number of iterations to run through the mandelbrot algorithm.
self.iteration = 70
def setOuterColor(self, color):
self.outer_color = color
self.mid_color_diff = color_diff(self.middle_color, self.outer_color)
def setMiddleColor(self, color):
self.middle_color = color
self.mid_color_diff = color_diff(self.middle_color, self.outer_color)
self.inner_color_diff = color_diff(self.inner_color, self.middle_color)
def setInnerColor(self, color):
self.inner_color = color
self.inner_color_diff = color_diff(self.inner_color, self.middle_color)
def setFractalColor(self, color):
self.fractal_color = color
def generateMandelbrot(self):
window.setFixedSize(window.size())
self.image = QtGui.QImage(self.size(), QtGui.QImage.Format_RGB32)
painter = QtGui.QPainter(self.image)
self.comp_y_max = self.comp_y_min + float(self.comp_x_max - self.comp_x_min) * self.height() / self.width()
# Part of the linear interpolation formula generated here to save processing time.
self.real_lerp = float(self.comp_x_max - self.comp_x_min)/self.width()
self.img_lerp = float(self.comp_y_max - self.comp_y_min)/self.height()
loading_percent = self.width() / 100
window.statusBar().addWidget(window.progressBar, 1)
window.progressBar.show()
print "Generating Fractal..."
for x in range(self.width()):
for y in range(self.height()):
i = self.point_is_in_set(x, y)
if i == self.iteration: # if the point remained bounded for every iteration
painter.setPen(self.fractal_color)
# Escape-time coloring.
# Color goes from black to {color} for the first slice of the iterations
# Color goes from {color} to white for the second slice of the iterations
else:
slice = self.iteration * 0.5
if i < slice:
percent = float(i) / slice
rgb = add_color_diff(self.mid_color_diff, self.outer_color, percent)
painter.setPen(QtGui.QColor(rgb))
else:
percent = (i - slice)/(self.iteration - slice)
rgb = add_color_diff(self.inner_color_diff, self.middle_color, percent)
painter.setPen(QtGui.QColor(rgb))
painter.drawPoint(x, y)
if x % loading_percent == 0: #temporary loading indicator
# loading = "{0}%".format(x / loading_percent)
loading = x / loading_percent
window.progressBar.setValue(loading)
self.generate = True
print "Done!"
window.statusBar().removeWidget(window.progressBar)
window.statusBar().showMessage("Done!")
self.update()
# Mandelbrot algorithm that checks whether a certain point is in the set
def point_is_in_set(self, x, y):
# Linear interpolation that interpolates the window's pixel coordinate point
# to the respective point on the complex plane.
comp_x = self.comp_x_min + x * self.real_lerp
comp_y = self.comp_y_max - y * self.img_lerp
iter_x = comp_x
iter_y = comp_y
for i in range(0, self.iteration):
iter_x2 = iter_x**2
iter_y2 = iter_y**2
if (iter_x2 + iter_y2 > 4):
return i
iter_y = 2 * iter_x * iter_y + comp_y
iter_x = iter_x2 - iter_y2 + comp_x
i += 1
return i
def paintEvent(self, event):
painter = QtGui.QPainter(self)
if self.generate:
painter.drawImage(QtCore.QPoint(0, 0), self.image)
else:
painter.setPen(QtCore.Qt.white)
painter.setFont(QtGui.QFont("Arial", window.width()/25, 100))
painter.fillRect(self.rect(), QtCore.Qt.black)
painter.drawText(self.rect(), QtCore.Qt.AlignCenter, "Ready to generate Mandelbrot")
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.resize(800, 700)
self.setWindowTitle("fracas")
self.grapher = Grapher(self)
self.setCentralWidget(self.grapher)
self.createActions()
self.createMenus()
self.progressBar = QtGui.QProgressBar()
self.progressBar.setFormat("")
self.statusBar().showMessage("Ready")
def setColor(self):
sender = self.sender()
if sender.data() == "outer":
color = QtGui.QColorDialog.getColor(self.grapher.outer_color, self)
if color.isValid():
self.grapher.setOuterColor(color)
self.icon_color(self.outer_pix, color)
self.outerColorAct.setIcon(self.outer_pix)
elif sender.data() == "middle":
color = QtGui.QColorDialog.getColor(self.grapher.middle_color, self)
if color.isValid():
self.grapher.setMiddleColor(color)
self.icon_color(self.middle_pix, color)
self.middleColorAct.setIcon(self.middle_pix)
elif sender.data() == "inner":
color = QtGui.QColorDialog.getColor(self.grapher.inner_color, self)
if color.isValid():
self.grapher.setInnerColor(color)
self.icon_color(self.inner_pix, color)
self.innerColorAct.setIcon(self.inner_pix)
elif sender.data() == "fractal":
color = QtGui.QColorDialog.getColor(self.grapher.fractal_color, self)
if color.isValid():
self.grapher.setFractalColor(color)
self.icon_color(self.fractal_pix, color)
self.fractalColorAct.setIcon(self.fractal_pix)
def createActions(self):
self.genAct = QtGui.QAction("&Generate", self)
self.genAct.triggered.connect(self.grapher.generateMandelbrot)
self.i_painter = QtGui.QPainter()
self.outer_pix = QtGui.QPixmap(self.size())
self.middle_pix = QtGui.QPixmap(self.size())
self.inner_pix = QtGui.QPixmap(self.size())
self.fractal_pix = QtGui.QPixmap(self.size())
self.icon_color(self.outer_pix, self.grapher.outer_color)
self.icon_color(self.middle_pix, self.grapher.middle_color)
self.icon_color(self.inner_pix, self.grapher.inner_color)
self.icon_color(self.fractal_pix, self.grapher.fractal_color)
self.outerColorAct = QtGui.QAction(self.outer_pix, 'Outer Color', self, triggered=self.setColor)
self.outerColorAct.setData("outer")
self.middleColorAct = QtGui.QAction(self.middle_pix, 'Middle Color', self, triggered=self.setColor)
self.middleColorAct.setData("middle")
self.innerColorAct = QtGui.QAction(self.inner_pix, 'Inner Color', self, triggered=self.setColor)
self.innerColorAct.setData("inner")
self.fractalColorAct = QtGui.QAction(self.fractal_pix, 'Fractal Color', self, triggered=self.setColor)
self.fractalColorAct.setData("fractal")
def createMenus(self):
self.fileMenu = self.menuBar().addMenu("&File")
self.fileMenu.addAction(self.genAct)
self.start_color_menu = self.menuBar().addMenu('Colors')
self.start_color_menu.addAction(self.outerColorAct)
self.start_color_menu.addAction(self.middleColorAct)
self.start_color_menu.addAction(self.innerColorAct)
self.start_color_menu.addAction(self.fractalColorAct)
def icon_color(self, pix, color):
self.i_painter.begin(pix)
self.i_painter.fillRect(self.rect(), color)
self.i_painter.end()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
| Python |
from PySide import QtGui
def add_color_diff((r, g, b), color2, multi = 1):
red = r * multi + color2.red()
green = g * multi + color2.green()
blue = b * multi + color2.blue()
return QtGui.QColor(red, green, blue)
def color_diff(color1, color2):
r = color1.red() - color2.red()
g = color1.green() - color2.green()
b = color1.blue() - color2.blue()
return r, g, b | Python |
from distutils.core import setup
import py2exe
import operator
import sys
if operator.lt(len(sys.argv), 2):
sys.argv.append('py2exe')
setup(windows = [{'script': "main.py"}],
options = {"py2exe" : {'optimize': 2}},
zipfile = "shared.lib")
| Python |
# -*- coding: utf-8 -*-
'''
Created on 2014年3月3日
@author: jun.chn@gmail.com
'''
import subprocess
import sys
def cmd_util(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
res = p.stdout.readlines()
if p.wait() == 0:
return res
return False
'''
活动连接
协议 本地地址 外部地址 状态 PID
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 932
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
TCP 0.0.0.0:554 0.0.0.0:0 LISTENING 5740
'''
class netstat(object):
cmd = ('netstat', '-nao')
LISTENING = 'LISTENING'
def __init__(self, cols):
self.proto, self.local, self.foreign, self.state, self.PID = cols
@classmethod
def create(cls, line):
cols = line.split()
if len(cols) == 5:
return netstat(cols)
return None
@classmethod
def make(cls):
res = []
lines = cmd_util(cls.cmd)
for line in lines:
net = netstat.create(line)
if net and net.state == cls.LISTENING:
res.append(net)
return res
def __str__(self):
return '%s %s' % (self.proto, self.local)
'''
映像名称 PID 会话名 会话# 内存使用 状态 用户名 CPU 时间 窗口标题
========================= ======== ================ =========== ============ =============== ================================================== ============ ========================================================================
System 4 Services 0 2,208 K Unknown 暂缺 0:01:59 暂缺
'''
class tasklist(object):
cmd = ('tasklist', '/fo', 'table', '/v', '/fi', "pid eq %s" )
def __init__(self, line):
self.image_name, self.PID, self.session_name, self.session_id, self.use_memory, self.use_memory_unit,self.status, self.user,self.cpu_time, self.windows_name = line.split()
# self.user = self.user.decode("gbk")
@classmethod
def create(cls, line):
cols = line.split()
if len(cols) == 10:
return tasklist(line)
return None
@classmethod
def make(cls, pids):
res = []
for pid in pids:
lines = cmd_util(cls.cmd[:-1] + (cls.cmd[-1] % pid,))
task = cls.create(lines[-1])
if task:
res.append(task)
return sorted(res, key=lambda task : int(task.PID))
def __str__(self):
return "%s %s" % (self.PID, self.image_name)
class cport(object):
def __init__(self):
self.load()
def load(self):
self.nets = netstat.make()
self.tasks = tasklist.make(set([net.PID for net in self.nets]))
def display(self):
for task in self.tasks:
print '[PID=%s]' % task
for net in self.nets:
if task.PID == net.PID:
print '\t%s' % net
def display_list(self):
print '\t'.join(['PID','NAME','PROTO','LOCAL'])
for task in self.tasks:
for net in self.nets:
if task.PID == net.PID:
print '%s\t%s\t%s\t%s' % (task.PID, task.image_name, net.proto, net.local)
def setUtf8():
reload(sys)
sys.setdefaultencoding('utf-8') # @UndefinedVariable
if __name__ == '__main__':
setUtf8()
obj = cport()
if len(sys.argv) > 1 and sys.argv[1].upper() == '-L':
obj.display_list()
else:
obj.display()
| Python |
# -*- coding: utf-8 -*-
'''
Created on 2014年3月10日
@author: jun.chn@gmail.com
'''
# setup.py
from distutils.core import setup
import py2exe
setup(console=['cport.py']) | Python |
import urllib
import urllib2
import re
import json
import time
from datetime import datetime
from urlparse import urlparse, parse_qs
from traceback import format_exc
from bs4 import BeautifulSoup
import xbmcplugin
import xbmcgui
import xbmcaddon
import xbmcvfs
addon = xbmcaddon.Addon()
addon_version = addon.getAddonInfo('version')
addon_id = addon.getAddonInfo('id')
icon = addon.getAddonInfo('icon')
news_domain = 'http://video.foxnews.com'
business_domain = 'http://video.foxbusiness.com'
def addon_log(string):
try:
log_message = string.encode('utf-8', 'ignore')
except:
log_message = 'addonException: addon_log'
xbmc.log("[%s-%s]: %s" %(addon_id, addon_version, log_message),level=xbmc.LOGDEBUG)
def make_request(url, data=None, headers=None):
addon_log('Request URL: %s' %url)
if headers is None:
headers = {
'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0',
'Referer': 'http://video.foxnews.com'
}
try:
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
data = response.read()
addon_log(str(response.info()))
response.close()
return data
except urllib2.URLError, e:
addon_log('We failed to open "%s".' %url)
if hasattr(e, 'reason'):
addon_log('We failed to reach a server.')
addon_log('Reason: %s' %e.reason)
if hasattr(e, 'code'):
addon_log('We failed with error code - %s.' %e.code)
def get_soup(url):
data = make_request(url)
if data:
return BeautifulSoup(data, 'html.parser')
def get_categories(url=None):
if url is None:
# live streams are still WIP
# add_dir('Watch Live', news_domain + '/playlist/live-landing-page/', icon, 'get_playlist')
add_dir('FoxBusiness.com', business_domain, icon, 'get_categories')
url = news_domain
cat_url = url + '/playlist/featured-editors-picks/'
else:
cat_url = url + '/playlist/latest-video-latest-video/'
soup = get_soup(cat_url)
for i in soup.find('nav')('a'):
add_dir(i.string.encode('utf-8'), url + i['href'], icon, 'get_sub_cat')
def get_sub_categories(url):
soup = get_soup(url)
items_soup = soup('div', attrs={'id' : 'shows'})[0]('a')
current = False
items = []
for i in items_soup:
item_url = 'http:' + i['href']
if item_url == url:
current = (i.string.encode('utf-8'), item_url, icon, 'get_playlist')
continue
items.append((i.string.encode('utf-8'), item_url, icon, 'get_playlist'))
if not current:
current_name = soup.body.h1.contents[0].strip().encode('utf-8')
current = (current_name, url, icon, 'get_playlist')
items.insert(0, current)
for i in items:
add_dir(*i)
def get_video(video_id):
url = news_domain + '/v/feed/video/%s.js?template=fox' %video_id
data = json.loads(make_request(url))
items = data['channel']['item']['media-group']['media-content']
m3u8_url = [i['@attributes']['url'] for i in items if
i['@attributes']['type'] == 'application/x-mpegURL']
if m3u8_url:
return m3u8_url[0]
def get_smil(video_id):
if video_id.startswith('http'):
smil_url = video_id
else:
smil_url = news_domain + '/v/feed/video/%s.smil' %video_id
soup = get_soup(smil_url)
try:
base = soup.find('meta', attrs={'name': "rtmpAuthBase"})['content']
except:
base = soup.find('meta', attrs={'name': "httpBase"})['content']
dict_list = [{'url': i['src'], 'bitrate': i['system-bitrate']} for i in soup('video')]
path = user_select(dict_list)
addon_log('Resolved from smil: %s' %base + path)
return base + path.replace(' ', '')
def user_select(dict_list):
dialog = xbmcgui.Dialog()
ret = dialog.select('Choose a stream', ['Bitrate: %s' %i['bitrate'] for i in dict_list])
if ret > -1:
return dict_list[ret]['url']
def resolve_url(url):
succeeded = False
resolved_url = None
if isinstance(url, list):
resolved_url = user_select(url)
elif url.endswith('smil'):
resolved_url = get_smil(url)
elif url.endswith('.mp4') or url.endswith('.m3u8'):
resolved_url = url
if resolved_url:
succeeded = True
else:
resolved_url = ''
item = xbmcgui.ListItem(path=resolved_url)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), succeeded, item)
def get_playlist(url):
data = make_request(url)
pattern = 'pageVars.playlistId = "(.+?)";'
match = re.findall(pattern, data)
if not match:
addon_log('Did not find playlist id')
return
domain = news_domain
if business_domain in url:
domain = business_domain
json_url = domain + '/v/feed/playlist/%s.js?template=fox' %match[0]
json_data = json.loads(make_request(json_url), 'utf-8')
items = json_data['channel']['item']
for i in items:
item_url = None
state = i['media-status']['@attributes']['state']
title = i['title'].encode('utf-8')
if state != 'active':
addon_log('item state: %s: %s' %(title, state))
continue
try:
item_url = [x['@attributes']['url'] for
x in i['media-group']['media-content'] if
x['@attributes']['type'] == 'application/x-mpegURL'][0]
except:
addon_log('m3u8 url was not found: %s' %format_exc())
if not item_url:
try:
mp4_items = [{'url': x['@attributes']['url'],
'bitrate': x['@attributes']['bitrate']} for
x in i['media-group']['media-content'] if
x['@attributes']['type'] == 'video/mp4']
if not mp4_items or len(mp4_items) < 1:
raise
if len(mp4_items) == 1:
item_url = mp4_items[0]['url']
else:
item_url = mp4_items
except:
addon_log('mp4 url was not found: %s' %format_exc())
if not item_url:
try:
item_url = [x['@attributes']['url'] for
x in i['media-group']['media-content'] if
x['@attributes']['type'] == 'application/smil+xml'][0]
except:
addon_log('smil url was not found: %s' %format_exc())
if not item_url:
try:
enclosure_url = i['enclosure']['@attributes']['url']
if enclosure_url:
item_url = enclosure_url
else:
raise
except:
addon_log('addonException: get_playlist: unable to resolve url')
if not item_url:
continue
thumb = i['media-group']['media-thumbnail']['@attributes']['url']
date_time = datetime(*(time.strptime(i['pubDate'][:-6], '%a, %d %b %Y %H:%M:%S')[:6]))
info = {
'Title': title,
'Date': date_time.strftime('%d.%m.%Y'),
'Premiered': date_time.strftime('%d-%m-%Y'),
'Duration': get_duration(i['itunes-duration']),
'Plot': i['description'].encode('utf-8')
}
add_dir(title, item_url, thumb, 'resolve_url', info)
def get_duration(duration):
if duration is None:
return 1
d_split = duration.split(':')
if len(d_split) == 4:
del d_split[-1]
minutes = int(d_split[-2])
if int(d_split[-1]) >= 30:
minutes += 1
if len(d_split) >= 3:
minutes += (int(d_split[-3]) * 60)
if minutes < 1:
minutes = 1
return minutes
def get_params():
p = parse_qs(sys.argv[2][1:])
for i in p.keys():
p[i] = p[i][0]
return p
def add_dir(name, url, iconimage, mode, info={}):
params = {'name': name, 'url': url, 'mode': mode}
url = '%s?%s' %(sys.argv[0], urllib.urlencode(params))
listitem = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
isfolder = True
if mode == 'resolve_url':
isfolder = False
listitem.setProperty('IsPlayable', 'true')
listitem.setInfo(type="Video", infoLabels=info)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, listitem, isfolder)
params = get_params()
addon_log(repr(params))
try:
mode = params['mode']
except:
mode = None
if mode == None:
get_categories()
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode == 'get_categories':
get_categories(params['url'])
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode == 'get_sub_cat':
get_sub_categories(params['url'])
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode == 'get_playlist':
get_playlist(params['url'])
xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode == 'resolve_url':
resolve_url(params['url']) | Python |
# This file originally came from
# http://www.scons.org/cgi-sys/cgiwrap/scons/moin.cgi/NsisSconsTool
# I have edited it as required to work with the Debugmode Frameserver NSIS script.
#------------------------------------------
#
# NSIS Support for SCons
# Written by Mike Elkins, January 2004
# Provided 'as-is', it works for me!
"""
This tool provides SCons support for the Nullsoft Scriptable Install System
a windows installer builder available at http://nsis.sourceforge.net/home
To use it you must copy this file into the scons/SCons/Tools directory or use
the tooldir arg in the Tool function and put a line like 'env.Tool("NSIS")'
into your file. Then you can do 'env.Installer("foobar")' which will read foobar.nsi and
create dependencies on all the files you put into your installer, so that if
anything changes your installer will be rebuilt. It also makes the target
equal to the filename you specified in foobar.nsi. Wildcards are handled correctly.
In addition, if you set NSISDEFINES to a dictionary, those variables will be passed
to NSIS.
"""
import SCons.Builder
import SCons.Util
import SCons.Scanner
# NOTE (4 September 2007): The following import line was part of the original
# code on this wiki page before this date. It's not used anywhere below and
# therefore unnecessary. The SCons.Sig module is going away after 0.97.0d20070809,
# so the line should be removed from your copy of this module. There may be a
# do-nothing SCons.Sig module that generates a warning message checked in, so existing
# configurations won't break and can help point people to the line that needs removing.
#import SCons.Sig
import os.path
import glob
def nsis_parse( sources, keyword, multiple ):
"""
A function that knows how to read a .nsi file and figure
out what files are referenced, or find the 'OutFile' line.
sources is a list of nsi files.
keyword is the command ('File' or 'OutFile') to look for
multiple is true if you want all the args as a list, false if you
just want the first one.
"""
stuff = []
for s in sources:
c = s.get_contents()
for l in c.split('\n'):
semi = l.find(';')
if (semi != -1):
l = l[:semi]
hash = l.find('#')
if (hash != -1):
l = l[:hash]
# Look for the keyword
l = l.strip()
spl = l.split(None,1)
if len(spl) > 1:
if spl[0].capitalize() == keyword.capitalize():
arg = spl[1]
if arg.startswith('"') and arg.endswith('"'):
arg = arg[1:-1]
if multiple:
stuff += [ arg ]
else:
return arg
return stuff
def nsis_path( filename, nsisdefines, rootdir ):
"""
Do environment replacement, and prepend with the SCons root dir if
necessary
"""
# We can't do variables defined by NSIS itself (like $INSTDIR),
# only user supplied ones (like ${FOO})
varPos = filename.find('${')
while varPos != -1:
endpos = filename.find('}',varPos)
assert endpos != -1
if not nsisdefines.has_key(filename[varPos+2:endpos]):
raise KeyError ("Could not find %s in NSISDEFINES" % filename[varPos+2:endpos])
val = nsisdefines[filename[varPos+2:endpos]]
if type(val) == list:
if varPos != 0 or endpos+1 != len(filename):
raise Exception("Can't use lists on variables that aren't complete filenames")
return val
filename = filename[0:varPos] + val + filename[endpos+1:]
varPos = filename.find('${')
return filename
def nsis_scanner( node, env, path ):
"""
The scanner that looks through the source .nsi files and finds all lines
that are the 'File' command, fixes the directories etc, and returns them.
"""
if not os.path.exists(node.rstr()):
return []
nodes = []
source_dir = os.path.dirname(node.rstr())
for include in nsis_parse([node],'file',1):
exp = nsis_path(include,env['NSISDEFINES'],source_dir)
if type(exp) != list:
exp = [exp]
for p in exp:
# Why absolute path? Cause it breaks mysteriously without it :(
filename = os.path.abspath(os.path.join(str(source_dir),p))
nodes.append(filename)
return nodes
def nsis_emitter( source, target, env ):
"""
The emitter changes the target name to match what the command actually will
output, which is the argument to the OutFile command.
"""
nsp = nsis_parse(source,'outfile',0)
if not nsp:
return (target,source)
x = (
nsis_path(nsp,env['NSISDEFINES'],''),
source)
return x
def quoteIfSpaced(text):
if ' ' in text:
return '"'+text+'"'
else:
return text
def toString(item,env):
if type(item) == list:
ret = ''
for i in item:
if ret:
ret += ' '
val = toString(i,env)
if ' ' in val:
val = "'"+val+"'"
ret += val
return ret
else:
# For convienence, handle #s here
if str(item).startswith('#'):
item = env.File(item).get_abspath()
return str(item)
def runNSIS(source,target,env,for_signature):
ret = env['NSIS']+" "
if env.has_key('NSISFLAGS'):
for flag in env['NSISFLAGS']:
ret += flag
ret += ' '
if env.has_key('NSISDEFINES'):
for d in env['NSISDEFINES']:
ret += '/D'+d
if env['NSISDEFINES'][d]:
ret +='='+quoteIfSpaced(toString(env['NSISDEFINES'][d],env))
ret += ' '
for s in source:
ret += quoteIfSpaced(str(s))
return ret
def generate(env):
"""
This function adds NSIS support to your environment.
"""
env['BUILDERS']['Installer'] = SCons.Builder.Builder(generator=runNSIS,
src_suffix='.nsi',
emitter=nsis_emitter)
env.Append(SCANNERS = SCons.Scanner.Scanner( function = nsis_scanner,
skeys = ['.nsi']))
if not env.has_key('NSISDEFINES'):
env['NSISDEFINES'] = {}
env['NSIS'] = find_nsis(env)
def find_nsis(env):
"""
Try and figure out if NSIS is installed on this machine, and if so,
where.
"""
if SCons.Util.can_read_reg:
# If we can read the registry, get the NSIS command from it
try:
k = SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'SOFTWARE\\NSIS')
val, tok = SCons.Util.RegQueryValueEx(k,None)
ret = val + os.path.sep + 'makensis.exe'
if os.path.exists(ret):
return '"' + ret + '"'
else:
return None
except:
pass # Couldn't find the key, just act like we can't read the registry
# Hope it's on the path
return env.WhereIs('makensis.exe')
def exists(env):
"""
Is NSIS findable on this machine?
"""
if find_nsis(env) != None:
return 1
return 0
| Python |
import os
program_files = os.environ['ProgramFiles']
if not program_files.endswith('\\'):
program_files += '\\'
def SetupEnv(environ, vcver):
# Add the most commonly used libs as the default ones to save work in each target.
environ['LIBPATH'] = [
'../fscommon', # for the build targets one level below /src
'../../fscommon' # for the build targets two levels below /src
]
environ['LIBS'] = [
# Standard windows libraries
'shlwapi.lib',
'kernel32.lib',
'user32.lib',
'gdi32.lib',
'winspool.lib',
'comdlg32.lib',
'advapi32.lib',
'shell32.lib',
'ole32.lib',
'oleaut32.lib',
'uuid.lib',
'odbc32.lib',
'odbccp32.lib',
'winmm.lib',
# Frameserver related libraries
'common.lib',
]
# If the environment variables INCLUDE and LIB were set, use them instead of the
# default ones that SCons has created. This allows each developer to have their
# own install dir for each SDK and point them to the build with the environment
# variables.
if os.environ.has_key('INCLUDE'):
environ['ENV']['INCLUDE'] = environ['ENV']['INCLUDE'].rstrip(';') + ';' + os.environ['INCLUDE']
if os.environ.has_key('LIB'):
environ['ENV']['LIB'] = environ['ENV']['LIB'].rstrip(';') + ';' + os.environ['LIB']
if vcver == 'vc9_x64':
environ['ENV']['LIB'] = (os.path.join(program_files, 'Microsoft Visual Studio 9.0\\VC\\LIB\\amd64') + ';' +
os.path.join(program_files, 'Microsoft SDKs\\Windows\\v6.1\\lib\\x64'))
environ.PrependENVPath('PATH', os.path.join(program_files, 'Microsoft Visual Studio 9.0\\VC\\bin\\x86_amd64'))
environ.AppendENVPath('PATH', os.path.join(program_files, 'Microsoft SDKs\\Windows\\v6.1\\Bin'))
# Release configurations.
if int(ARGUMENTS.get('dbg', 0)):
out_dir = 'build/dbg'
ccflags9_x64 = ['/MDd', '/W3', '/Od', '/Fd', '/Gm', '/EHsc','/RTC1', '/Zi', '/errorReport:prompt']
ccpdbflags9_x64 = ['${(PDB and "/Zi") or ""}']
linkflags9_x64 = ['/machine:X64', '/DEBUG' , '/MANIFEST', '/MANIFESTUAC:level=\'asInvoker\' uiAccess=\'false\'', '/SUBSYSTEM:WINDOWS', '/DYNAMICBASE' , '/NXCOMPAT', '/ERRORREPORT:PROMPT']
cppdefines9_x64 = ['WIN64', 'UNICODE', '_UNICODE', '_DEBUG']
ccflags9 = ['/MDd', '/W3', '/Od', '/Fd', '/Gm', '/EHsc','/RTC1', '/ZI', '/errorReport:prompt']
ccpdbflags9 = ['${(PDB and "/ZI") or ""}']
linkflags9 = ['/machine:X86', '/DEBUG' , '/MANIFEST', '/MANIFESTUAC:level=\'asInvoker\' uiAccess=\'false\'', '/SUBSYSTEM:WINDOWS', '/DYNAMICBASE' , '/NXCOMPAT', '/ERRORREPORT:PROMPT']
cppdefines9 = ['WIN32', '_WINDOWS', 'UNICODE', '_UNICODE', '_DEBUG']
ccflags = ['/MTd', '/W3', '/Od', '/FD', '/GZ']
rcflags = ['/l', '0x409', '/d', '_DEBUG']
linkflags = ['/machine:I386']
cppdefines = ['WIN32', '_WINDOWS', '_MBCS', '_DEBUG']
else:
out_dir = 'build/opt'
ccflags9_x64 = ['/MD', '/W3', '/O2', '/Oi', '/GL', '/FD', '/Gy', '/EHsc', '/Zi', '/errorReport:prompt']
ccpdbflags9_x64 = ['${(PDB and "/Zi") or ""}']
linkflags9_x64 = ['/machine:X64', '/DEBUG' , '/MANIFEST', '/MANIFESTUAC:level=\'asInvoker\' uiAccess=\'false\'', '/SUBSYSTEM:WINDOWS', '/DYNAMICBASE' , '/NXCOMPAT', '/OPT:REF', '/OPT:ICF', '/LTCG', '/ERRORREPORT:PROMPT']
cppdefines9_x64 = ['WIN64', 'UNICODE', '_UNICODE', 'NDEBUG']
ccflags9 = ['/MD', '/W3', '/O2', '/Oi', '/GL', '/FD', '/EHsc', '/Zi', '/errorReport:prompt']
ccpdbflags9 = ['${(PDB and "/Zi") or ""}']
linkflags9 = ['/machine:X86', '/DEBUG' , '/MANIFEST', '/MANIFESTUAC:level=\'asInvoker\' uiAccess=\'false\'', '/SUBSYSTEM:WINDOWS', '/DYNAMICBASE' , '/NXCOMPAT', '/OPT:REF', '/OPT:ICF', '/LTCG', '/ERRORREPORT:PROMPT']
cppdefines9 = ['WIN32', '_WINDOWS', 'UNICODE', '_UNICODE', 'NDEBUG']
ccflags = ['/MD', '/W3', '/O1', '/FD']
rcflags = ['/l', '0x409', '/d', '_DEBUG']
linkflags = ['/machine:I386', '/filealign:512', '/map', '/opt:ref', '/opt:icf']
cppdefines = ['WIN32', '_WINDOWS', '_MBCS', 'NDEBUG']
if vcver == 'vc6':
ccflags += ['/GX']
else:
ccflags += ['/EHsc']
if vcver == 'vc9_x64':
environ['CCFLAGS'] = ccflags9_x64
environ['LINKFLAGS'] = linkflags9_x64
environ['CPPDEFINES'] = cppdefines9_x64
environ['CCPDBFLAGS'] = ccpdbflags9_x64
elif vcver == 'vc9':
environ['CCFLAGS'] = ccflags9
environ['LINKFLAGS'] = linkflags9
environ['CPPDEFINES'] = cppdefines9
environ['CCPDBFLAGS'] = ccpdbflags9
else:
environ['CCFLAGS'] += ccflags
environ['LINKFLAGS'] = linkflags
environ['CPPDEFINES'] = cppdefines
environ['CXXFLAGS'] = ['$(', '/TP', '$)'] #as in SCONS v2.x
environ['RCFLAGS'] += rcflags
environ['dbg'] = int(ARGUMENTS.get('dbg', 0))
environ['NSISFLAGS'] = ['/V2']
environ.Tool("nsis", toolpath=["scons_tools"])
environ.VariantDir(out_dir, 'src', duplicate=0)
# Check that the relevant build tools and libraries are installed
path = os.path.join(program_files + 'Microsoft SDKs\\Windows\\v6.1\\Bin')
if not os.path.exists(path):
print ('Unable to find Windows SDK 6.1 at "%s". Please download and install '
'Windows Software Development Kit (SDK) for Windows Server 2008 and .NET Framework 3.5' % path)
Exit(1)
paths = [
os.path.join(program_files, 'Microsoft SDKs\\Windows\\v6.1\\lib\\x64'),
os.path.join(program_files, 'Microsoft Visual Studio 9.0\\VC\\LIB\\amd64'),
os.path.join(program_files, 'Microsoft Visual Studio 9.0\\VC\\bin\\x86_amd64')
]
for path in paths:
if not os.path.exists(path):
print ('Unable to find x64 components of Windows SDK 6.1 at "%s". Please download and install '
'Windows Software Development Kit (SDK) for Windows Server 2008 and .NET Framework 3.5 '
'along with the x64 components.' % path)
Exit(1)
# Setup the environment for various versions of VC
env = Environment(MSVS_VERSION = '6.0')
env_vc9 = Environment(MSVS_VERSION = '9.0')
env_vc9_x64 = Environment(MSVS_VERSION = '9.0')
SetupEnv(env, 'vc6')
SetupEnv(env_vc9, 'vc9')
SetupEnv(env_vc9_x64, 'vc9_x64')
Export('env')
Export('env_vc9')
Export('env_vc9_x64')
# Build!
if int(ARGUMENTS.get('dbg', 0)):
env.SConscript('build/dbg/SConscript')
else:
env.SConscript('build/opt/SConscript')
| Python |
Import('env_vc9')
Import('env_vc9_x64')
# ---- libFileIO ----
fio_env = env_vc9.Clone()
fio_env['CPPDEFINES'] += ['_LIB']
fio_env['CPPPATH'] = ['../sdks/VegasV2/libFileIO']
fio_env['LIBS'].remove('common.lib')
fio_env['LIBS'] += ['rpcrt4.lib']
fio_env['LINKFLAGS'] += ['/IGNOREIDL']
target = 'libFileIO'
fio_env['PDB'] = target + '.pdb'
bin = fio_env.Library(
target,
[
'../sdks/VegasV2/libFileIO/SfAudioUtil.cpp',
'../sdks/VegasV2/libFileIO/SfMem.cpp',
'../sdks/VegasV2/libFileIO/SfReadStreams.cpp',
'../sdks/VegasV2/libFileIO/SfTemplate.cpp',
'../sdks/VegasV2/libFileIO/SfWaveFormat.cpp'
]
)
# ---- VegasV2 ----
env = env_vc9.Clone()
env['CPPDEFINES'] += ['_USRDLL']
env['CPPPATH'] = ['../sdks/VegasV2/libFileIO', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'].remove('common.lib')
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib', 'common_unicode.lib', 'libfileio.lib']
env['LIBPATH'] += ['../VegasV2']
env['LINKFLAGS'] += ['/IGNOREIDL']
target = 'dfscVegasV2Out'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'VegasFSMain.cpp',
'VegasFS.cpp',
'VegasFSRender.cpp',
'VegasFS.def',
env.RES('VegasFS.rc'),
]
)
# Add a post-build step to embed the manifest using mt.exe
# The number at the end of the line indicates the file type (1: EXE; 2:DLL).
if not env['dbg']:
env.AddPostAction(bin,
'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;2')
env.Install('#/src/dist/bin', bin[0])
# ---- libFileIO ----
fio_env64 = env_vc9_x64.Clone()
fio_env64['CPPDEFINES'] += ['_LIB']
fio_env64['CPPPATH'] = ['../sdks/VegasV2/libFileIO']
fio_env64['LIBS'].remove('common.lib')
fio_env64['LIBS'] += ['rpcrt4.lib']
fio_env64['LINKFLAGS'] += ['/IGNOREIDL']
target = 'libFileIO_x64'
fio_env64['PDB'] = target + '.pdb'
bin = fio_env64.Library(
target,
[
fio_env64.Object('SfAudioUtil64', '../sdks/VegasV2/libFileIO/SfAudioUtil.cpp'),
fio_env64.Object('SfMem64', '../sdks/VegasV2/libFileIO/SfMem.cpp'),
fio_env64.Object('SfReadStreams64', '../sdks/VegasV2/libFileIO/SfReadStreams.cpp'),
fio_env64.Object('SfTemplate64', '../sdks/VegasV2/libFileIO/SfTemplate.cpp'),
fio_env64.Object('SfWaveFormat64', '../sdks/VegasV2/libFileIO/SfWaveFormat.cpp')
]
)
# ---- VegasV2 ----
env64 = env_vc9_x64.Clone()
env64['CPPDEFINES'] += ['_USRDLL']
env64['CPPPATH'] = ['../sdks/VegasV2/libFileIO', '..', '../fscommon', '../dfsc', '../utils']
env64['LIBS'].remove('common.lib')
env64['LIBS'] += ['rpcrt4.lib', 'wininet.lib', 'common_unicode_x64.lib', 'libfileio_x64.lib']
env64['LIBPATH'] += ['../VegasV2']
env64['LINKFLAGS'] += ['/IGNOREIDL']
target = 'dfscVegasV264Out'
env64['PDB'] = target + '.pdb'
bin = env64.SharedLibrary(
target,
[
env64.Object('VegasFSMain64', 'VegasFSMain.cpp'),
env64.Object('VegasFS64', 'VegasFS.cpp'),
env64.Object('VegasFSRender64', 'VegasFSRender.cpp'),
'VegasFS.def',
env64.RES('VegasFS.rc64', 'VegasFS.rc'),
]
)
# Add a post-build step to embed the manifest using mt.exe
# The number at the end of the line indicates the file type (1: EXE; 2:DLL).
if not env64['dbg']:
env64.AddPostAction(bin,
'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;2')
env64.Install('#/src/dist/bin', bin[0])
| Python |
Import('env_vc9')
Import('env_vc9_x64')
# ------ Premiere Pro CS4 and below (32 bit build) ----
env_cs4 = env_vc9.Clone()
env_cs4['CPPDEFINES'] += ['_USRDLL', 'PRWIN_ENV', 'MSWindows', 'UNICODE', '_UNICODE']
env_cs4['RCFLAGS'] += ['/d', 'PRWIN_ENV']
env_cs4['CPPPATH'] = ['../sdks/Premiere/cs4', '..', '../fscommon', '../dfsc', '../utils']
env_cs4['LIBS'].remove('common.lib')
env_cs4['LIBS'] += ['rpcrt4.lib', 'wininet.lib', 'common_unicode.lib']
env_cs4['PDB'] = 'dfscPremiereOut.pdb'
bin = env_cs4.SharedLibrary(
'dfscPremiereOut',
[
'PremiereFS.cpp',
],
SHLIBSUFFIX = '.prm'
)
# Add a post-build step to embed the manifest using mt.exe
# The number at the end of the line indicates the file type (1: EXE; 2:DLL).
if not env_cs4['dbg']:
env_cs4.AddPostAction(bin,
'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;2')
env_cs4.Install('#/src/dist/bin', bin[0])
# ------ Premiere Pro CS5 and above (64 bit build) ----
env_cs5 = env_vc9_x64.Clone()
env_cs5['CPPDEFINES'] += ['_USRDLL']
env_cs5['RCFLAGS'] += ['/d', 'PRWIN_ENV']
env_cs5['CPPPATH'] = ['../sdks/Premiere/cs5/examples/headers', '..', '../fscommon', '../dfsc', '../utils']
env_cs5['LIBS'].remove('common.lib')
env_cs5['LIBS'] += ['rpcrt4.lib', 'wininet.lib', 'common_unicode_x64.lib']
env_cs5['PDB'] = 'dfscPremiereOutCS5.pdb'
bin = env_cs5.SharedLibrary(
'dfscPremiereOutCS5',
[
env_cs5.Object('PremiereFS_CS5', 'PremiereFS.cpp'),
],
SHLIBSUFFIX = '.prm'
)
# Add a post-build step to embed the manifest using mt.exe
# The number at the end of the line indicates the file type (1: EXE; 2:DLL).
if not env_cs5['dbg']:
env_cs5.AddPostAction(bin,
'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;2')
env_cs5.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
Import('env_vc9')
Import('env_vc9_x64')
# ---- ImageSequence.dll ----
is_env = env.Clone()
is_env['CPPDEFINES'] += ['_USRDLL', 'IMAGESEQUENCE_EXPORTS']
is_env['LIBS'] += ['gdiplus.lib', 'vfw32.lib']
target = 'ImageSequence'
is_env['PDB'] = target + '.pdb'
bin = is_env.SharedLibrary(
target,
[
'ImageSequence.cpp',
]
)
env.Install('#/src/dist/bin', bin[0])
# TODO: Uncomment this once we fix image sequence export from 64 bit processes.
# Build the x64 version of ImageSequence.dll using VC9
"""
is_x64_env = env_vc9_x64.Clone()
is_x64_env['CPPDEFINES'].remove('UNICODE')
is_x64_env['CPPDEFINES'].remove('_UNICODE')
is_x64_env['CPPDEFINES'] += ['_MBCS', '_USRDLL', 'IMAGESEQUENCE_EXPORTS']
is_x64_env['LIBS'] += ['gdiplus.lib', 'vfw32.lib']
target = 'ImageSequence-x64'
is_x64_env['PDB'] = target + '.pdb'
bin = is_x64_env.SharedLibrary(
target,
[
is_x64_env.Object('ImageSequence-x64', 'ImageSequence.cpp'),
]
)
env.Install('#/src/dist/bin', bin[0])
"""
# ---- fscommon.dll ----
fc_env = env.Clone()
fc_env['CPPDEFINES'] += ['_USRDLL']
fc_env['LINKFLAGS'] += ['/noentry']
target = 'fscommon'
fc_env['PDB'] = target + '.pdb'
bin = fc_env.SharedLibrary(
target,
[
env.RES('fscommon.rc'),
]
)
env.Install('#/src/dist/bin', bin[0])
# ---- common.lib ----
# Build the MBCS version of the library
cpppath = ['..', '../dfsc', '../utils']
co_env = env.Clone()
co_env['CPPPATH'] = cpppath
co_env.Library(
'common',
[
'autoupdate.cpp',
'blankavi.cpp',
'fscommon.cpp',
'../utils/utils.cpp',
]
)
# Build the UNICODE version of the library using VC8
co_uni_env = env_vc9.Clone()
co_uni_env['CPPPATH'] = cpppath
co_uni_env['CPPDEFINES'] += ['UNICODE', '_UNICODE']
co_uni_env.Library(
'common_unicode',
[
co_uni_env.Object('autoupdate-u', 'autoupdate.cpp'),
co_uni_env.Object('blankavi-u', 'blankavi.cpp'),
co_uni_env.Object('fscommon-u', 'fscommon.cpp'),
co_uni_env.Object('utils-u', '../utils/utils.cpp'),
]
)
# Build the UNICODE x64 version of the library using VC9
co_x64_env = env_vc9_x64.Clone()
co_x64_env['CPPPATH'] = cpppath
co_x64_env['CPPDEFINES'] += ['UNICODE', '_UNICODE']
co_x64_env.Library(
'common_unicode_x64',
[
co_x64_env.Object('autoupdate-u-x64', 'autoupdate.cpp'),
co_x64_env.Object('blankavi-u-x64', 'blankavi.cpp'),
co_x64_env.Object('fscommon-u-x64', 'fscommon.cpp'),
co_x64_env.Object('utils-u-x64', '../utils/utils.cpp'),
]
)
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL']
env['CPPPATH'] = ['../sdks/Wax', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib']
target = 'dfscWaxOut'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'WaxFS.cpp',
'WaxFS.def',
]
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL', 'EXPORT_VIO']
env['CPPPATH'] = ['../sdks/MediaStudioPro/include', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib']
target = 'dfscMSProOut'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'EntryPoints.cpp',
'MediaStudioProFS.def',
'MediaStudioProFS.cpp',
'Util.cpp',
],
SHLIBSUFFIX = '.vio'
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env.SConscript(
[
'dfsc/SConscript',
'EditStudio/SConscript',
'fscommon/SConscript',
'MediaStudioPro/SConscript',
'NetClient/SConscript',
'NetServer/SConscript',
'Premiere/SConscript',
'PremiereV2/SConscript',
'Vegas/SConscript',
'VegasV2/SConscript',
'Wax/SConscript',
'dist/SConscript',
]
)
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL']
env['CPPPATH'] = ['../sdks/Vegas/ffp', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib']
target = 'dfscVegasOut'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'VegasFSMain.cpp',
'VegasFS.cpp',
'VegasFSRender.cpp',
'../sdks/Vegas/ffp/SfHelpers.cpp',
'VegasFS.def',
env.RES('VegasFS.rc'),
]
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL']
target = 'dfsc'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'dfsc.cpp',
'dfsc.def',
]
)
env.Install('#/src/dist/bin', bin[0])
| Python |
SConscript(
[
'dfscacm/SConscript',
'dfscvfw/SConscript',
]
)
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL', 'DFSCACM_EXPORTS']
target = 'dfscacm'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'codec.c',
'dfscacm.def',
env.RES('codec.rc')
]
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL', 'PRWIN_ENV', 'MSWindows']
env['RCFLAGS'] += ['/d', 'PRWIN_ENV']
env['CPPPATH'] = ['../sdks/Premiere/compiler', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib']
target = 'cm-dfscPremiereOut'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'PremiereFS.cpp',
env.RES('PremiereFS.rc'),
],
SHLIBSUFFIX = '.prm'
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL']
env['CPPPATH'] = ['../sdks/EditStudio/include', '../sdks/EditStudio/src', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib']
target = 'dfscEditStudioOut'
env['PDB'] = target + '.pdb'
bin = env.SharedLibrary(
target,
[
'EditStudioFS.cpp',
'EditStudioFS.def',
],
SHLIBSUFFIX = '.eds_plgn'
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL']
env['CPPPATH'] = ['../sdks/Wax', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib', 'ws2_32.lib']
target = 'DFsNetClient'
env['PDB'] = target + '.pdb'
bin = env.Program(
target,
[
'NetClient.cpp',
]
)
env.Install('#/src/dist/bin', bin[0])
| Python |
Import('env')
env = env.Clone()
env['CPPDEFINES'] += ['_USRDLL']
env['CPPPATH'] = ['../sdks/Wax', '..', '../fscommon', '../dfsc', '../utils']
env['LIBS'] += ['rpcrt4.lib', 'wininet.lib', 'ws2_32.lib']
target = 'DFsNetServer'
env['PDB'] = target + '.pdb'
bin = env.Program(
target,
[
'NetServer.cpp',
]
)
env.Install('#/src/dist/bin', bin[0])
| Python |
import maya.cmds as cmds;
import maya.mel;
cmds.SelectAll();
cmds.Delete();
wallThickness = 2.0;
horizontalBoomFudge = 0.1;
boomWidth = 12.7 + horizontalBoomFudge;# 0 .5 in to mm
height = wallThickness + boomWidth/2.0;# just making it 3 mm to be an even metric number,
fudge = 0.6;
zipWidth = 5.0;
zipThickness= 1.0;
holeDiameter = 3.7084 + fudge;#6 screw chart width
blockSize = 23;
screwDiameter = 6.0;
def alignAndSubtract(object):
cmds.select(object[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.align(y='min',alignToLead=True);
cmds.select(object[0]);
cmds.move(0,wallThickness,0,relative=True);
cmds.select(borderBlock[0],object[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def removeSides(sign):
side = cmds.polyCube(w=blockSize, h=boomWidth/2.0 + wallThickness,d=blockSize);
cmds.move(sign*(blockSize/2.0 + boomWidth/2.0 + wallThickness),0,wallThickness*2+boomWidth,relative=True);
cmds.select(borderBlock[0],side[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def zipHorizontal(x,y):
zipBlock = cmds.polyCube(w=zipWidth, h=height,d=zipThickness);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def zipVertical(x,y):
zipBlock = cmds.polyCube(w=zipThickness, h=height*2.0,d=zipWidth);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
# borderBlock = cmds.polyCube(w=blockSize, h=(boomWidth/2.0 + wallThickness)/2.0,d=blockSize);
borderBlock = cmds.polyCube(w=boomWidth+wallThickness*2, h=boomWidth/2.0 + wallThickness,d=blockSize+2*boomWidth);
# cmds.select(borderBlock[0],pipeBlock[0]);
# borderBlock = cmds.polyBoolOp(op=1,useThresholds=1);
#
verticalBoom = cmds.polyCube(w=boomWidth, h=boomWidth,d=blockSize*4);
borderBlock = alignAndSubtract(verticalBoom);
borderBlock = zipVertical(-boomWidth/2.0-wallThickness,boomWidth/2.0);
borderBlock = zipVertical(boomWidth/2.0+wallThickness,boomWidth/2.0);
borderBlock = zipVertical(-boomWidth/2.0-wallThickness,boomWidth*1.5+blockSize-zipWidth);
borderBlock = zipVertical(boomWidth/2.0+wallThickness,boomWidth*1.5+blockSize-zipWidth);
riser = cmds.polyCube(w=blockSize+wallThickness*2.0, h=blockSize+wallThickness*2.0,d=blockSize+wallThickness*1.0);
cmds.select(riser[0],borderBlock[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(riser[0]);
cmds.move(0,-(blockSize+wallThickness*2.0),0,relative=True)
hole = cmds.polyCube(w=blockSize, h=blockSize,d=blockSize*2.0);
cmds.select(hole[0],riser[0],);
cmds.align(y='min',alignToLead=True);
cmds.select(hole[0]);
cmds.move(0,wallThickness,0,relative=True)
cmds.select(riser[0],hole[0]);
riser = cmds.polyBoolOp(op=2,useThresholds=1);
cmds.select(riser[0],borderBlock[0]);
borderBlock = cmds.polyBoolOp(op=1,useThresholds=1);
screwHole = cmds.polyCylinder(r=screwDiameter/2.0,h=height*10,sx=25);
cmds.select(borderBlock[0],screwHole[0]);
borderBlock = cmds.polyBoolOp(op=2,useThresholds=1);
cmds.rotate(90,0,0,r=True);
| Python |
import maya.cmds as cmds;
import maya.mel;
originalWidth = 10;
boomWidth = 12.7;# 0 .5 in to mm
fudge = 0.1;
horizontalBoomFudge = 0.1;
verticalBoomFudge = 0.1;#need to leave room for overhang and warping. #no longer needed since we aren't printing overhang
horizontalChange = boomWidth - originalWidth + horizontalBoomFudge;
verticalChange = boomWidth - originalWidth + horizontalBoomFudge;
holeDiameter = 3.7084;#6 screw chart width
oldHoleDiameter = 3.0;
newHoleDiameter = holeDiameter + fudge;
ratio = newHoleDiameter / oldHoleDiameter;
wallThickness = 3.5;
servoWidthDifference = 0.65;
zipWidth = 5.0;
zipThickness= 1.0;
def zipVertical(x,y):
zipBlock = cmds.polyCube(w=zipThickness, h=boomWidth*3.0,d=zipWidth);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(y='max',alignToLead=True);
cmds.align(x='min',alignToLead=True);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
cmds.SelectAll();
cmds.Delete();
cmds.file('C:/Users/Santiago/Documents/maya/scripts/boomMount.STL',i=True);
cmds.SelectAll();
boomMount = cmds.ls(sl=True)#work around for the fact twhat non polys don't have curve3[0] format
cmds.select(boomMount[0]);
cmds.scale(0.1,0.1,0.1);
cmds.rotate(-90,0,0);
cmds.select( "transform1.vtx[1]","transform1.vtx[3]","transform1.vtx[5]","transform1.vtx[7]", "transform1.vtx[83]","transform1.vtx[85]","transform1.vtx[87]","transform1.vtx[89]","transform1.vtx[91]","transform1.vtx[95]","transform1.vtx[99]","transform1.vtx[101]","transform1.vtx[117]","transform1.vtx[119]","transform1.vtx[123]","transform1.vtx[125]" ) ;
cmds.move(0,verticalChange,0,relative=True);
cmds.select( "transform1.vtx[0:7]");
cmds.move(-horizontalChange,0,0,relative=True);
cmds.select( "transform1.vtx[8:81]");
cmds.move(-horizontalChange/2.0,verticalChange/2.0,0,relative=True);
maya.mel.eval("scale -r -p -2.15973cm 1.01cm 1.5cm " + str(ratio) + " 1 " + str(ratio) + ";");#get this value by applying change through editor and seeing log
#move servo brace
cmds.select( "transform1.vtx[116:119]","transform1.vtx[122:125]");
cmds.move(servoWidthDifference,0,0,relative=True)
removeBlock = cmds.polyCube(w=boomWidth*2.0, h=boomWidth/2.0 + wallThickness,d=30);
cmds.select(removeBlock[0],"transform1");
cmds.align(y='max',alignToLead=True);
cmds.align(x='min',alignToLead=True);
cmds.align(z='min',alignToLead=True);
cmds.select(removeBlock[0]);
cmds.move(0,0.01,-0.01,relative=True);#need to add a little fudge for boolean logic
cmds.select("transform1",removeBlock[0]);
borderBlock = cmds.polyBoolOp(op=2,useThresholds=1);
borderBlock = zipVertical(-zipThickness/2.0,10);
borderBlock = zipVertical(-zipThickness/2.0+wallThickness*2.0+boomWidth+horizontalBoomFudge,10);
borderBlock = zipVertical(-zipThickness/2.0,24);
borderBlock = zipVertical(-zipThickness/2.0+wallThickness*2.0+boomWidth+horizontalBoomFudge,24);
cmds.select(borderBlock[0]);
cmds.rotate(90,0,0,r=True);
| Python |
import maya.cmds as cmds;
import maya.mel;
cmds.SelectAll();
cmds.Delete();
wallThickness = 4.0;
horizontalBoomFudge = 0.1;
boomWidth = 12.7 + horizontalBoomFudge;# 0 .5 in to mm
height = wallThickness + boomWidth/2.0;# just making it 3 mm to be an even metric number,
fudge = 0.6;
zipWidth = 5.0;
zipThickness= 1.0;
holeDiameter = 3.7084 + fudge;#6 screw chart width
blockSize = 50;
def alignAndSubtract(object):
cmds.select(object[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.align(y='min',alignToLead=True);
cmds.select(object[0]);
cmds.move(0,wallThickness,0,relative=True);
cmds.select(borderBlock[0],object[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def removeSides(sign):
side = cmds.polyCube(w=blockSize, h=boomWidth/2.0 + wallThickness,d=blockSize);
cmds.move(sign*(blockSize/2.0 + boomWidth/2.0 + wallThickness),0,wallThickness*2+boomWidth,relative=True);
cmds.select(borderBlock[0],side[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def zipHorizontal(x,y):
zipBlock = cmds.polyCube(w=zipWidth, h=height,d=zipThickness);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def zipVertical(x,y):
zipBlock = cmds.polyCube(w=zipThickness, h=height*2.0,d=zipWidth);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
borderBlock = cmds.polyCube(w=blockSize, h=(boomWidth/2.0 + wallThickness)/2.0,d=blockSize);
pipeBlock = cmds.polyCube(w=boomWidth+wallThickness*2, h=boomWidth/2.0 + wallThickness,d=blockSize+2*boomWidth);
cmds.select(pipeBlock[0],borderBlock[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(borderBlock[0],pipeBlock[0]);
borderBlock = cmds.polyBoolOp(op=1,useThresholds=1);
verticalBoom = cmds.polyCube(w=boomWidth, h=boomWidth,d=blockSize*2);
borderBlock = alignAndSubtract(verticalBoom);
borderBlock = zipVertical(-boomWidth/2.0-wallThickness,boomWidth/2.0);
borderBlock = zipVertical(boomWidth/2.0+wallThickness,boomWidth/2.0);
borderBlock = zipVertical(-boomWidth/2.0-wallThickness,boomWidth*1.5+blockSize-zipWidth);
borderBlock = zipVertical(boomWidth/2.0+wallThickness,boomWidth*1.5+blockSize-zipWidth);
cmds.rotate(90,0,0,r=True);
| Python |
import maya.cmds as cmds
cmds.SelectAll();
cmds.Delete();
wallThickness = 1.0;
cameraheight = 35.0;
cameraWidth = 43.0;
holderWidth = 45.0;
nexusHeight = 180.0;
nexusThickness = 10.5;
nexusHeightFudge = 0.1;
lipWidth = 5.0;
holeDiameter = 5.0;
leftHoleHeight = cameraheight/ 2.0 - 4.0;
leftHoleOffset = (cameraWidth / 2.0) - 0.8 - (holeDiameter /2.0) + 0.1;
rightHoleHeight = cameraheight/ 2.0 - 1.0;
rightHoleOffset = (cameraWidth / 2.0) - 2.8 - (holeDiameter /2.0) - 0.1;
lensHoleDiameter = 18.0;
lensHoleHeight = 16.2;
outer = cmds.polyCube(w=(cameraWidth+wallThickness*2), h=(nexusThickness + wallThickness*2),d=(nexusHeight+ cameraheight +wallThickness*3));
inner = cmds.polyCube(w=(cameraWidth+wallThickness*2), h=(nexusThickness + nexusHeightFudge),d=(nexusHeight));
innerCutter = cmds.polyCube(w=(cameraWidth+wallThickness*2), h=(nexusThickness*2),d=(nexusHeight - lipWidth*2));
cameraCutter = cmds.polyCube(w=(cameraWidth+wallThickness*2), h=(nexusThickness*2),d=(cameraheight + wallThickness));
leftHole = cmds.polyCylinder(sa=100,r=holeDiameter/2.0,h=nexusThickness*2)#by this point height is only wallthickness deep, so this should be plenty
rightHole = cmds.polyCylinder(sa=100,r=holeDiameter/2.0,h=nexusThickness*2)
lensHole = cmds.polyCylinder(sa=100,r=lensHoleDiameter/2.0,h=nexusThickness*2)
cmds.select(cameraCutter[0],outer[0]);
cmds.align(z='max',alignToLead=True);
cmds.select(lensHole[0],cameraCutter[0]);
cmds.align(z='mid',alignToLead=True);
cmds.select(lensHole[0]);
cmds.move(0,0,3,relative=True);#moving up to allow room for screws
cmds.select(leftHole[0],lensHole[0]);
cmds.align(z='mid',alignToLead=True);
cmds.select(leftHole[0]);
cmds.move(leftHoleOffset,0,-leftHoleHeight,relative=True);
cmds.select(rightHole[0],lensHole[0]);
cmds.align(z='mid',alignToLead=True);
cmds.select(rightHole[0]);
cmds.move(-rightHoleOffset,0,-rightHoleHeight,relative=True);
cmds.select(inner[0],outer[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(innerCutter[0],outer[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(innerCutter[0],inner[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(innerCutter[0]);
cmds.move(0,0,wallThickness+lipWidth,relative=True);
innerCutter2 = cmds.duplicate(innerCutter[0]);
cmds.select(innerCutter2);
cmds.scale((cameraWidth-2*wallThickness)/(cameraWidth+wallThickness*2),1,1,relative=True);
cmds.move(0,-wallThickness,0,relative=True);
cmds.select(inner[0]);
cmds.move(0,0,wallThickness,relative=True);
cmds.select(cameraCutter[0],outer[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(cameraCutter[0]);
cmds.move(0,wallThickness,0,relative=True);
cmds.select(outer[0],inner[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.select(outer[0],innerCutter[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.select(outer[0],innerCutter2[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.select(outer[0],cameraCutter[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.select(outer[0],leftHole[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.select(outer[0],rightHole[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.select(outer[0],lensHole[0]);#can't figure out why this is the proper order
outer = cmds.polyBoolOp(op=2);
cmds.rotate('90deg',0,0);
| Python |
import maya.cmds as cmds
if (not cmds.objExists("screwMountShader")):
screwMountShader = cmds.shadingNode('lambert', asShader=True,name="screwMountShader");
cmds.setAttr("screwMountShader.color",0.960784,0.0753556,0.0753556,type="double3");
wallThickness = 0.7;
baseThickness = 1.4;
boardBuffer = 1.0;#distance between board and box
mwSideLength = 40.0 + boardBuffer;
enclosureHeight = 20.0;
mountHoleRadius = 3.0/2;
mountHoleThickness = 1.0/2;
mountOuterRadius = mountHoleRadius + mountHoleThickness;
mountHoleDistance = 35;
strapWidth = 15;
strapHoleHeight = 2.3;
screwMountHeight = strapHoleHeight + wallThickness + 1.5;
def createScrewMount( x, z, object):
aMount = cmds.polyPipe(r=mountOuterRadius,h=screwMountHeight*2,t=mountHoleThickness)#polypipe bug, where height is created at half height. :(
cmds.move(x,(screwMountHeight/2.0 + baseThickness),z);
cmds.select(aMount[0]);
cmds.hyperShade(a="screwMountShader");
cmds.select(aMount[0],object[0]);
return cmds.polyBoolOp(op=1);
def createStrap(object):
strapOutter = cmds.polyCube(w=strapWidth+wallThickness*2, h=strapHoleHeight + wallThickness,d=mwSideLength+wallThickness);
cmds.move(0,strapHoleHeight/2.0 + baseThickness + wallThickness/2,0);
cmds.select(object[0],strapOutter[0]);
object = cmds.polyBoolOp(op=1);
strapInner = cmds.polyCube(w=strapWidth, h=strapHoleHeight,d=mwSideLength*2);
cmds.move(0,strapHoleHeight/2.0 + baseThickness,0);
cmds.select(object[0],strapInner[0]);
object = cmds.polyBoolOp(op=2);
cmds.SelectAll();
cmds.Delete();
enclosure = cmds.polyCube(w=(mwSideLength+wallThickness*2), h=(enclosureHeight),d=(mwSideLength+wallThickness*2));
inside = cmds.polyCube(w=(mwSideLength), h=enclosureHeight,d=(mwSideLength));
cmds.select(inside[0],r=True);
cmds.move(0,baseThickness, 0);
cmds.select(enclosure[0],inside[0],r=True);
enclosure = cmds.polyBoolOp(op=2);
cmds.move(0,(enclosureHeight/2), 0);
cmds.select(enclosure[0],r=True);
enclosure = createScrewMount(mountHoleDistance/2,mountHoleDistance/2,enclosure);
enclosure = createScrewMount(mountHoleDistance/2,-mountHoleDistance/2,enclosure);
enclosure = createScrewMount(-mountHoleDistance/2,mountHoleDistance/2,enclosure);
enclosure = createScrewMount(-mountHoleDistance/2,-mountHoleDistance/2,enclosure);
createStrap(enclosure);
| Python |
import maya.cmds as cmds
cmds.SelectAll();
cmds.Delete();
height = 43.0
circleDiameter = 120
motorDiameter = 82.5
baseThickness = 2#area that is square
topCylinderHeight = 6;
cubeSide = 120
wallThickness = 4
screwHoleDiameter = 5.0
strutRadius = 20
ventDiameter = 30.0
holeDistance = 105#refers to x/y not diagonal
def createVerticalHole( x, z, radius, object):
hole = cmds.polyCylinder(sa=100,r=radius,h=height*2.0)#polypipe bug, where height is created at half height. :(
cmds.move(x,0,z);
cmds.select(object[0],hole[0]);
return cmds.polyBoolOp(op=2);
def createStruts(degrees,object):
for i in xrange(0,360,degrees):
hole = cmds.polyCylinder(sa=100,r=strutRadius,h=height*2.0)#polypipe bug, where height is created at half height. :(
cmds.select(object[0],hole[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(hole[0]);
cmds.move(motorDiameter/2.0+strutRadius+wallThickness,baseThickness,0,relative=True);
cmds.rotate(0,i,0,p=(0,0,0));#rotate about origin
cmds.select(object[0],hole[0]);
object = cmds.polyBoolOp(op=2);
return object;
def createPartialCone(radius1,radius2,height):
coneHeight = (radius2*height/(radius1-radius2)) + height;
cutterCone = cmds.polyCone(sx=20,sy=30,sz=10,r=radius1,height=coneHeight);
cutterBox = cmds.polyCube(w=radius1*2.0+wallThickness, h=height,sy=5,d=radius1*2.0+wallThickness);#will be used to cut cone to size
cmds.select(cutterBox[0],cutterCone[0]);
cmds.align(y='min',alignToLead=True);
returnObject = cmds.polyBoolOp(op=3);
cmds.xform(cp=True);
cmds.move(0,0,0,ws=True,rpr=True);
return returnObject;
def createPartialHollowCone(radius1,radius2,height,thickness):
outterCone = createPartialCone(radius1+thickness,radius2+thickness,height);
innerCone = createPartialCone(radius1,radius2,height);
cmds.select(outterCone[0],innerCone[0]);
cmds.align(y='min',alignToLead=True);
returnObject = cmds.polyBoolOp(op=2);
cmds.xform(cp=True);
cmds.move(0,0,0,ws=True,rpr=True);
return returnObject;
def createSideHole(object,size,rotation,position):
hole = cmds.polyCylinder(sa=100,r=size,h=motorDiameter+wallThickness*2)
cmds.rotate('90deg',rotation,0);
cmds.select(object[0],hole[0]);
cmds.align(y='Max',alignToLead=True);
cmds.select(hole[0]);
cmds.move(0,position,0,relative=True);
cmds.select(object[0],hole[0]);
returnObject =cmds.polyBoolOp(object[0],hole[0],op=2);
return returnObject;
def createVentHole(object,size,rotation):
hole = cmds.polyCylinder(sa=100,r=size,h=height*10.0)#polypipe bug, where height is created at half height. :(
cmds.rotate('90deg',rotation,0);
cmds.select(object[0],hole[0]);
cmds.align(y='mid',alignToLead=True);
cmds.select(hole[0]);
cmds.select(object[0],hole[0]);
return cmds.polyBoolOp(op=2);
box = cmds.polyCube(w=cubeSide+wallThickness*2, h=baseThickness,sy=5,d=cubeSide+wallThickness*2)
#innerCircle = cmds.polyCylinder(sa=100,r=circleDiameter/2.0,h=height)#polypipe bug, where height is created at half height. :(
outterCone = createPartialCone(circleDiameter/2.0+wallThickness,motorDiameter/2.0+wallThickness,height)
innerCone = createPartialCone(circleDiameter/2.0,motorDiameter/2.0,height)
cmds.select(box[0]);
cmds.select(box[0],outterCone[0]);#can't figure out why this is the proper order
cmds.align(y='min',alignToLead=True);
shroudOutter = cmds.polyBoolOp(op=1);
cmds.select(shroudOutter[0],innerCone[0]);
shroudOutter = cmds.polyBoolOp(op=2);
shroudOutter = createVerticalHole(holeDistance/2.0,holeDistance/2.0,screwHoleDiameter/2.0,shroudOutter);
shroudOutter = createVerticalHole(holeDistance/2.0,-holeDistance/2.0,screwHoleDiameter/2.0,shroudOutter);
shroudOutter = createVerticalHole(-holeDistance/2.0,holeDistance/2.0,screwHoleDiameter/2.0,shroudOutter);
shroudOutter = createVerticalHole(-holeDistance/2.0,-holeDistance/2.0,screwHoleDiameter/2.0,shroudOutter);
shroudOutter = createStruts(45,shroudOutter);
top = cmds.polyPipe(sa=100,r=motorDiameter/2.0+wallThickness,h=topCylinderHeight*2.0,t=wallThickness)#polypipe bug, where height is created at half height. :(
cmds.select(shroudOutter[0],top[0]);#can't figure out why this is the proper order
cmds.align(y='max',alignToLead=True);
cmds.select(top[0]);
cmds.move(0,topCylinderHeight,0,relative=True);
cmds.select(shroudOutter[0],top[0]);#can't figure out why this is the proper order
shroudOutter = cmds.polyBoolOp(op=1);
shroudOutter = createSideHole(shroudOutter,screwHoleDiameter/2.0,-30,-2.0);
cmds.rotate('90deg',0,0);
| Python |
import maya.cmds as cmds;
cmds.SelectAll();
cmds.Delete();
def pin_solid( h=10.0, r=4.0, lh=3.0,lt=1.0):
curve2 = cmds.curve(d=1,ep=[
(0,0,0),
(r,0,0),
(r,h-lh,0),
(r+lt/2.0,h-lh+0.25*lh,0),
(r+lt/2.0,h-lh+0.50*lh,0),
(r-lt/2.0,h,0),
(0,h,0),
]);
curve2 = cmds.ls(sl=True)#work around
cmds.nurbsToPolygonsPref( pc=300 )
pin = cmds.revolve(curve2[0],ax=(0,1,0),p=(0,0,0),po=1,s=30,d=1);
centerCut = cmds.polyCube(w=r*0.5, h=h,sy=1,d=r*2+lt*2);
cmds.move(0,h/2.0+h/4.0,0);
leftCut = cmds.duplicate(centerCut[0]);
cmds.select(leftCut[0]);
cmds.move(1.125*r,0,0,relative=True);
rightCut = cmds.duplicate(centerCut[0]);
cmds.select(rightCut[0]);
cmds.move(-1.125*r,0,0,relative=True);
centerCylinder = cmds.polyCylinder(radius=r/2.5,h=h,sx=40);#will be trimmed later
cmds.move(0,h/2.0+h/4,0);
for s in [leftCut[0],rightCut[0],centerCylinder[0],centerCut[0]]:
cmds.select(pin[0],s);
pin = cmds.polyBoolOp(op=2);
cmds.select(curve2);
cmds.Delete();
return pin;
def pinHole(h=10, r=4, lh=3, lt=1, t=0.3, tight=True):
# h = shaft height
# r = shaft radius
# lh = lip height
# lt = lip thickness
# t = tolerance
# tight = set to false if you want a joint that spins easily
if(tight):
centerCylinder = cmds.polyCylinder(radius=r,h=h+0.2,sx=40);#will be trimmed later
else:
print "not tight"
centerCylinder = cmds.polyCylinder(radius=r+(t/2.0)+0.25,h=h+0.2,sx=40);#will be trimmed later
cmds.move(0,(h+0.2)/2.0,0);
curve = cmds.curve(d=1,ep=[
(0,0,0),
(r+(t/2)+(lt/2),0,0),
(r,lh/3.0,0),
(0,lh/3.0,0),
]);
curve = cmds.ls(sl=True)#work around
cmds.nurbsToPolygonsPref( pc=300 );
# widen the entrance hole to make insertion easier
bottomTip = cmds.revolve(curve[0],ax=(0,1,0),p=(0,0,0),po=1,s=30,d=1);
pinHole = pin_solid(h,r+(t/2.0),lh,lt);
cmds.select(curve);
cmds.Delete();
for s in [bottomTip[0],centerCylinder[0]]:
cmds.select(pinHole[0],s);
pinHole = cmds.polyBoolOp(op=1,useThresholds=1);
return pinHole;
# pin_solid() | Python |
import maya.cmds as cmds;
import pymel.core as pm;
cmds.SelectAll();
cmds.Delete();
pulleyRadius = 25;
ropeDiameter = 3;
lipHeight = 1;
screwDiameter = 7.9375;#5/16 in bolt to mm
wallthickness = 5;
washerThickness = 1.5875;#5/16 in bolt washer = 1/16 in thickness to mm
pulleyheight = ropeDiameter + 2*lipHeight;
enclosureDepth = 1.5*pulleyRadius + 2*ropeDiameter;
enclosureHeight = pulleyRadius + 1.5*screwDiameter;
enclosureWidth = 2*pulleyheight+2*wallthickness + 4*washerThickness + 0.1;#0.1 fudge factor
pulleyClearance = 2;#distance between pulley and bottom of cnclosure
guide = cmds.polyTorus( sx=20, sy=20, r=pulleyRadius, sr=(ropeDiameter/2.0) )
cmds.select(guide);
guide2 = pm.duplicate(guide,un=True);
pm.move(-5,0,0,guide2); | Python |
import maya.cmds as cmds;
import maya.mel;
fudge = 0.1;
holeDiameter = 3.7084;#6 screw chart width
oldHoleDiameter = 3.0;
newHoleDiameter = holeDiameter + fudge;
ratio = newHoleDiameter / oldHoleDiameter;
cmds.SelectAll();
cmds.Delete();
cmds.file('C:/Users/Santiago/Documents/maya/scripts/customMount.STL',i=True);
cmds.SelectAll();
motorMount = cmds.ls(sl=True)#work around for the fact twhat non polys don't have curve3[0] format
cmds.select(motorMount[0]);
cmds.scale(0.1,0.1,0.1);
cmds.rotate(-90,0,0);
cmds.select("transform1.vtx[911:925]","transform1.vtx[928:935]","transform1.vtx[938:951]","transform1.vtx[1047:1083]","transform1.vtx[1141:1167]","transform1.vtx[1169:1178]");
maya.mel.eval("scale -r -p 0.85cm 0.85cm 0.182025cm 1 " + str(ratio) + " " + str(ratio));
cmds.select("transform1");
cmds.scale(0.1,0.1,0.1);#not sure why this is necessary
cmds.rotate(0,0,0); | Python |
import maya.cmds as cmds;
# cmds.SelectAll();
# cmds.Delete();
wallthickness_mount = 2.0; #taken from strykercode as a starting point
def createScrewMount(x,y):
motorHoleRadius1 = 3.2/2.0; #actual = 3 adding fudge
motorHoleRadius2 = 6.2/2.0;#actual = 6 adding fudge
curve2 = cmds.curve(d=1,ep=[
(0,0,0),
(motorHoleRadius2,0,0),
(motorHoleRadius1,wallthickness_mount,0),
(0,wallthickness_mount,0),
]);
curve2 = cmds.ls(sl=True)#work around
cmds.nurbsToPolygonsPref( pc=300 )
hole = cmds.revolve(curve2[0],ax=(0,1,0),p=(0,0,0),po=1,s=25,d=1);
cmds.move(x,0,y);
cmds.select(curve2[0]);
cmds.Delete();
return hole;
def createMotorMount():
motorHolesRadius = 7.7/2.0;
xSeparation = 19.0;
ySeparation = 16.0;
base = cmds.polyCylinder(r=motorHolesRadius,h=wallthickness_mount,sx=25);
cmds.move(0,wallthickness_mount/2.0,0);
hole1 = createScrewMount(0,ySeparation/2.0);
hole2 = createScrewMount(0,-ySeparation/2.0);
hole3 = createScrewMount(xSeparation/2.0,0);
hole4 = createScrewMount(-xSeparation/2.0,0);
for h in [hole1[0],hole2[0],hole3[0],hole4[0]]:
cmds.select(base[0],h);
base = cmds.polyBoolOp(op=1,useThresholds=1);
return base;
| Python |
import maya.cmds as cmds
cmds.SelectAll();
cmds.Delete();
height = 10.0
cubeSide=208
circleDiameter = 232
wallThickness = 1
fanDiameter = 180
fanTubeHeight = wallThickness*2
tubeDiameter = 101.6#4 in
circleOutter = cmds.polyCylinder(sa=100,r=circleDiameter/2.0+wallThickness,h=height)#polypipe bug, where height is created at half height. :(
boxOutter = cmds.polyCube(w=cubeSide+wallThickness*2, h=height,sy=5,d=circleDiameter+wallThickness*2);
#cmds.move(0,0, -(circleDiameter/2.0+wallThickness*2));
cmds.select(boxOutter[0],circleOutter[0]);
shroudOutter = cmds.polyBoolOp(op=3);
circleInner = cmds.polyCylinder(sa=50,r=circleDiameter/2.0,h=height)#polypipe bug, where height is created at half height. :(
boxInner = cmds.polyCube(w=cubeSide, h=height,sy=5,d=circleDiameter+1);
#cmds.move(0,0, -(circleDiameter/2.0+wallThickness*2));
cmds.select(boxInner[0],circleInner[0]);
shroudInner = cmds.polyBoolOp(op=3);
cmds.move(0,-wallThickness, 0);
cmds.select(shroudOutter[0],shroudInner[0]);
shroud = cmds.polyBoolOp(op=2);
fanHousing = cmds.polyCylinder(sa=50,r=fanDiameter/2.0+wallThickness*2,h=height)
cmds.select(shroud[0],fanHousing[0]);
shroud = cmds.polyBoolOp(op=2);
#box = cmds.polyCube(w=cubeSide+wallThickness*2+1, h=height+1,sy=5,d=circleDiameter);
#cmds.move(0,0, -(circleDiameter/2.0));
#cmds.select(shroud[0],box[0]);
#shroud = cmds.polyBoolOp(op=3);
#cmds.rotate('270deg',0,0);
fanFlat = cmds.polyPipe(sa=100,r=fanDiameter/2.0+wallThickness*2,h=wallThickness*2,t=wallThickness*2)#polypipe bug, where height is created at half height. :(
cmds.move(0,wallThickness/2.0, 0);
fanTube = cmds.polyPipe(sa=100,r=fanDiameter/2.0,h=fanTubeHeight*2,t=wallThickness)#polypipe bug, where height is created at half height. :(
cmds.move(0,fanTubeHeight/2.0, 0);
coneOutter = cmds.polyCone(sa=100,r=fanDiameter/2.0,h=fanDiameter/2.0)
cmds.move(0,fanDiameter/4.0+fanTubeHeight, 0);
fanPipe = cmds.polyCylinder(sa=100,r=tubeDiameter/2.0+wallThickness,h=fanDiameter/2.0);
cmds.move(0,fanDiameter/4.0, 0);
cmds.select(coneOutter[0],fanPipe[0]);
shroud = cmds.polyBoolOp(op=1);
#objects = cmds.polySeparate(shroud);
#cmds.select(objects[0])
# cmds.Delete();
# cmds.select(objects[1])
#cmds.rotate('90deg',0,0); | Python |
import maya.cmds as cmds
import mount_2826_6 as mount;
cmds.SelectAll();
cmds.Delete();
length = 50;
height = 10.0;
taperAmount = 1.6619/4.3146;
baseHoleRadius = (3.2/2.0); #hole width is 3 mm using 4.5 for fudge factor
baseHoleWidth = baseHoleRadius*2.0;
closerHoleDistance = 46.23 + baseHoleWidth;
fartherHoleDistance = 68.74+ baseHoleWidth;
frontToBackDistance = 32.84 + baseHoleWidth;
firstHoleYoffset = 5.6; #distance from hole closest to back of mount to back of mount
wallThickness = 1.1;
#--motor mount specifics
motorMountZ = 26.0;
motorBoxWidth = 27.0;
motorBoxHeight = motorBoxWidth / 2.0 + motorMountZ;
frontMotorMountHeight = 2.857;
frontMotorMountWidth = 33.238;
def createStrykerCurve():
curveFace = cmds.polyCreateFacet( p=[
(-4.3146,0,0),
(-3.6198,0.0339,0),
(-2.6207,0.4996,0),
(-1.6215,0.8975,0),
(-0.6224,1.0669,0),
(0.6224,1.0669,0),
(1.6215,0.8975,0),
(2.6207,0.4996,0),
(3.6198,0.0339,0),
(4.3146,0,0)]);
cmds.polyExtrudeFacet((curveFace[0] + '.f[0]'), thickness= length/10,d=4);#divide by 10 for conversion
latticeDx = 10;
latticeDy = 2;
latticeDz = 5;
cmds.select(curveFace[0]);
cmds.lattice( dv=(latticeDx,latticeDy, latticeDz), oc=True );
handle = cmds.ls(sl=True)#work around for the fact twhat non polys don't have curve3[0] format
handleObject = handle[0].replace("Lattice","")
cmds.setAttr(handleObject + '.local',1);#necessary for 1 to 1 movement
curveModifier = 9.682;# how far to come down
startHeight = 10.669;
middleHeight = 8.107;
endHeight = 7.519;
controlPointY = (middleHeight - (0.25*startHeight + 0.25*endHeight))*2.0;
curveAmount = 0;#in percent of difference
for i in range(0,latticeDz):
cmds.select(handle[0] + '.pt[0:' + str(latticeDx-1) + '][1:' + str(latticeDy-1) + '][' + str(i) + ':' + str(i) + ']');
scaledInput = i/float(latticeDz-1);#scales to -1 to 1
position = (1-scaledInput)*(1-scaledInput)*startHeight + 2*(1-scaledInput)*scaledInput*controlPointY + scaledInput*scaledInput*endHeight;
print(i,scaledInput,position,middleHeight);
cmds.move(position,y=True);
cmds.select(curveFace[0]);
cmds.lattice( dv=(2,2,2), oc=True );
handle = cmds.ls(sl=True)#work around for the fact twhat non polys don't have curve3[0] format
handleObject = handle[0].replace("Lattice","")
cmds.setAttr(handleObject + '.local',1);#necessary for 1 to 1 movement
cmds.select(handle[0] + '.pt[0:1][1][1]');
cmds.move(2.857,y=True);#move to proper height
cmds.select(handle[0] + '.pt[0][0:1][1]');
cmds.move(-16.619,x=True);#move front in on one side
cmds.select(handle[0] + '.pt[1][0:1][1]');
cmds.move(16.619,x=True);#move front in on other side
cmds.delete(curveFace[0], constructionHistory=True);#need to delete history to make things permanent
cmds.select(curveFace[0]);
return curveFace;
# cmds.setAttr(handle[0] + '.rotateX',90);
# cmds.setAttr(handle[0] + '.translateY',0);
# cmds.setAttr(handle[0] + '.scaleY',5.0);
# cmds.setAttr(handle[0] + '.translateZ',0);
#cmds.select(curveFace[0]);
#cmds.delete(curveFace[0], constructionHistory=True);#need to delete history to make things permanent
#second curve for linear squishing
# cmds.nonLinear(type='flare',curve=-0.0,ds=1);
# handle = cmds.ls(sl=True)#work around for the fact that non polys don't have curve3[0] format
# handleObject = handle[0].replace("Handle","")
# cmds.setAttr(handle[0] + '.rotateX',90);
# cmds.setAttr(handle[0] + '.translateY',0);
# cmds.setAttr(handle[0] + '.scaleY',5.0);
# cmds.setAttr(handle[0] + '.translateZ',0);
# Lock an attribute to prevent further modification
#cmds.setAttr( handle[0] + '.endFlareZ', lock=False )#need to unlock first
#cmds.polyExtrudeFacet( (curveFace[0] + '.f[0]'), kft=False, ltz=2, inputCurve=curve3[0],divisions=10,taper=taperAmount,ch=True);
# return curveFace;
vertCone = cmds.polySphere(r=motorBoxHeight);
vertCone2 = cmds.polyCylinder(r=motorBoxHeight,h=motorBoxHeight*2,sx=40);#will be trimmed later
cmds.rotate('90deg',0,0);
cmds.move(0,0,motorBoxHeight);
cmds.select(vertCone2[0],vertCone[0]);#order matters, try it the other way and it won't work.
vertCone = cmds.polyBoolOp(op=1,ch=1);
cmds.scale(0.5,1,1);
boundingBox = cmds.polyCube(w=motorBoxHeight, h=motorBoxHeight,sy=1,d=length);
cmds.move(0,motorBoxHeight/2,-length/2);
cmds.select(vertCone[0],boundingBox[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(boundingBox[0],vertCone[0]);
vertCone = cmds.polyBoolOp(op=3,ch=1);
aBoxLength = 50
aBoxWidth = 85
aBoxThickness = 0.5
A = createStrykerCurve();
#cmds.rotate(0,'90deg',0);
def createPlate(thickness):
basePlate = cmds.polyCreateFacet( p=[
(-3.1875,0,2.5),
(-3.7655,0,1.5),
(-4.1395,0,0.5),
(-4.3095,0,-0.5),
(-4.2755,0,-1.5),
(-4.0375,0,-2.5),
(4.0375,0,-2.5),
(4.2755,0,-1.5),
(4.3095,0,-0.5),
(4.1395,0,0.5),
(3.7655,0,1.5),
(3.1875,0,2.5),
]);
cmds.polyExtrudeFacet((basePlate[0] + '.f[0]'), thickness= thickness);#divide by 10 for conversion
basePlate = cmds.ls(sl=True)#work around for the fact that non polys don't have curve3[0] format
cmds.select(basePlate[0],A[0]);
cmds.align(z='max',alignToLead=True);
cmds.align(y='min',alignToLead=True);
return basePlate;
basePlate = createPlate(aBoxThickness/10.0);
cmds.select(basePlate[0],A[0]);
A = cmds.polyBoolOp(op=1,ch=1,useThresholds=1);
baseSub = createPlate(motorBoxHeight/10.0);
cmds.select(baseSub[0],A[0]);
A = cmds.polyBoolOp(op=3,ch=1,useThresholds=1);
# cmds.select(vertCone[0]);
#
B = createStrykerCurve();
#
cmds.move(0,-aBoxThickness,0,relative=True);
#
cmds.select(A[0],B[0]);
A = cmds.polyBoolOp(op=2,ch=0,useThresholds=1);
C = createStrykerCurve();
cmds.select(vertCone[0],C[0])
vertCone = cmds.polyBoolOp(op=2,ch=0,useThresholds=1);
cmds.move(0,-0.01,0,relative=True);
cmds.select(vertCone[0],A[0]);
A = cmds.polyBoolOp(op=1);
diff = cmds.polyCube(w=motorBoxWidth, h=motorBoxWidth,d=length);
cmds.select(diff[0],A[0]);
cmds.align(z='max',alignToLead=True);
cmds.align(y='max',alignToLead=True);
cmds.select(diff[0]);
cmds.move(0,0,-wallThickness,relative=True);
# A_temp = cmds.duplicate(A[0]);
# diff_temp = cmds.duplicate(diff[0]);
# cmds.select(A_temp[0],diff_temp[0]);
# plug = cmds.polyBoolOp(op=3);
cmds.select(A[0],diff[0]);
A = cmds.polyBoolOp(op=2);
# oldbase was at 25, cylinder is at 16.2, diff = 8.8
hole1 = cmds.polyCylinder(r=baseHoleRadius,h=(wallThickness*3),sx=40);
cmds.move((-0.5*closerHoleDistance),0,( - baseHoleWidth - firstHoleYoffset));
hole2 = cmds.polyCylinder(r=baseHoleRadius,h=(wallThickness*3),sx=40);
cmds.move((0.5*closerHoleDistance),0,( - baseHoleWidth - firstHoleYoffset));
hole3 = cmds.polyCylinder(r=baseHoleRadius,h=(wallThickness*3),sx=40);
cmds.move((0.5*fartherHoleDistance),0,( - baseHoleWidth - firstHoleYoffset - frontToBackDistance));
hole4 = cmds.polyCylinder(r=baseHoleRadius,h=(wallThickness*3),sx=40);
cmds.move((-0.5*fartherHoleDistance),0,( - baseHoleWidth - firstHoleYoffset - frontToBackDistance));
for h in [hole1[0],hole2[0],hole3[0],hole4[0]]:
cmds.select(A[0],h);
A = cmds.polyBoolOp(op=2,useThresholds=1);
motorMount = mount.createMotorMount();
cmds.select(motorMount[0]);
cmds.move(0,motorMountZ,0);
cmds.rotate(90,0,0);
cmds.move(0,0,-mount.wallthickness_mount,relative=True);
cmds.select(A[0],motorMount[0]);
cmds.polyBoolOp(op=2);
cmds.rotate(0,180,0);
| Python |
import maya.cmds as cmds;
import maya.mel;
cmds.SelectAll();
cmds.Delete();
wallThickness = 4.0;
horizontalBoomFudge = 0.1;
boomWidth = 12.7 + horizontalBoomFudge;# 0 .5 in to mm
height = wallThickness + boomWidth/2.0;# just making it 3 mm to be an even metric number,
fudge = 0.6;
zipWidth = 5.0;
zipThickness= 1.0;
holeDiameter = 3.7084 + fudge;#6 screw chart width
blockSize = 50;
def alignAndSubtract(object):
cmds.select(object[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.align(y='min',alignToLead=True);
cmds.select(object[0]);
cmds.move(0,wallThickness,wallThickness,relative=True);
cmds.select(borderBlock[0],object[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def removeSides(sign):
side = cmds.polyCube(w=blockSize, h=boomWidth/2.0 + wallThickness,d=blockSize);
cmds.move(sign*(blockSize/2.0 + boomWidth/2.0 + wallThickness),0,wallThickness*2+boomWidth,relative=True);
cmds.select(borderBlock[0],side[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def zipHorizontal(x,y):
zipBlock = cmds.polyCube(w=zipWidth, h=height,d=zipThickness);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
def zipVertical(x,y):
zipBlock = cmds.polyCube(w=zipThickness, h=height,d=zipWidth);
cmds.select(zipBlock[0],borderBlock[0]);
cmds.align(z='min',alignToLead=True);
cmds.select(zipBlock[0]);
cmds.move(x,0,y,relative=True);
cmds.select(borderBlock[0],zipBlock[0]);
return cmds.polyBoolOp(op=2,useThresholds=1);
borderBlock = cmds.polyCube(w=blockSize, h=boomWidth/2.0 + wallThickness,d=blockSize);
horizontalBoom = cmds.polyCube(w=blockSize*2, h=boomWidth,d=boomWidth);
verticalBoom = cmds.polyCube(w=boomWidth, h=boomWidth,d=blockSize*2);
borderBlock = alignAndSubtract(horizontalBoom);
borderBlock = alignAndSubtract(verticalBoom);
borderBlock = removeSides(1.0);
borderBlock = removeSides(-1.0);
borderBlock = zipHorizontal((blockSize/2.0-boomWidth/2.0-wallThickness)/2.0+boomWidth/2.0+wallThickness,-zipThickness/2.0);
borderBlock = zipHorizontal(-((blockSize/2.0-boomWidth/2.0-wallThickness)/2.0+boomWidth/2.0+wallThickness),-zipThickness/2.0);
borderBlock = zipHorizontal((blockSize/2.0-boomWidth/2.0-wallThickness)/2.0+boomWidth/2.0+wallThickness,-zipThickness/2.0+wallThickness*2.0+boomWidth);
borderBlock = zipHorizontal(-((blockSize/2.0-boomWidth/2.0-wallThickness)/2.0+boomWidth/2.0+wallThickness),-zipThickness/2.0+wallThickness*2.0+boomWidth);
borderBlock = zipVertical(boomWidth/2.0+wallThickness,wallThickness*3.0+boomWidth);
borderBlock = zipVertical(-boomWidth/2.0-wallThickness,wallThickness*3.0+boomWidth);
borderBlock = zipVertical(boomWidth/2.0+wallThickness,wallThickness*3.0+boomWidth*2.0);
borderBlock = zipVertical(-boomWidth/2.0-wallThickness,wallThickness*3.0+boomWidth*2.0);
cmds.rotate(90,0,0,r=True);
| Python |
import maya.cmds as cmds;
import createPin;
cmds.SelectAll();
cmds.Delete();
outsideDiameter = 85.24;
insideDiameter = 74.28;
heightToTopPeg = 7.0;
pegDiameter = 4.2;
peg2peg = 63.9;
pegOffset = 5.6;#peg isn't in center of circle
#height = 2*(heightToTopPeg - pegDiameter) + pegDiameter;
height = 9.3;#changed this so I can change pegDiameter independently
wireChannelThickness = 2.0;
wireChannelDepth = height / 2.0;
bandWidth = 25;
bandThickness = 4.6;# fudge to make boolean easier
bandRadius = 83.63;#measured from headset band, using chord to radius formula
bandDiameter = bandRadius*2.0;
bandBlockOffset = 5.0;
bandInsideHole = 2.0;
bandWallThickness = 1.0;
pinHeight = 10.0;
pinRadius = 4.0;
#using cylinders vs pipes because of pipe bugs
outside = cmds.polyCylinder(r=outsideDiameter/2.0,h=height,sx=40);
inside = cmds.polyCylinder(r=insideDiameter/2.0,h=height*2,sx=40);
peg = cmds.polyCylinder(r=pegDiameter/2.0,h=(outsideDiameter+insideDiameter)/2.0,sx=40);
cmds.move(pegOffset,0,0);
cmds.rotate('90deg',0,0);
cmds.select(outside[0],inside[0]);
hull = cmds.polyBoolOp(op=2);
# hullCutter = cmds.duplicate(hull[0]);
# cmds.move(0,height,0);
cmds.select(hull[0]);
borderBlockWidth = outsideDiameter/2;
borderBlock = cmds.polyCube(w=borderBlockWidth, h=height*2,d=outsideDiameter*1.5);
cmds.select(borderBlock[0],hull[0]);
cmds.align(x='min',alignToLead=True);
cmds.select(hull[0],borderBlock[0]);
hull = cmds.polyBoolOp(op=3);#order matters
fudge = 0.1;
flatSection = cmds.polyCube(w=(pegOffset+fudge), h=height,d=outsideDiameter);
cmds.move(pegOffset/2.0-fudge/2.0,0,0);
cmds.select(hull[0],flatSection[0]);
hull = cmds.polyBoolOp(op=1);
rounder = cmds.polyCylinder(r=height/2.0,h=outsideDiameter,sx=40);
cmds.move(pegOffset,0,0);
cmds.rotate('90deg',0,0);
cmds.select(rounder[0],hull[0]);
hull = cmds.polyBoolOp(op=1,useThresholds=1);#useThresholds had to be set to 1 for this to work
#figured this out by trying the operation using maya and seeing what was in the log when it worked
removeBlock1 = cmds.polyCube(w=(height/2.0+pegOffset+fudge), h=height*2,d=insideDiameter);
cmds.select(removeBlock1[0],hull[0]);
cmds.align(x='max',alignToLead=True);
cmds.select(hull[0],removeBlock1[0]);
hull = cmds.polyBoolOp(op=2);
cmds.select(hull[0],peg[0]);
hull = cmds.polyBoolOp(op=1);
removeBlock2 = cmds.polyCube(w=(height/2.0+pegOffset+fudge), h=height*2,d=peg2peg);
cmds.select(removeBlock2[0],hull[0]);
cmds.align(x='max',alignToLead=True);
cmds.select(hull[0],removeBlock2[0]);
hull = cmds.polyBoolOp(op=2);
#create wirechannel
centerDiameter = (outsideDiameter+insideDiameter)/2.0;
wireOutsideDiameter = centerDiameter+wireChannelThickness;
wireInsideDiameter = centerDiameter-wireChannelThickness;
outside = cmds.polyCylinder(r=wireOutsideDiameter/2.0,h=wireChannelDepth,sx=40);
inside = cmds.polyCylinder(r=wireInsideDiameter/2.0,h=wireChannelDepth,sx=40);
cmds.select(outside[0],inside[0]);
wireGuide = cmds.polyBoolOp(op=2);
#cut in half
borderBlockWidth = wireOutsideDiameter/2;
borderBlock = cmds.polyCube(w=borderBlockWidth, h=height*2,d=outsideDiameter*1.5);
cmds.select(borderBlock[0],wireGuide[0]);
cmds.align(x='min',alignToLead=True);
cmds.select(wireGuide[0],borderBlock[0]);
wireGuide = cmds.polyBoolOp(op=3);#order matters
#
fudge = 0.1;
flatSectionWidth =pegOffset+wireChannelThickness/2.0;#pegOffset + fudge puts the edge in line with center of peg, we need half of the
#wireChannelThickness in order to create guide
flatSection1 = cmds.polyCube(w=flatSectionWidth, h=wireChannelDepth,d=wireChannelThickness);
cmds.move(flatSectionWidth/2.0,wireChannelDepth/2.0,centerDiameter/2.0);
flatSection2 = cmds.polyCube(w=flatSectionWidth, h=wireChannelDepth,d=wireChannelThickness);
cmds.move(flatSectionWidth/2.0,wireChannelDepth/2.0,-centerDiameter/2.0);
cmds.select(flatSection1[0],wireGuide[0]);
cmds.align(y='min',alignToLead=True);
wireGuide = cmds.polyBoolOp(op=1);
cmds.select(flatSection2[0],wireGuide[0]);
cmds.align(y='min',alignToLead=True);
wireGuide = cmds.polyBoolOp(op=1);
flatSection3 = cmds.polyCube(w=wireChannelThickness, h=wireChannelDepth,d=centerDiameter);
cmds.move(pegOffset,wireChannelDepth/2.0,0);
#cmds.select(flatSection3[0],wireGuide[0]);
#wireGuide = cmds.polyBoolOp(op=1);
#
#
#fudge = 0.1;
#removeBlock3 = cmds.polyCube(w=flatSectionWidth, h=height/2.0,d=wireInsideDiameter);
#cmds.move((flatSectionWidth)/2.0,0,0);
#cmds.select(flatSection[0],removeBlock3[0]);
#flatSection = cmds.polyBoolOp(op=2);
#cmds.select(wireGuide[0],flatSection[0]);
cmds.select(wireGuide[0],hull[0]);
cmds.align(y='max',alignToLead=True);
# #offset block
block = cmds.polyCube(w=bandWidth/2.0, h=height + bandBlockOffset+pinHeight/2.0,d=bandWidth);
cmds.select(block[0],hull[0]);
cmds.align(x='min',alignToLead=True);
cmds.align(y='min',alignToLead=True);
cmds.select(block[0]);
cmds.move(-bandWidth/4-1.0,-pinHeight/2.0,0,relative=True);#0.5 for overlap reasons
#create band
bandOutsideDiameter = bandDiameter+bandThickness;
bandInsideDiameter = bandDiameter-bandThickness;
outside = cmds.polyCylinder(r=bandOutsideDiameter/2.0,h=bandWidth,sx=100);
inside = cmds.polyCylinder(r=bandInsideDiameter/2.0,h=bandWidth,sx=100);
cmds.select(outside[0],inside[0]);
band = cmds.polyBoolOp(op=2);
bandOutsideDiameter = bandDiameter+bandInsideHole;
bandInsideDiameter = bandDiameter-bandInsideHole;
# outside = cmds.polyCylinder(r=bandOutsideDiameter/2.0,h=bandWidth-bandWallThickness*2.0,sx=100);
# inside = cmds.polyCylinder(r=bandInsideDiameter/2.0,h=bandWidth-bandWallThickness*2.0,sx=100);
outside = cmds.polyCylinder(r=bandOutsideDiameter/2.0,h=bandWidth*2.0,sx=100);
inside = cmds.polyCylinder(r=bandInsideDiameter/2.0,h=bandWidth*2.0,sx=100);
cmds.select(outside[0],inside[0]);
bandInside = cmds.polyBoolOp(op=2);
cmds.select(bandInside[0],band[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(bandInside[0]);
cmds.move(0,bandWallThickness,0,relative=True);
band2 = cmds.duplicate(bandInside[0]);
# cmds.xform(ws=True, rotatePivot=(-bandDiameter/2.0,0,0));#move pivot to edge of band so rotation makes more sense
# cmds.rotate('90deg',0,'70deg');
cmds.select(band[0],bandInside[0]);
band = cmds.polyBoolOp(op=2);
def createCurve(curveShape,borderBlockIn):
borderBlock = cmds.polyCube(w=bandOutsideDiameter/2.0, h=bandWidth*2,d=borderBlockIn);
cmds.select(borderBlock[0],curveShape[0]);
cmds.align(x='min',alignToLead=True);
cmds.select(borderBlock[0]);
cmds.move(0,0,-borderBlockWidth/2.0,relative=True)
cmds.select(borderBlock[0],curveShape[0]);
curveShape = cmds.polyBoolOp(op=3,useThresholds=1);
cmds.select(curveShape[0]);
cmds.xform(ws=True, rotatePivot=(-bandDiameter/2.0,0,0));#move pivot to edge of band so rotation makes more sense
cmds.rotate('90deg',0,'70deg');
cmds.move(bandDiameter/2.0-outsideDiameter/2.0,height/2.0-bandThickness,0);
cmds.move(0,bandBlockOffset,0,relative=True);
return curveShape;
borderBlockWidth = 60.0;
band = createCurve(band,borderBlockWidth);
band2 = createCurve(band2,borderBlockWidth);
cmds.xform( cp=True );#center pivot
# band2 = cmds.duplicate(band[0]);
# cmds.select(band2[0]);
# cmds.scale(1,wireChannelThickness/bandWidth,1,relative=True);
# cmds.move(bandThickness/2.0,bandThickness/2.0,bandWidth*0.3,relative=True);
cmds.select(block[0],band2[0]);
block = cmds.polyBoolOp(op=2);
# cmds.select(band[0],hullCutter[0]);
# band = cmds.polyBoolOp(op=2);
# cmds.select(band[0],hull[0]);
# hull = cmds.polyBoolOp(op=1);
pin = createPin.pin_solid( h=pinHeight, r=pinRadius);
cmds.select(pin[0]);
cmds.rotate(-90,90,0);
cmds.select(pin[0],hull[0]);
cmds.align(x='min',alignToLead=True);
cmds.select(pin[0]);
cmds.move(-pinHeight+pinHeight/4.0-0.25,0,0,relative=True);
wireHoleWidth = (((outsideDiameter-insideDiameter)/2.0)-wireChannelThickness)/2.0*1.5;
wireHole = cmds.polyCube(w=wireHoleWidth, h=wireChannelDepth+pinRadius/2.5,d=wireChannelThickness);
cmds.select(wireHole[0],hull[0]);
cmds.align(x='min',alignToLead=True);
cmds.align(y='max',alignToLead=True);
cmds.select(wireHole[0]);
cmds.move(-wireHoleWidth/4.0,0,0,relative=True);
cmds.select(hull[0],pin[0]);
hull = cmds.polyBoolOp(op=1);
#create hole between wireguide and peg
cmds.select(wireGuide[0]);
cmds.move(0,0.1,0,relative=True);
cmds.select(hull[0],wireHole[0]);
hull = cmds.polyBoolOp(op=2);
cmds.select(hull[0],wireGuide[0]);
hull = cmds.polyBoolOp(op=2);
cmds.select(hull[0],flatSection3[0]);#had to do this separately as it was removing some extra walls
hull = cmds.polyBoolOp(op=2);
# borderBlockWidth = outsideDiameter-insideDiameter+pinHeight;
# borderBlock = cmds.polyCube(w=borderBlockWidth, h=height*2,d=pinRadius*4.0);
# cmds.select(borderBlock[0],hull[0]);
# cmds.align(x='min',alignToLead=True);
# cmds.select(hull[0],borderBlock[0]);
# hull = cmds.polyBoolOp(op=3);#order matters
# block = cmds.polyCube(w=bandWidth/2.0, h=height + bandBlockOffset,d=bandWidth);
# testBlock = cmds.polyCube(w=bandWidth/2.0, h=height + bandBlockOffset,d=bandWidth);
# wireHole = cmds.polyCube(w=bandWidth, h=pinRadius*1.5,d=wireChannelThickness);
# cmds.select(wireHole[0],testBlock[0]);
# cmds.align(y='max',alignToLead=True);
# cmds.select(testBlock[0],wireHole[0]);
# testBlock = cmds.polyBoolOp(op=2);
# cmds.move(0,pinRadius,0)
createPin.pinHole( h=pinHeight, r=pinRadius);
pinHole = cmds.ls(sl=True)#work around
cmds.rotate(-90,90,0)
cmds.select(pinHole[0],block[0]);
cmds.align(x='max',alignToLead=True);
cmds.select(pinHole[0]);
cmds.move(0.01,0,0,relative=True);
#
#
cmds.select(block[0],pinHole[0]);
block = cmds.polyBoolOp(op=2);
cmds.select(band[0],block[0]);
band = cmds.polyBoolOp(op=1);
cmds.rotate(-90,0,0)
wireHole = cmds.polyCube(w=bandWidth/1.0, h=(height + bandBlockOffset+pinHeight*1.5)/2.0,d=wireChannelThickness);
cmds.select(wireHole[0],band[0]);
cmds.align(x='max',alignToLead=True);
cmds.align(y='max',alignToLead=True);
cmds.select(wireHole[0]);
cmds.move(bandWidth/2.0,0,0,relative=True);
cmds.select(band[0],wireHole[0]);
band = cmds.polyBoolOp(op=2);
wireHole2 = cmds.polyCube(w=bandWidth/8.0, h=(height + bandBlockOffset+pinHeight*1.5)/2.0,d=(height + bandBlockOffset+pinHeight/2.0)/2.0);
cmds.select(wireHole2[0],band[0]);
cmds.align(x='max',alignToLead=True);
cmds.align(y='max',alignToLead=True);
cmds.select(wireHole2[0]);
cmds.move(-bandWidth/2.0+bandWidth/8.0,0,-0.5*(height + bandBlockOffset+pinHeight/2.0)/2.0 + bandWallThickness,relative=True)
cmds.select(band[0],wireHole2[0]);
band = cmds.polyBoolOp(op=2);
cmds.select(band[0]);
cmds.rotate(0,180,0);
cmds.move(-insideDiameter/1.3,0,0,relative=True);
cmds.select(band[0],hull[0]);
cmds.align(y='min',alignToLead=True);
cmds.select(hull[0]);
cmds.Delete();
# cmds.group(band[0],hull[0]);
cmds.select(band[0]);
cmds.rotate('90deg',0,0);
| Python |
import maya.cmds as cmds;
cmds.SelectAll();
cmds.Delete();
outerThickness = 7.5;
outerLength = 11;
innerThickness = 2.88;
stickLength = 131;
screwDiameter = 1.65;
wireThickness = 3.15;
wireHolderWidth = 20.0 + outerThickness;
wireHolderThickness = 6;
wirePlacementOffset = 1.0;#position below stick where wire hole will be
wireOffset = 10;#distance between wires
#box = cmds.polyPlane( sx=1, sy=1, w=innerThickness, h=innerThickness);
oneSide = cmds.polyCube(n='oneSide',w=outerLength, h=outerThickness,d=outerThickness);
stick = cmds.curve( p=[(0, 0, 0), (10, 0, 0),(61, 0,-5.5), (85, 3,-11), (120, 12,-32)] );
cmds.move(outerLength/2.0);
cmds.polyExtrudeFacet( 'oneSide.f[4]', kft=False, ltz=2, inputCurve=stick,divisions=100,taper=0.3)
removeBox = cmds.polyCube(w=outerLength, h=outerThickness,d=outerThickness);
cmds.move(0,0,-outerThickness/2.0);
cmds.select(oneSide[0],removeBox[0]);
object = cmds.polyBoolOp(op=2);
innerBox = cmds.polyCube(w=outerLength, h=innerThickness,d=outerThickness);
cmds.select(object[0],innerBox[0]);
object = cmds.polyBoolOp(op=1);
screwHole = cmds.polyCylinder( sx=20, sy=15, sz=5, h=outerThickness,r=screwDiameter/2.0);
cmds.move(outerThickness/4.0,0,-outerThickness/4.0);
cmds.select(object[0],screwHole[0]);
object = cmds.polyBoolOp(op=2);
cmds.select(object);
cmds.rotate(90,0,0,r=True);
removeBox2 = cmds.polyCube(w=outerLength, h=outerThickness,d=outerThickness);
cmds.move(-outerLength/2.0,outerThickness/2.0,0);
cmds.select(object[0],removeBox2[0]);
object = cmds.polyBoolOp(op=2);
wireHolder = cmds.polyCube(n='oneSide',w=outerLength, h=wireHolderThickness,d=wireHolderWidth);
cmds.move(0,-wireHolderThickness/2.0,wireHolderWidth/2.0-outerThickness/2.0)
cmds.select(object[0],wireHolder[0]);
object = cmds.polyBoolOp(op=1);
wire1 = cmds.polyCylinder( sx=20, sy=15, sz=5, h=outerThickness*2.0,r=wireThickness/2.0);
wire2 = cmds.polyCylinder( sx=20, sy=15, sz=5, h=outerThickness*2.0,r=wireThickness/2.0);
cmds.move(0,-outerThickness/4.0,- outerThickness/2.0-wireThickness/2.0)
cmds.select(wire1);
cmds.rotate(0,0,90,r=True);
cmds.move(0,-wireHolderThickness/2.0,outerThickness/2.0+wireThickness/2.0 + wirePlacementOffset)
cmds.select(object[0],wire1[0]);
object = cmds.polyBoolOp(op=2);
cmds.select(wire2);
cmds.rotate(0,0,90,r=True);
cmds.move(0,-wireHolderThickness/2.0,outerThickness/2.0+wireThickness/2.0 + wirePlacementOffset + wireOffset)
cmds.select(object[0],wire2[0]);
object = cmds.polyBoolOp(op=2);
#have to rotate only object, because if you rotate all, you rotate the curve and mess things up.
cmds.rotate(90,0,0,r=True);
| Python |
import maya.cmds as cmds
import pymel.core as pm;
cmds.SelectAll();
cmds.Delete();
pulleyRadius = 25;
ropeDiameter = 3*1.15;
lipHeight = 1;
lipWall =0.1;
screwDiameter = 7.9375*1.10;#5/16 in bolt to mm
boltMountDistance = pulleyRadius / 2;#purposefully using integer division here to get even nubmer
wallthickness = 5;
washerThickness = 1.5875;#5/16 in bolt washer = 1/16 in thickness to mm
pulleyheight = ropeDiameter + 2*lipHeight;
pulleyClearance = 10;#distance between pulley and bottom of cnclosure
enclosureDepth = 2*pulleyRadius + 2*ropeDiameter + 2;
enclosureHeight = pulleyRadius + 1.25*screwDiameter + pulleyClearance;
enclosureWidth = 2*pulleyheight+2*wallthickness + 4*washerThickness + 0.1;#0.1 fudge factor
def createPulley( x, z):
pulley = cmds.polyPipe(r=pulleyRadius,h=pulleyheight*2,t=(pulleyRadius-(screwDiameter/2.0)))#polypipe bug, where height is created at half height. :(
sqGuide = cmds.polyPipe(r=pulleyRadius,h=(pulleyheight*2 - lipHeight*2),t=(lipWall))#polypipe bug, where height is created at half height. :(
cmds.select(pulley[0],sqGuide[0]);
pulley = cmds.polyBoolOp(op=2);
guide = cmds.polyTorus( sx=20, sy=20, r=(pulleyRadius-lipWall), sr=(ropeDiameter/2.0 +lipHeight/2.0) )
cmds.select(pulley[0],guide[0]);
pulley = cmds.polyBoolOp(op=2);
#cmds.rotate(0,0,'90deg');
cmds.move(x,0,z);
return pulley;
def createRope(x , z):
rope = cmds.polyCylinder( sx=20, sy=15, sz=5, h=4*pulleyRadius,r=ropeDiameter);#purposely making r = diameter to double hole size
cmds.move(x,0,z);
return rope;
def createBoltHole(z):
bolt = cmds.polyCylinder( sx=20, sy=15, sz=5, h=4*pulleyRadius,r=screwDiameter/2.0);#purposely making r = diameter to double hole size
cmds.move(0,0,z);
return bolt;
def subtractObject(object1,object2):
cmds.select(object1[0],object2[0]);
returnObject = cmds.polyBoolOp(op=2);
return returnObject;
bolt = cmds.polyCylinder( sx=10, sy=15, sz=5, h=4*pulleyRadius,r=screwDiameter/2.0);
cmds.rotate(0,0,'90deg');
enclosure = cmds.polyCube(w=enclosureWidth, h=enclosureHeight,sy=5,d=enclosureDepth);
inside = cmds.polyCube(w=enclosureWidth - 2*wallthickness,sy=5, h=enclosureHeight,d=enclosureDepth);
cmds.select(inside[0],r=True);
cmds.move(0,wallthickness, 0);
cmds.select(enclosure[0],inside[0],r=True);
enclosure = cmds.polyBoolOp(op=2);
#cmds.nonLinear( type='flare', endFlareZ = 0.15 );
#now place enclosure with bottom at 0
cmds.move(0,enclosureHeight/2.0,0)
#now move enclosure down to appropriate height, so that height of enclosure doesn't affect bottom position of enclosure
cmds.move(0,-pulleyRadius - 0.5*wallthickness - pulleyClearance,0,relative=True);
cmds.select(enclosure[0]);
cmds.select(enclosure[0],bolt[0],r=True);
enclosure = cmds.polyBoolOp(op=2);
pulley1 = createPulley(-0.5*pulleyheight - washerThickness,0);
pulley2 = createPulley(0.5*pulleyheight + washerThickness,0);
rope1 = createRope(-0.5*pulleyheight - washerThickness,pulleyRadius);
rope2 = createRope(0.5*pulleyheight + washerThickness,pulleyRadius);
bolt1 = createBoltHole(boltMountDistance);
bolt2 = createBoltHole(-boltMountDistance);
enclosure = subtractObject(enclosure,bolt1);
enclosure = subtractObject(enclosure,bolt2);
enclosure = subtractObject(enclosure,rope1);
enclosure = subtractObject(enclosure,rope2);
#cmds.rotate(0,0,'90deg');
#cmds.move(0,enclosureWidth/2.0,0);
cmds.select(pulley1[0]);
cmds.move(-1.35*pulleyRadius,pulleyheight/2.0,1.015*pulleyRadius);
cmds.select(pulley2[0]);
cmds.move(-1.35*pulleyRadius,pulleyheight/2.0,-1.015*pulleyRadius);
cmds.select(enclosure[0],pulley1[0]);
cmds.align(y='Min',alignToLead=True);
cmds.align(x='Stack',alignToLead=True);
cmds.select(enclosure[0]);
cmds.move(1,0,0,r=True);
#cmds.rotate('90deg',0,0);
group = cmds.group(enclosure[0],pulley1[0],pulley2[0],n='scene');
cmds.rotate('90deg',0,0);
# cmds.polySeparate(group);
cmds.ungroup(group);
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.