Search Results

Search found 1706 results on 69 pages for 'offset'.

Page 13/69 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • PNGException "crc corruption" when attempting to create ImageIcon objects from ZIP archive

    - by Nathan Strong
    I've got a ZIP file containing a number of PNG images that I am trying to load into my Java application as ImageIcon resources directly from the archive. Here's my code: import java.io.*; import java.util.Enumeration; import java.util.zip.*; import javax.swing.ImageIcon; public class Test { public static void main( String[] args ) { if( args.length == 0 ) { System.out.println("usage: java Test.java file.zip"); return; } File archive = new File( args[0] ); if( !archive.exists() || !archive.canRead() ) { System.err.printf("Unable to find/access %s.\n", archive); return; } try { ZipFile zip = new ZipFile(archive); Enumeration <? extends ZipEntry>e = zip.entries(); while( e.hasMoreElements() ) { ZipEntry entry = (ZipEntry) e.nextElement(); int size = (int) entry.getSize(); int count = (size % 1024 == 0) ? size / 1024 : (size / 1024)+1; int offset = 0; int nread, toRead; byte[] buffer = new byte[size]; for( int i = 0; i < count; i++ ) { offset = 1024*i; toRead = (size-offset > 1024) ? 1024 : size-offset; nread = zip.getInputStream(entry).read(buffer, offset, toRead); } ImageIcon icon = new ImageIcon(buffer); // boom -- why? } zip.close(); } catch( IOException ex ) { System.err.println(ex.getMessage()); } } } The sizes reported by entry.getSize() match the uncompressed size of the PNG files, and I am able to read the data out of the archive without any exceptions, but the creation of the ImageIcon blows up. The stacktrace: sun.awt.image.PNGImageDecoder$PNGException: crc corruption at sun.awt.image.PNGImageDecoder.getChunk(PNGImageDecoder.java:699) at sun.awt.image.PNGImageDecoder.getData(PNGImageDecoder.java:707) at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:234) at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246) at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172) at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136) sun.awt.image.PNGImageDecoder$PNGException: crc corruption at sun.awt.image.PNGImageDecoder.getChunk(PNGImageDecoder.java:699) at sun.awt.image.PNGImageDecoder.getData(PNGImageDecoder.java:707) at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:234) at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246) at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172) at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136) Can anyone shed some light on it? Google hasn't turned up any useful information.

    Read the article

  • Overloading framework methods in objective-c, or retaining local changes with framework updates.

    - by Jeff B
    I am using cocos2d to build an iPhone game. It's mostly done, but along the way I came across some things that I would like to handle better. I am fairly new to Objective C, and honestly I do more Perl scripting in my day-to-day job than anything, so my C skills are a little rusty. One of them is the fact that I have modified cocos2d files for some specific cases in my game. However, when I update to a new version, I have to manually pull my changes forward. So, the question is, what is the best way to deal with this? Some options I have thought of: Overload/redefine the cocos2d classes. I was under the impression that I cannot overload existing class functions, so I don't think this will work. Create patches that I re-apply after library updates. I don't think this will work as the new files won't necessarily be the same as the old ones, and if they were, I could just copy the whole file forward. Turn in my changes to Cocos2d. Not an option as my changes are very specific to my application. Am I missing something obvious? UPDATE: I will explain what I am doing to be more clear. Cocos2d has a CCNode object, which can contain children, etc. I added a shadow, which is very similar to a child, but handled a little differently. The shadow has an offset from the parent, and translates with it's parent, rotates around it's own center when the parent rotates, etc. The shadow is not included as a true child, however, so given the correct z-index, the shadows can render under ALL other objects, but still move with the parent. To do this I added addShadow functions to CCNode, and modified the setPosition and setRotate functions to move the shadowSprite: CCNode.m: -(id) init { if ((self=[super init]) ) { ... shadowSprite_ = nil; ... } } ... -(BOOL) addShadow: (CCNode*) child offset: (CGPoint) offset { shadowSprite_ = child; shadowSprite_.position = CGPointMake(position_.x+offset.x, position_.y+offset.y); return YES; } ... -(void) setRotation: (float)newRotation { rotation_ = newRotation; isTransformDirty_ = isInverseDirty_ = YES; if(shadowSprite_) { [shadowSprite_ setRotation: newRotation]; } } There is more, of course, including the prototypes in the .h file, but that is the basics. I don't think I need shadowSprite to be a property, because I don't need to access it after it has been added.

    Read the article

  • Rendering of graphics different depending on position

    - by jedierikb
    When drawing parallel vertical lines with a fixed distance between them (1.75 pixels) with a non-integer x-value-offset to both lines, the lines are drawn differently based on the offset. In the picture below are two pairs of very close together vertical lines. As you can see, they look very different. This is frustrating, especially when animating the sprite. Any ideas how ensure that sprites-with-non-integer-positions' graphics will visually display the same? package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; public class tmpa extends Sprite { private var _sp1:Sprite; private var _sp2:Sprite; private var _num:Number; public function tmpa( ):void { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; _sp1 = new Sprite( ); drawButt( _sp1, 0 ); _sp1.x = 100; _sp1.y = 100; _num = 0; _sp2 = new Sprite( ); drawButt( _sp2, _num ); _sp2.x = 100; _sp2.y = 200; addChild( _sp1 ); addChild( _sp2 ); addEventListener( Event.ENTER_FRAME, efCb, false, 0, true ); } private function efCb( evt:Event ):void { _num += .1; if (_num > 400) { _num = 0; } drawButt( _sp2, _num ); } private function drawButt( sp:Sprite, offset:Number ):void { var px1:Number = 1 + offset; var px2:Number = 2.75 + offset; sp.graphics.clear( ); sp.graphics.lineStyle( 1, 0, 1, true ); sp.graphics.moveTo( px1, 1 ); sp.graphics.lineTo( px1, 100 ); sp.graphics.lineStyle( 1, 0, 1, true ); sp.graphics.moveTo( px2, 1 ); sp.graphics.lineTo( px2, 100 ); } } } edit from original post which thought the problem was tied to the x-position of the sprite.

    Read the article

  • Not seeing Sync Block in Object Layout

    - by bob-bedell
    It's my understanding the all .NET object instances begin with an 8 byte 'object header': a synch block (4 byte pointer into a SynchTableEntry table), and a type handle (4 byte pointer into the types method table). I'm not seeing this in VS 2010 RC's (CLR 4.0) debugger memory windows. Here's a simple class that will generate a 16 byte instance, less the object header. class Program { short myInt = 2; // 4 bytes long myLong = 3; // 8 bytes string myString = "aString"; // 4 byte object reference // 16 byte instance static void Main(string[] args) { new Program(); return; } } An SOS object dump tells me that the total object size is 24 bytes. That makes sense. My 16 byte instance plus an 8 byte object header. !DumpObj 0205b660 Name: Offset_Test.Program MethodTable: 000d383c EEClass: 000d13f8 Size: 24(0x18) bytes File: C:\Users\Bob\Desktop\Offset_Test\Offset_Test\bin\Debug\Offset_Test.exe Fields: MT Field Offset Type VT Attr Value Name 632020fc 4000001 10 System.Int16 1 instance 2 myInt 632050d8 4000002 4 System.Int64 1 instance 3 myLong 631fd2b8 4000003 c System.String 0 instance 0205b678 myString Here's the raw memory: 0x0205B660 000d383c 00000003 00000000 0205b678 00000002 ... And here are some annotations: offset 0 000d383c ;TypeHandle (pointer to MethodTable), 4 bytes offset 4 00000003 00000000 ;myLong, 8 bytes offset 12 0205b678 ;myString, 4 byte reference to address of "myString" on GC Heap offset 16 00000002 ;myInt, 4 bytes My object begins a address 0x0205B660. But I can only account for 20 bytes of it, the type handle and the instance fields. There is no sign of a synch block pointer. The object size is reported as 24 bytes, but the debugger is showing that it only occupies 20 bytes of memory. I'm reading Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects, and expected the first 4 bytes of my object to be a zeroed synch block pointer, as shown in Figure 8 of that article. Granted, this is an article about CLR 1.1. I'm just wondering if the difference between what I'm seeing and what this early article reports is a change in either the debugger's display of object layout, or in the way the CLR lays out objects in versions later than 1.1. Anyway, can anyone account for my 4 missing bytes?

    Read the article

  • Switching my collision detection to array lists caused it to stop working

    - by Charlton Santana
    I have made a collision detection system which worked when I did not use array list and block generation. It is weird why it's not working but here's the code, and if anyone could help I would be very grateful :) The first code if the block generation. private static final List<Block> BLOCKS = new ArrayList<Block>(); Random rnd = new Random(System.currentTimeMillis()); int randomx = 400; int randomy = 400; int blocknum = 100; String Title = "blocktitle" + blocknum; private Block block; public void generateBlocks(){ if(blocknum > 0){ int offset = rnd.nextInt(250) + 100; //500 is the maximum offset, this is a constant randomx += offset;//ofset will be between 100 and 400 int randomyoff = rnd.nextInt(80); //500 is the maximum offset, this is a constant randomy = platformheighttwo - 6 - randomyoff;//ofset will be between 100 and 400 block = new Block(BitmapFactory.decodeResource(getResources(), R.drawable.block2), randomx, randomy); BLOCKS.add(block); blocknum -= 1; } The second is where the collision detection takes place note: the block.draw(canvas); works perfectly. It's the blocks that don't work. for(Block block : BLOCKS) { block.draw(canvas); if (sprite.bottomrx < block.bottomrx && sprite.bottomrx > block.bottomlx && sprite.bottomry < block.bottommy && sprite.bottomry > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } // bottom left touching block? if (sprite.bottomlx < block.bottomrx && sprite.bottomlx > block.bottomlx && sprite.bottomly < block.bottommy && sprite.bottomly > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } // top right touching block? if (sprite.toprx < block.bottomrx && sprite.toprx > block.bottomlx && sprite.topry < block.bottommy && sprite.topry > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } //top left touching block? if (sprite.toprx < block.bottomrx && sprite.toprx > block.bottomlx && sprite.topry < block.bottommy && sprite.topry > block.topry ){ Log.d(TAG, "Collided!!!!!!!!!!!!1"); } } The values eg bottomrx are in the block.java file..

    Read the article

  • Direct3D - Zooming into Mouse Position

    - by roohan
    I'm trying to implement my camera class for a simulation. But I cant figure out how to zoom into my world based on the mouse position. I mean the object under the mouse cursor should remain at the same screen position. My zooming looks like this: VOID ZoomIn(D3DXMATRIX& WorldMatrix, FLOAT const& MouseX, FLOAT const& MouseY) { this->Position.z = this->Position.z * 0.9f; D3DXMatrixLookAtLH(&this->ViewMatrix, &this->Position, &this->Target, &this->UpDirection); } I passed the world matrix to the function because I had the idea to move my drawing origin according to the mouse position. But I cant find out how to calculate the offset in to move my drawing origin. Anyone got an idea how to calculate this? Thanks in advance. SOLVED Ok I solved my problem. Here is the code if anyone is interested: VOID CAMERA2D::ZoomIn(FLOAT const& MouseX, FLOAT const& MouseY) { // Get the setting of the current view port. D3DVIEWPORT9 ViewPort; this->Direct3DDevice->GetViewport(&ViewPort); // Convert the screen coordinates of the mouse to world space coordinates. D3DXVECTOR3 VectorOne; D3DXVECTOR3 VectorTwo; D3DXVec3Unproject(&VectorOne, &D3DXVECTOR3(MouseX, MouseY, 0.0f), &ViewPort, &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix); D3DXVec3Unproject(&VectorTwo, &D3DXVECTOR3(MouseX, MouseY, 1.0f), &ViewPort, &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix); // Calculate the resulting vector components. float WorldZ = 0.0f; float WorldX = ((WorldZ - VectorOne.z) * (VectorTwo.x - VectorOne.x)) / (VectorTwo.z - VectorOne.z) + VectorOne.x; float WorldY = ((WorldZ - VectorOne.z) * (VectorTwo.y - VectorOne.y)) / (VectorTwo.z - VectorOne.z) + VectorOne.y; // Move the camera into the screen. this->Position.z = this->Position.z * 0.9f; D3DXMatrixLookAtLH(&this->ViewMatrix, &this->Position, &this->Target, &this->UpDirection); // Calculate the world space vector again based on the new view matrix, D3DXVec3Unproject(&VectorOne, &D3DXVECTOR3(MouseX, MouseY, 0.0f), &ViewPort, &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix); D3DXVec3Unproject(&VectorTwo, &D3DXVECTOR3(MouseX, MouseY, 1.0f), &ViewPort, &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix); // Calculate the resulting vector components. float WorldZ2 = 0.0f; float WorldX2 = ((WorldZ2 - VectorOne.z) * (VectorTwo.x - VectorOne.x)) / (VectorTwo.z - VectorOne.z) + VectorOne.x; float WorldY2 = ((WorldZ2 - VectorOne.z) * (VectorTwo.y - VectorOne.y)) / (VectorTwo.z - VectorOne.z) + VectorOne.y; // Create a temporary translation matrix for calculating the origin offset. D3DXMATRIX TranslationMatrix; D3DXMatrixIdentity(&TranslationMatrix); // Calculate the origin offset. D3DXMatrixTranslation(&TranslationMatrix, WorldX2 - WorldX, WorldY2 - WorldY, 0.0f); // At the offset to the cameras world matrix. this->WorldMatrix = this->WorldMatrix * TranslationMatrix; } Maybe someone has even a better solution than mine.

    Read the article

  • Where can these be posted besides the Python Cookbook?

    - by Noctis Skytower
    Whitespace Assembler #! /usr/bin/env python """Assembler.py Compiles a program from "Assembly" folder into "Program" folder. Can be executed directly by double-click or on the command line. Give name of *.WSA file without extension (example: stack_calc).""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 3 $' ################################################################################ import string from Interpreter import INS, MNEMONIC ################################################################################ def parse(code): program = [] process_virtual(program, code) process_control(program) return tuple(program) def process_virtual(program, code): for line, text in enumerate(code.split('\n')): if not text or text[0] == '#': continue if text.startswith('part '): parse_part(program, line, text[5:]) elif text.startswith(' '): parse_code(program, line, text[5:]) else: syntax_error(line) def syntax_error(line): raise SyntaxError('Line ' + str(line + 1)) ################################################################################ def process_control(program): parts = get_parts(program) names = dict(pair for pair in zip(parts, generate_index())) correct_control(program, names) def get_parts(program): parts = [] for ins in program: if isinstance(ins, tuple): ins, arg = ins if ins == INS.PART: if arg in parts: raise NameError('Part definition was found twice: ' + arg) parts.append(arg) return parts def generate_index(): index = 1 while True: yield index index *= -1 if index > 0: index += 1 def correct_control(program, names): for index, ins in enumerate(program): if isinstance(ins, tuple): ins, arg = ins if ins in HAS_LABEL: if arg not in names: raise NameError('Part definition was never found: ' + arg) program[index] = (ins, names[arg]) ################################################################################ def parse_part(program, line, text): if not valid_label(text): syntax_error(line) program.append((INS.PART, text)) def valid_label(text): if not between_quotes(text): return False label = text[1:-1] if not valid_name(label): return False return True def between_quotes(text): if len(text) < 3: return False if text.count('"') != 2: return False if text[0] != '"' or text[-1] != '"': return False return True def valid_name(label): valid_characters = string.ascii_letters + string.digits + '_' valid_set = frozenset(valid_characters) label_set = frozenset(label) if len(label_set - valid_set) != 0: return False return True ################################################################################ from Interpreter import HAS_LABEL, Program NO_ARGS = Program.NO_ARGS HAS_ARG = Program.HAS_ARG TWO_WAY = tuple(set(NO_ARGS) & set(HAS_ARG)) ################################################################################ def parse_code(program, line, text): for ins, word in enumerate(MNEMONIC): if text.startswith(word): check_code(program, line, text[len(word):], ins) break else: syntax_error(line) def check_code(program, line, text, ins): if ins in TWO_WAY: if text: number = parse_number(line, text) program.append((ins, number)) else: program.append(ins) elif ins in HAS_LABEL: text = parse_label(line, text) program.append((ins, text)) elif ins in HAS_ARG: number = parse_number(line, text) program.append((ins, number)) elif ins in NO_ARGS: if text: syntax_error(line) program.append(ins) else: syntax_error(line) def parse_label(line, text): if not text or text[0] != ' ': syntax_error(line) text = text[1:] if not valid_label(text): syntax_error(line) return text ################################################################################ def parse_number(line, text): if not valid_number(text): syntax_error(line) return int(text) def valid_number(text): if len(text) < 2: return False if text[0] != ' ': return False text = text[1:] if '+' in text and '-' in text: return False if '+' in text: if text.count('+') != 1: return False if text[0] != '+': return False text = text[1:] if not text: return False if '-' in text: if text.count('-') != 1: return False if text[0] != '-': return False text = text[1:] if not text: return False valid_set = frozenset(string.digits) value_set = frozenset(text) if len(value_set - valid_set) != 0: return False return True ################################################################################ ################################################################################ from Interpreter import partition_number VMC_2_TRI = { (INS.PUSH, True): (0, 0), (INS.COPY, False): (0, 2, 0), (INS.COPY, True): (0, 1, 0), (INS.SWAP, False): (0, 2, 1), (INS.AWAY, False): (0, 2, 2), (INS.AWAY, True): (0, 1, 2), (INS.ADD, False): (1, 0, 0, 0), (INS.SUB, False): (1, 0, 0, 1), (INS.MUL, False): (1, 0, 0, 2), (INS.DIV, False): (1, 0, 1, 0), (INS.MOD, False): (1, 0, 1, 1), (INS.SET, False): (1, 1, 0), (INS.GET, False): (1, 1, 1), (INS.PART, True): (2, 0, 0), (INS.CALL, True): (2, 0, 1), (INS.GOTO, True): (2, 0, 2), (INS.ZERO, True): (2, 1, 0), (INS.LESS, True): (2, 1, 1), (INS.BACK, False): (2, 1, 2), (INS.EXIT, False): (2, 2, 2), (INS.OCHR, False): (1, 2, 0, 0), (INS.OINT, False): (1, 2, 0, 1), (INS.ICHR, False): (1, 2, 1, 0), (INS.IINT, False): (1, 2, 1, 1) } ################################################################################ def to_trinary(program): trinary_code = [] for ins in program: if isinstance(ins, tuple): ins, arg = ins trinary_code.extend(VMC_2_TRI[(ins, True)]) trinary_code.extend(from_number(arg)) else: trinary_code.extend(VMC_2_TRI[(ins, False)]) return tuple(trinary_code) def from_number(arg): code = [int(arg < 0)] if arg: for bit in reversed(list(partition_number(abs(arg), 2))): code.append(bit) return code + [2] return code + [0, 2] to_ws = lambda trinary: ''.join(' \t\n'[index] for index in trinary) def compile_wsa(source): program = parse(source) trinary = to_trinary(program) ws_code = to_ws(trinary) return ws_code ################################################################################ ################################################################################ import os import sys import time import traceback def main(): name, source, command_line, error = get_source() if not error: start = time.clock() try: ws_code = compile_wsa(source) except: print('ERROR: File could not be compiled.\n') traceback.print_exc() error = True else: path = os.path.join('Programs', name + '.ws') try: open(path, 'w').write(ws_code) except IOError as err: print(err) error = True else: div, mod = divmod((time.clock() - start) * 1000, 1) args = int(div), '{:.3}'.format(mod)[1:] print('DONE: Comipled in {}{} ms'.format(*args)) handle_close(error, command_line) def get_source(): if len(sys.argv) > 1: command_line = True name = sys.argv[1] else: command_line = False try: name = input('Source File: ') except: return None, None, False, True print() path = os.path.join('Assembly', name + '.wsa') try: return name, open(path).read(), command_line, False except IOError as err: print(err) return None, None, command_line, True def handle_close(error, command_line): if error: usage = 'Usage: {} <assembly>'.format(os.path.basename(sys.argv[0])) print('\n{}\n{}'.format('-' * len(usage), usage)) if not command_line: time.sleep(10) ################################################################################ if __name__ == '__main__': main() Whitespace Helpers #! /usr/bin/env python """Helpers.py Includes a function to encode Python strings into my WSA format. Has a "PRINT_LINE" function that can be copied to a WSA program. Contains a "PRINT" function and documentation as an explanation.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 1 $' ################################################################################ def encode_string(string, addr): print(' push', addr) print(' push', len(string)) print(' set') addr += 1 for offset, character in enumerate(string): print(' push', addr + offset) print(' push', ord(character)) print(' set') ################################################################################ # Prints a string with newline. # push addr # call "PRINT_LINE" """ part "PRINT_LINE" call "PRINT" push 10 ochr back """ ################################################################################ # def print(array): # if len(array) <= 0: # return # offset = 1 # while len(array) - offset >= 0: # ptr = array.ptr + offset # putch(array[ptr]) # offset += 1 """ part "PRINT" # Line 1-2 copy get less "__PRINT_RET_1" copy get zero "__PRINT_RET_1" # Line 3 push 1 # Line 4 part "__PRINT_LOOP" copy copy 2 get swap sub less "__PRINT_RET_2" # Line 5 copy 1 copy 1 add # Line 6 get ochr # Line 7 push 1 add goto "__PRINT_LOOP" part "__PRINT_RET_2" away part "__PRINT_RET_1" away back """ Whitespace Interpreter #! /usr/bin/env python """Interpreter.py Runs programs in "Programs" and creates *.WSO files when needed. Can be executed directly by double-click or on the command line. If run on command line, add "ASM" flag to dump program assembly.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 4 $' ################################################################################ def test_file(path): disassemble(parse(trinary(load(path))), True) ################################################################################ load = lambda ws: ''.join(c for r in open(ws) for c in r if c in ' \t\n') trinary = lambda ws: tuple(' \t\n'.index(c) for c in ws) ################################################################################ def enum(names): names = names.replace(',', ' ').split() space = dict((reversed(pair) for pair in enumerate(names)), __slots__=()) return type('enum', (object,), space)() INS = enum('''\ PUSH, COPY, SWAP, AWAY, \ ADD, SUB, MUL, DIV, MOD, \ SET, GET, \ PART, CALL, GOTO, ZERO, LESS, BACK, EXIT, \ OCHR, OINT, ICHR, IINT''') ################################################################################ def parse(code): ins = iter(code).__next__ program = [] while True: try: imp = ins() except StopIteration: return tuple(program) if imp == 0: # [Space] parse_stack(ins, program) elif imp == 1: # [Tab] imp = ins() if imp == 0: # [Tab][Space] parse_math(ins, program) elif imp == 1: # [Tab][Tab] parse_heap(ins, program) else: # [Tab][Line] parse_io(ins, program) else: # [Line] parse_flow(ins, program) def parse_number(ins): sign = ins() if sign == 2: raise StopIteration() buffer = '' code = ins() if code == 2: raise StopIteration() while code != 2: buffer += str(code) code = ins() if sign == 1: return int(buffer, 2) * -1 return int(buffer, 2) ################################################################################ def parse_stack(ins, program): code = ins() if code == 0: # [Space] number = parse_number(ins) program.append((INS.PUSH, number)) elif code == 1: # [Tab] code = ins() number = parse_number(ins) if code == 0: # [Tab][Space] program.append((INS.COPY, number)) elif code == 1: # [Tab][Tab] raise StopIteration() else: # [Tab][Line] program.append((INS.AWAY, number)) else: # [Line] code = ins() if code == 0: # [Line][Space] program.append(INS.COPY) elif code == 1: # [Line][Tab] program.append(INS.SWAP) else: # [Line][Line] program.append(INS.AWAY) def parse_math(ins, program): code = ins() if code == 0: # [Space] code = ins() if code == 0: # [Space][Space] program.append(INS.ADD) elif code == 1: # [Space][Tab] program.append(INS.SUB) else: # [Space][Line] program.append(INS.MUL) elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] program.append(INS.DIV) elif code == 1: # [Tab][Tab] program.append(INS.MOD) else: # [Tab][Line] raise StopIteration() else: # [Line] raise StopIteration() def parse_heap(ins, program): code = ins() if code == 0: # [Space] program.append(INS.SET) elif code == 1: # [Tab] program.append(INS.GET) else: # [Line] raise StopIteration() def parse_io(ins, program): code = ins() if code == 0: # [Space] code = ins() if code == 0: # [Space][Space] program.append(INS.OCHR) elif code == 1: # [Space][Tab] program.append(INS.OINT) else: # [Space][Line] raise StopIteration() elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] program.append(INS.ICHR) elif code == 1: # [Tab][Tab] program.append(INS.IINT) else: # [Tab][Line] raise StopIteration() else: # [Line] raise StopIteration() def parse_flow(ins, program): code = ins() if code == 0: # [Space] code = ins() label = parse_number(ins) if code == 0: # [Space][Space] program.append((INS.PART, label)) elif code == 1: # [Space][Tab] program.append((INS.CALL, label)) else: # [Space][Line] program.append((INS.GOTO, label)) elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] label = parse_number(ins) program.append((INS.ZERO, label)) elif code == 1: # [Tab][Tab] label = parse_number(ins) program.append((INS.LESS, label)) else: # [Tab][Line] program.append(INS.BACK) else: # [Line] code = ins() if code == 2: # [Line][Line] program.append(INS.EXIT) else: # [Line][Space] or [Line][Tab] raise StopIteration() ################################################################################ MNEMONIC = '\ push copy swap away add sub mul div mod set get part \ call goto zero less back exit ochr oint ichr iint'.split() HAS_ARG = [getattr(INS, name) for name in 'PUSH COPY AWAY PART CALL GOTO ZERO LESS'.split()] HAS_LABEL = [getattr(INS, name) for name in 'PART CALL GOTO ZERO LESS'.split()] def disassemble(program, names=False): if names: names = create_names(program) for ins in program: if isinstance(ins, tuple): ins, arg = ins assert ins in HAS_ARG has_arg = True else: assert INS.PUSH <= ins <= INS.IINT has_arg = False if ins == INS.PART: if names: print(MNEMONIC[ins], '"' + names[arg] + '"') else: print(MNEMONIC[ins], arg) elif has_arg and ins in HAS_ARG: if ins in HAS_LABEL and names: assert arg in names print(' ' + MNEMONIC[ins], '"' + names[arg] + '"') else: print(' ' + MNEMONIC[ins], arg) else: print(' ' + MNEMONIC[ins]) ################################################################################ def create_names(program): names = {} number = 1 for ins in program: if isinstance(ins, tuple) and ins[0] == INS.PART: label = ins[1] assert label not in names names[label] = number_to_name(number) number += 1 return names def number_to_name(number): name = '' for offset in reversed(list(partition_number(number, 27))): if offset: name += chr(ord('A') + offset - 1) else: name += '_' return name def partition_number(number, base): div, mod = divmod(number, base) yield mod while div: div, mod = divmod(div, base) yield mod ################################################################################ CODE = (' \t\n', ' \n ', ' \t \t\n', ' \n\t', ' \n\n', ' \t\n \t\n', '\t ', '\t \t', '\t \n', '\t \t ', '\t \t\t', '\t\t ', '\t\t\t', '\n \t\n', '\n \t \t\n', '\n \n \t\n', '\n\t \t\n', '\n\t\t \t\n', '\n\t\n', '\n\n\n', '\t\n ', '\t\n \t', '\t\n\t ', '\t\n\t\t') EXAMPLE = ''.join(CODE) ################################################################################ NOTES = '''\ STACK ===== push number copy copy number swap away away number MATH ==== add sub mul div mod HEAP ==== set get FLOW ==== part label call label goto label zero label less label back exit I/O === ochr oint ichr iint''' ################################################################################ ################################################################################ class Stack: def __init__(self): self.__data = [] # Stack Operators def push(self, number): self.__data.append(number) def copy(self, number=None): if number is None: self.__data.append(self.__data[-1]) else: size = len(self.__data) index = size - number - 1 assert 0 <= index < size self.__data.append(self.__data[index]) def swap(self): self.__data[-2], self.__data[-1] = self.__data[-1], self.__data[-2] def away(self, number=None): if number is None: self.__data.pop() else: size = len(self.__data) index = size - number - 1 assert 0 <= index < size del self.__data[index:-1] # Math Operators def add(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix + suffix) def sub(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix - suffix) def mul(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix * suffix) def div(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix // suffix) def mod(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix % suffix) # Program Operator def pop(self): return self.__data.pop() ################################################################################ class Heap: def __init__(self): self.__data = {} def set_(self, addr, item): if item: self.__data[addr] = item elif addr in self.__data: del self.__data[addr] def get_(self, addr): return self.__data.get(addr, 0) ################################################################################ import os import zlib import msvcrt import pickle import string class CleanExit(Exception): pass NOP = lambda arg: None DEBUG_WHITESPACE = False ################################################################################ class Program: NO_ARGS = INS.COPY, INS.SWAP, INS.AWAY, INS.ADD, \ INS.SUB, INS.MUL, INS.DIV, INS.MOD, \ INS.SET, INS.GET, INS.BACK, INS.EXIT, \ INS.OCHR, INS.OINT, INS.ICHR, INS.IINT HAS_ARG = INS.PUSH, INS.COPY, INS.AWAY, INS.PART, \ INS.CALL, INS.GOTO, INS.ZERO, INS.LESS def __init__(self, code): self.__data = code self.__validate() self.__build_jump() self.__check_jump() self.__setup_exec() def __setup_exec(self): self.__iptr = 0 self.__stck = stack = Stack() self.__heap = Heap() self.__cast = [] self.__meth = (stack.push, stack.copy, stack.swap, stack.away, stack.add, stack.sub, stack.mul, stack.div, stack.mod, self.__set, self.__get, NOP, self.__call, self.__goto, self.__zero, self.__less, self.__back, self.__exit, self.__ochr, self.__oint, self.__ichr, self.__iint) def step(self): ins = self.__data[self.__iptr] self.__iptr += 1 if isinstance(ins, tuple): self.__meth[ins[0]](ins[1]) else: self.__meth[ins]() def run(self): while True: ins = self.__data[self.__iptr] self.__iptr += 1 if isinstance(ins, tuple): self.__meth[ins[0]](ins[1]) else: self.__meth[ins]() def __oint(self): for digit in str(self.__stck.pop()): msvcrt.putwch(digit) def __ichr(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() while True: char = msvcrt.getwch() if char in '\x00\xE0': msvcrt.getwch() elif char in string.printable: char = char.replace('\r', '\n') msvcrt.putwch(char) break item = ord(char) # Storing Number self.__heap.set_(addr, item) def __iint(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() buff = '' char = msvcrt.getwch() while char != '\r' or not buff: if char in '\x00\xE0': msvcrt.getwch() elif char in '+-' and not buff: msvcrt.putwch(char) buff += char elif '0' <= char <= '9': msvcrt.putwch(char) buff += char elif char == '\b': if buff: buff = buff[:-1] msvcrt.putwch(char) msvcrt.putwch(' ') msvcrt.putwch(char) char = msvcrt.getwch() msvcrt.putwch(char) msvcrt.putwch('\n') item = int(buff) # Storing Number self.__heap.set_(addr, item) def __goto(self, label): self.__iptr = self.__jump[label] def __zero(self, label): if self.__stck.pop() == 0: self.__iptr = self.__jump[label] def __less(self, label): if self.__stck.pop() < 0: self.__iptr = self.__jump[label] def __exit(self): self.__setup_exec() raise CleanExit() def __set(self): item = self.__stck.pop() addr = self.__stck.po

    Read the article

  • IP address reuse on macvlan devices

    - by Alex Bubnoff
    I'm trying to create easy to use and possibly simple testing environment for some product and got some strange behaviour of macvlan's. What I'm trying to achieve: make a toolset for one-line start/stop of lxc containers(via docker) bound to external ip(I have enough of it on host machine). So, I'm doing something like this: docker run -d -name=container_name container_image pipework eth1 container_name ip/prefix_len@gateway and pipework here does this: GUEST_IFNAME=ph$NSPID$eth1 ip link add link eth1 dev $GUEST_IFNAME type macvlan mode bridge ip link set eth1 up ip link set $GUEST_IFNAME netns $NSPID ip netns exec $NSPID ip link set $GUEST_IFNAME name eth1 ip netns exec $NSPID ip addr add $IPADDR dev eth1 ip netns exec $NSPID ip route delete default ip netns exec $NSPID ip link set eth1 up ip netns exec $NSPID ip route replace default via $GATEWAY ip netns exec $NSPID arping -c 1 -A -I eth1 $IPADDR And it works for first time per IP. But for second time and later packets for containers IP isn't getting into container, while all configuration seem fine. So it looks like this: External machine ? ping 212.76.131.212 ....silence.... Host machine root@ubuntu:~# ip link show eth1 2: eth1: mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 00:15:17:c9:e1:c9 brd ff:ff:ff:ff:ff:ff root@ubuntu:~# ip addr show eth1 2: eth1: mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 00:15:17:c9:e1:c9 brd ff:ff:ff:ff:ff:ff root@ubuntu:~# tcpdump -v -i eth1 icmp tcpdump: WARNING: eth1: no IPv4 address assigned tcpdump: listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes 00:00:46.542042 IP (tos 0x0, ttl 60, id 9623, offset 0, flags [DF], proto ICMP (1), length 84) 5.134.221.98 212.76.131.212: ICMP echo request, id 6718, seq 2345, length 64 00:00:47.549969 IP (tos 0x0, ttl 60, id 9624, offset 0, flags [DF], proto ICMP (1), length 84) 5.134.221.98 212.76.131.212: ICMP echo request, id 6718, seq 2346, length 64 00:00:48.558143 IP (tos 0x0, ttl 60, id 9625, offset 0, flags [DF], proto ICMP (1), length 84) 5.134.221.98 212.76.131.212: ICMP echo request, id 6718, seq 2347, length 64 00:00:49.566319 IP (tos 0x0, ttl 60, id 9626, offset 0, flags [DF], proto ICMP (1), length 84) 5.134.221.98 212.76.131.212: ICMP echo request, id 6718, seq 2348, length 64 00:00:50.573999 IP (tos 0x0, ttl 60, id 9627, offset 0, flags [DF], proto ICMP (1), length 84) 5.134.221.98 212.76.131.212: ICMP echo request, id 6718, seq 2349, length 64 ^C 5 packets captured 5 packets received by filter 0 packets dropped by kernel 1 packet dropped by interface Host machine, netns of container root@ubuntu:~# ip netns exec 32053 ip link show eth1 48: eth1@if2: mtu 1500 qdisc noqueue state UNKNOWN link/ether b2:12:f7:cc:a1:9d brd ff:ff:ff:ff:ff:ff root@ubuntu:~# ip netns exec 32053 ip addr show eth1 48: eth1@if2: mtu 1500 qdisc noqueue state UNKNOWN link/ether b2:12:f7:cc:a1:9d brd ff:ff:ff:ff:ff:ff inet 212.76.131.212/29 scope global eth1 inet6 fe80::b012:f7ff:fecc:a19d/64 scope link valid_lft forever preferred_lft forever root@ubuntu:~# ip netns exec 32053 tcpdump -v -i eth1 icmp tcpdump: listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes ....silence.... ^C 0 packets captured 0 packets received by filter 0 packets dropped by kernel So, can anyone say, what can it be? Can this be caused by not a bug in macvlan implementation? Is there any tools I can use to debug that configuration?

    Read the article

  • How to programmatically create customcontrol and change its values in Silverlight 4

    - by user361317
    Hi! I want to create a custom tabcontrol class which has an icon before the text, and I want to be able to change the icon in the constructor of the new tabcontrol. I use implicit styles in Silverlight 4, and the custom tabcontrol should not have any xaml of its own, just the class and the implicit xaml style in my App.xaml. I cannot, however, get this to work. This is my code: <!-- Style for generic tabcontrols --> 20,0,0,0 <Style TargetType="controls:TabItem"> <Setter Property="IsTabStop" Value="False"/> <Setter Property="Background" Value="#FFDBEDFB"/> <Setter Property="BorderBrush" Value="#FFA3AEB9"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Padding" Value="6,2,6,2"/> <Setter Property="HorizontalContentAlignment" Value="Stretch"/> <Setter Property="VerticalContentAlignment" Value="Stretch"/> <Setter Property="MinWidth" Value="5"/> <Setter Property="MinHeight" Value="5"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="controls:TabItem"> <Grid x:Name="Root" Cursor="Hand" Height="25"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0"/> <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/> </VisualStateGroup.Transitions> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"> <Storyboard> <DoubleAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="FocusVisualTop" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="0" Value="0"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="DisabledVisualTopSelected" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="DisabledVisualTopUnSelected" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="SelectionStates"> <VisualState x:Name="Unselected"/> <VisualState x:Name="Selected"/> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="FocusVisualTop" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Unfocused"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid x:Name="TemplateTopUnselected" Margin="1"> <Border x:Name="BorderTop" BorderThickness="1,1,1,0"> <Border x:Name="GradientTop" BorderThickness="1,1,1,0" CornerRadius="5,5,0,0"> <Border.BorderBrush> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFB1CCEE" Offset="0"/> <GradientStop Color="#CCB1CCEE" Offset="1"/> </LinearGradientBrush> </Border.BorderBrush> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFCEE0F7" Offset="0.091"/> <GradientStop Color="#FFDEECFD" Offset="0.996"/> <GradientStop Color="White"/> </LinearGradientBrush> </Border.Background> <Grid Margin="3,3,3,2"> <Grid.RowDefinitions> <RowDefinition Height="16"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="16"/> <ColumnDefinition/> <ColumnDefinition Width="15"/> </Grid.ColumnDefinitions> <Image x:Name="TabInactiveIcon" Source="group.png" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center" Opacity="0.395"/> <ContentControl x:Name="HeaderTopUnselected" Cursor="{TemplateBinding Cursor}" Margin="3,0" FontSize="{TemplateBinding FontSize}" Foreground="#FF416AA3" IsTabStop="False" FontFamily="Tahoma" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"/> <Button x:Name="TabInactiveCloseButton" Template="{StaticResource TabItemCloseButton}" Cursor="Hand" Height="10" HorizontalAlignment="Right" Margin="0" VerticalAlignment="Top" Width="10" Content="Button" Grid.Column="2" d:LayoutOverrides="GridBox"/> </Grid> </Border> </Border> <Border x:Name="DisabledVisualTopUnSelected" IsHitTestVisible="false" Opacity="0" Background="#8CFFFFFF" CornerRadius="3,3,0,0"/> </Grid> <Border x:Name="FocusVisualElement" Margin="-1" IsHitTestVisible="false" Visibility="Collapsed" BorderBrush="#FF6DBDD1" BorderThickness="1" CornerRadius="3,3,0,0"/> <Grid x:Name="TemplateTopSelected" Margin="0,0,0,-3" Visibility="Collapsed"> <Border x:Name="BorderTop1" BorderThickness="1,1,1,0"> <Border x:Name="GradientTop1" BorderThickness="1,1,1,0" CornerRadius="5,5,0,0"> <Border.BorderBrush> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFB1CCEE" Offset="0"/> <GradientStop Color="#CAB1CCEE" Offset="1"/> </LinearGradientBrush> </Border.BorderBrush> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFCEE0F7" Offset="0.091"/> <GradientStop Color="White" Offset="0.974"/> <GradientStop Color="White"/> </LinearGradientBrush> </Border.Background> <Grid Margin="3,3,3,2"> <Grid.RowDefinitions> <RowDefinition Height="16"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="16"/> <ColumnDefinition/> <ColumnDefinition Width="15"/> </Grid.ColumnDefinitions> <Image x:Name="TabActiveIcon" Source="user.png" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center"/> <ContentControl x:Name="HeaderTopSelected" Cursor="{TemplateBinding Cursor}" Margin="3,0" FontSize="{TemplateBinding FontSize}" Foreground="#FF416AA3" IsTabStop="False" FontFamily="Tahoma" FontWeight="Bold" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"/> <Button x:Name="TabActiveCloseButton" Template="{StaticResource TabActiveCloseButton}" Cursor="Hand" Height="10" HorizontalAlignment="Right" Margin="0" VerticalAlignment="Top" Width="10" Content="Button" Grid.Column="2" d:LayoutOverrides="GridBox"/> </Grid> </Border> </Border> <Border x:Name="FocusVisualTop" Margin="-2,-2,-2,0" IsHitTestVisible="false" Visibility="Collapsed" BorderThickness="1,1,1,0" CornerRadius="3,3,0,0"/> <Border x:Name="DisabledVisualTopSelected" Margin="-2,-2,-2,0" IsHitTestVisible="false" Opacity="0" Background="#8CFFFFFF" CornerRadius="3,3,0,0"/> </Grid> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> and my class public class ClosableTabItem : TabItem { public static readonly DependencyProperty TabIconProperty = DependencyProperty.RegisterAttached("TabInactiveIcon", typeof(Image), typeof(ClosableTabItem), null); public Image TabIcon { get { return (Image)GetValue(ClosableTabItem.TabIconProperty); } set { SetValue(ClosableTabItem.TabIconProperty, value); } } public ClosableTabItem(string header, ContentControl content, TabItemIcons icon) { // I need to be able to set the header, content and icon here } private Image GetTabIcon(TabItemIcons icon) { Image img = new Image(); switch (icon) { case TabItemIcons.User: img.Source = new BitmapImage(new Uri("/icons/user.png", UriKind.Relative)); break; case TabItemIcons.Group: img.Source = new BitmapImage(new Uri("/icons/group.png", UriKind.Relative)); break; default: break; } return img; } } This is driving me nuts, and I can't find any examples where anyone has done this without having a xaml page for the custom tab. Is this even possible? Can someone point me in the right direction? Cheers! - jonah

    Read the article

  • Windows Azure : Storage Client Exception Unhandled

    - by veda
    I am writing a code for upload large files into the blobs using blocks... When I tested it, it gave me an StorageClientException It stated: One of the request inputs is out of range. I got this exception in this line of the code: blob.PutBlock(block, ms, null); Here is my code: protected void ButUploadBlocks_click(object sender, EventArgs e) { // store upladed file as a blob storage if (uplFileUpload.HasFile) { name = uplFileUpload.FileName; byte[] byteArray = uplFileUpload.FileBytes; Int64 contentLength = byteArray.Length; int numBytesPerBlock = 250 *1024; // 250KB per block int blocksCount = (int)Math.Ceiling((double)contentLength / numBytesPerBlock); // number of blocks MemoryStream ms ; List<string>BlockIds = new List<string>(); string block; int offset = 0; // get refernce to the cloud blob container CloudBlobContainer blobContainer = cloudBlobClient.GetContainerReference("documents"); // set the name for the uploading files string UploadDocName = name; // get the blob reference and set the metadata properties CloudBlockBlob blob = blobContainer.GetBlockBlobReference(UploadDocName); blob.Properties.ContentType = uplFileUpload.PostedFile.ContentType; for (int i = 0; i < blocksCount; i++, offset = offset + numBytesPerBlock) { block = Convert.ToBase64String(BitConverter.GetBytes(i)); ms = new MemoryStream(); ms.Write(byteArray, offset, numBytesPerBlock); blob.PutBlock(block, ms, null); BlockIds.Add(block); } blob.PutBlockList(BlockIds); blob.Metadata["FILETYPE"] = "text"; } } Can anyone tell me how to solve it...

    Read the article

  • jquery Plugins/Validation using submitHandler

    - by Eyla
    Greeting, I'm using jquery Plugins/Validation library. I want to allow validation on submitting but I'm not sure where I should insert the code: I know that I can user submitHandler for that but after reading the document I had hard time to implement it so I need your help guys. jquery validation is working ok but the problem that the form still submitted even there are invalid inputs. here is my validation function and I want to know how can I make it to not submit the form if there is invalid input. by the way, I'm using asp.net button for submitting the form. here is my code: $(document).ready(function() { $("#aspnetForm").validate({ rules: { "<%=txtHomePhone.UniqueID %>": { phonehome: true }, "<%=txtMobileHome.UniqueID %>": { mobilephone: true }, "<%=txtFaxHome.UniqueID %>": { faxhome: true }, "<%=txtEmailHome.UniqueID %>": { email: true }, "<%=txtZipCodeHome.UniqueID %>": { ziphome: true }, //work "<%=txtPhonework.UniqueID %>": { phonework: true }, "<%=txtMobileWork.UniqueID %>": { mobilework: true }, "<%=txtFaxWork.UniqueID %>": { faxwork: true }, "<%=txtEmailWork.UniqueID %>": { email: true }, "<%=txtWebSite.UniqueID %>": { url: true }, "<%=txtZipWork.UniqueID %>": { zipwork: true } }, errorElement: "mydiv", wrapper: "mydiv", // a wrapper around the error message errorPlacement: function(error, element) { offset = element.offset(); error.insertBefore(element) error.addClass('message'); // add a class to the wrapper error.css('position', 'absolute'); error.css('left', offset.left + element.outerWidth()); error.css('top', offset.top - (element.height() / 2)); } });

    Read the article

  • Remoting server forcibly closing client connections in the middle of remote calls

    - by Carsten Hess
    Hello everyone. I have a system consisting of a server accepting remoting calls from clients with TCP as the underlying transportlayer. It normally works like a charm, but if I increase the no. of clients, the server starts at random to close the TCP connections in the middle of the calls. Not all calls are interrupted this way. That is really unexpected behaviour... I get no exceptions on the server side, just the client side exception: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host Server stack trace: ved System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) ved System.Runtime.Remoting.Channels.SocketStream.Read(Byte[] buffer, Int32 offset, Int32 size) ved System.Runtime.Remoting.Channels.SocketHandler.ReadFromSocket(Byte[] buffer, Int32 offset, Int32 count) ved System.Runtime.Remoting.Channels.SocketHandler.Read(Byte[] buffer, Int32 offset, Int32 count) ved System.Runtime.Remoting.Channels.SocketHandler.ReadAndMatchFourBytes(Byte[] buffer) ved System.Runtime.Remoting.Channels.Tcp.TcpSocketHandler.ReadAndMatchPreamble() ved System.Runtime.Remoting.Channels.Tcp.TcpSocketHandler.ReadVersionAndOperation(UInt16& operation) ved System.Runtime.Remoting.Channels.Tcp.TcpClientSocketHandler.ReadHeaders() ved System.Runtime.Remoting.Channels.Tcp.TcpClientTransportSink.ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream, ITransportHeaders& responseHeaders, Stream& responseStream) ved System.Runtime.Remoting.Channels.BinaryClientFormatterSink.SyncProcessMessage(IMessage msg) Exception rethrown at [0]: ved System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) ved System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) ved EBH.GuG.AgentKit.Transports.RemotingAgentHostEndPoint.SyncInvoke(Agent a, Int32 port)

    Read the article

  • Jquery animation callback issues

    - by ChrisOPeterson
    I'm trying to build a simple carousel animation with jQuery. There are 3 viewable images at any one time with buttons to click on each side to go forward or backwards. The center image is raised up by 30px to be given prominence. When one of the buttons is pushed the center image should drop down then all three images move together left or right. The initial up and down animation works but on a callback none of the other animations will work. If I hard code the direction into them only one of them works. Is there something wrong with my current code or approach? ctr_right.click(function() { carouselAnimate("right") }); ctr_left.click(function() { carouselAnimate("left") }); function carouselAnimate(direction) { var offset = img_width + img_offset; img_focus.animate({"top": "+="+focus_offset}, "slow", function() { img_left.animate({direction: "-="+offset}, "slow"); img_focus.animate({direction: "-="+offset}, "slow"); img_right.animate({direction: "-="+offset}, "slow"); }); };

    Read the article

  • Connection aborted.

    - by Pinu
    I am getting this error when i am trying to upload a file of 3mb or more on my WCF client application. SocketException (0x2745): An established connection was aborted by the software in your host machine] System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +73 System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +131 [IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.] System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +294 System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) +26 System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) +297 [WebException: The underlying connection was closed: An unexpected error occurred on a receive.] System.Net.HttpWebRequest.GetResponse() +5314029 System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +54 [CommunicationException: An error occurred while receiving the HTTP response to http://localhost:4649/Service1.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +7596735 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +275 SmartConnectClient.SmartConnect.IService1.OrderCertMail(OrderCertMailResponse OrderCertMail1) +0 SmartConnectClient.SmartConnect.Service1Client.OrderCertMail(OrderCertMailResponse OrderCertMail1) in c:\documents and settings\pkale\my documents\visual studio 2008\projects\smartconnectclient\smartconnectclient\service references\smartconnect\reference.cs:1939 SmartConnectClient.Test_CertMail_Order.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\pkale\My Documents\Visual Studio 2008\Projects\SmartConnectClient\SmartConnectClient\Test_CertMail_Order.aspx.cs:40 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +50 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627 enter code here

    Read the article

  • Date since 1600 to NSDate?

    - by Steven Fisher
    I have a date that's stored as a number of days since January 1, 1600 that I need to deal with. This is a legacy date format that I need to read many, many times in my application. Previously, I'd been creating a calendar, empty date components and root date like this: self.gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar ] autorelease]; id rootComponents = [[[NSDateComponents alloc] init] autorelease]; [rootComponents setYear: 1600]; [rootComponents setMonth: 1]; [rootComponents setDay: 1]; self.rootDate = [gregorian dateFromComponents: rootComponents]; self.offset = [[[NSDateComponents alloc] init] autorelease]; Then, to convert the integer later to a date, I use this: [offset setDay: theLegacyDate]; id eventDate = [gregorian dateByAddingComponents: offset toDate: rootDate options: 0]; (I never change any values in offset anywhere else.) The problem is I'm getting a different time for rootDate on iOS vs. Mac OS X. On Mac OS X, I'm getting midnight. On iOS, I'm getting 8:12:28. (So far, it seems to be consistent about this.) When I add my number of days later, the weird time stays. OS | legacyDate | rootDate | eventDate ======== | ========== | ==========================|========================== Mac OS X | 143671 | 1600-01-01 00:00:00 -0800 | 1993-05-11 00:00:00 -0700 iOS | 143671 | 1600-01-01 08:12:28 +0000 | 1993-05-11 07:12:28 +0000 In the previous release of my product, I didn't care about the time; now I do. Why the weird time on iOS, and what should I do about it? (I'm assuming the hour difference is DST.) I've tried setting the hour, minute and second of rootComponents to 0. This has no impact. If I set them to something other than 0, it adds them to 8:12:28. I've been wondering if this has something to do with leap seconds or other cumulative clock changes. Or is this entirely the wrong approach to use on iOS?

    Read the article

  • Modify code to change timestamp timezone in sitemap

    - by Aahan Krish
    Below is the code from a plugin I use for sitemaps. I would like to know if there's a way to "enforce" a different timezone on all date variable and functions in it. If not, how do I modify the code to change the timestamp to reflect a different timezone? Say for example, to America/New_York timezone. Please look for date to quickly get to the appropriate code blocks. Code on Pastebin. <?php /** * @package XML_Sitemaps */ class WPSEO_Sitemaps { ..... /** * Build the root sitemap -- example.com/sitemap_index.xml -- which lists sub-sitemaps * for other content types. * * @todo lastmod for sitemaps? */ function build_root_map() { global $wpdb; $options = get_wpseo_options(); $this->sitemap = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"; $base = $GLOBALS['wp_rewrite']->using_index_permalinks() ? 'index.php/' : ''; // reference post type specific sitemaps foreach ( get_post_types( array( 'public' => true ) ) as $post_type ) { if ( $post_type == 'attachment' ) continue; if ( isset( $options['post_types-' . $post_type . '-not_in_sitemap'] ) && $options['post_types-' . $post_type . '-not_in_sitemap'] ) continue; $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' LIMIT 1", $post_type ) ); // don't include post types with no posts if ( !$count ) continue; $n = ( $count > 1000 ) ? (int) ceil( $count / 1000 ) : 1; for ( $i = 0; $i < $n; $i++ ) { $count = ( $n > 1 ) ? $i + 1 : ''; if ( empty( $count ) || $count == $n ) { $date = $this->get_last_modified( $post_type ); } else { $date = $wpdb->get_var( $wpdb->prepare( "SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = %s ORDER BY post_modified_gmt ASC LIMIT 1 OFFSET %d", $post_type, $i * 1000 + 999 ) ); $date = date( 'c', strtotime( $date ) ); } $this->sitemap .= '<sitemap>' . "\n"; $this->sitemap .= '<loc>' . home_url( $base . $post_type . '-sitemap' . $count . '.xml' ) . '</loc>' . "\n"; $this->sitemap .= '<lastmod>' . htmlspecialchars( $date ) . '</lastmod>' . "\n"; $this->sitemap .= '</sitemap>' . "\n"; } } // reference taxonomy specific sitemaps foreach ( get_taxonomies( array( 'public' => true ) ) as $tax ) { if ( in_array( $tax, array( 'link_category', 'nav_menu', 'post_format' ) ) ) continue; if ( isset( $options['taxonomies-' . $tax . '-not_in_sitemap'] ) && $options['taxonomies-' . $tax . '-not_in_sitemap'] ) continue; // don't include taxonomies with no terms if ( !$wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy = %s AND count != 0 LIMIT 1", $tax ) ) ) continue; // Retrieve the post_types that are registered to this taxonomy and then retrieve last modified date for all of those combined. $taxobj = get_taxonomy( $tax ); $date = $this->get_last_modified( $taxobj->object_type ); $this->sitemap .= '<sitemap>' . "\n"; $this->sitemap .= '<loc>' . home_url( $base . $tax . '-sitemap.xml' ) . '</loc>' . "\n"; $this->sitemap .= '<lastmod>' . htmlspecialchars( $date ) . '</lastmod>' . "\n"; $this->sitemap .= '</sitemap>' . "\n"; } // allow other plugins to add their sitemaps to the index $this->sitemap .= apply_filters( 'wpseo_sitemap_index', '' ); $this->sitemap .= '</sitemapindex>'; } /** * Build a sub-sitemap for a specific post type -- example.com/post_type-sitemap.xml * * @param string $post_type Registered post type's slug */ function build_post_type_map( $post_type ) { $options = get_wpseo_options(); ............ // We grab post_date, post_name, post_author and post_status too so we can throw these objects into get_permalink, which saves a get_post call for each permalink. while ( $total > $offset ) { $join_filter = apply_filters( 'wpseo_posts_join', '', $post_type ); $where_filter = apply_filters( 'wpseo_posts_where', '', $post_type ); // Optimized query per this thread: http://wordpress.org/support/topic/plugin-wordpress-seo-by-yoast-performance-suggestion // Also see http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/ $posts = $wpdb->get_results( "SELECT l.ID, post_content, post_name, post_author, post_parent, post_modified_gmt, post_date, post_date_gmt FROM ( SELECT ID FROM $wpdb->posts {$join_filter} WHERE post_status = 'publish' AND post_password = '' AND post_type = '$post_type' {$where_filter} ORDER BY post_modified ASC LIMIT $steps OFFSET $offset ) o JOIN $wpdb->posts l ON l.ID = o.ID ORDER BY l.ID" ); /* $posts = $wpdb->get_results("SELECT ID, post_content, post_name, post_author, post_parent, post_modified_gmt, post_date, post_date_gmt FROM $wpdb->posts {$join_filter} WHERE post_status = 'publish' AND post_password = '' AND post_type = '$post_type' {$where_filter} ORDER BY post_modified ASC LIMIT $steps OFFSET $offset"); */ $offset = $offset + $steps; foreach ( $posts as $p ) { $p->post_type = $post_type; $p->post_status = 'publish'; $p->filter = 'sample'; if ( wpseo_get_value( 'meta-robots-noindex', $p->ID ) && wpseo_get_value( 'sitemap-include', $p->ID ) != 'always' ) continue; if ( wpseo_get_value( 'sitemap-include', $p->ID ) == 'never' ) continue; if ( wpseo_get_value( 'redirect', $p->ID ) && strlen( wpseo_get_value( 'redirect', $p->ID ) ) > 0 ) continue; $url = array(); $url['mod'] = ( isset( $p->post_modified_gmt ) && $p->post_modified_gmt != '0000-00-00 00:00:00' ) ? $p->post_modified_gmt : $p->post_date_gmt; $url['chf'] = 'weekly'; $url['loc'] = get_permalink( $p ); ............. } /** * Build a sub-sitemap for a specific taxonomy -- example.com/tax-sitemap.xml * * @param string $taxonomy Registered taxonomy's slug */ function build_tax_map( $taxonomy ) { $options = get_wpseo_options(); .......... // Grab last modified date $sql = "SELECT MAX(p.post_date) AS lastmod FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS term_rel ON term_rel.object_id = p.ID INNER JOIN $wpdb->term_taxonomy AS term_tax ON term_tax.term_taxonomy_id = term_rel.term_taxonomy_id AND term_tax.taxonomy = '$c->taxonomy' AND term_tax.term_id = $c->term_id WHERE p.post_status = 'publish' AND p.post_password = ''"; $url['mod'] = $wpdb->get_var( $sql ); $url['chf'] = 'weekly'; $output .= $this->sitemap_url( $url ); } } /** * Build the <url> tag for a given URL. * * @param array $url Array of parts that make up this entry * @return string */ function sitemap_url( $url ) { if ( isset( $url['mod'] ) ) $date = mysql2date( "Y-m-d\TH:i:s+00:00", $url['mod'] ); else $date = date( 'c' ); $output = "\t<url>\n"; $output .= "\t\t<loc>" . $url['loc'] . "</loc>\n"; $output .= "\t\t<lastmod>" . $date . "</lastmod>\n"; $output .= "\t\t<changefreq>" . $url['chf'] . "</changefreq>\n"; $output .= "\t\t<priority>" . str_replace( ',', '.', $url['pri'] ) . "</priority>\n"; if ( isset( $url['images'] ) && count( $url['images'] ) > 0 ) { foreach ( $url['images'] as $img ) { $output .= "\t\t<image:image>\n"; $output .= "\t\t\t<image:loc>" . esc_html( $img['src'] ) . "</image:loc>\n"; if ( isset( $img['title'] ) ) $output .= "\t\t\t<image:title>" . _wp_specialchars( html_entity_decode( $img['title'], ENT_QUOTES, get_bloginfo('charset') ) ) . "</image:title>\n"; if ( isset( $img['alt'] ) ) $output .= "\t\t\t<image:caption>" . _wp_specialchars( html_entity_decode( $img['alt'], ENT_QUOTES, get_bloginfo('charset') ) ) . "</image:caption>\n"; $output .= "\t\t</image:image>\n"; } } $output .= "\t</url>\n"; return $output; } /** * Get the modification date for the last modified post in the post type: * * @param array $post_types Post types to get the last modification date for * @return string */ function get_last_modified( $post_types ) { global $wpdb; if ( !is_array( $post_types ) ) $post_types = array( $post_types ); $result = 0; foreach ( $post_types as $post_type ) { $key = 'lastpostmodified:gmt:' . $post_type; $date = wp_cache_get( $key, 'timeinfo' ); if ( !$date ) { $date = $wpdb->get_var( $wpdb->prepare( "SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = %s ORDER BY post_modified_gmt DESC LIMIT 1", $post_type ) ); if ( $date ) wp_cache_set( $key, $date, 'timeinfo' ); } if ( strtotime( $date ) > $result ) $result = strtotime( $date ); } // Transform to W3C Date format. $result = date( 'c', $result ); return $result; } } global $wpseo_sitemaps; $wpseo_sitemaps = new WPSEO_Sitemaps();

    Read the article

  • WPF toolbar disappearing on resize

    - by user1122909
    On my main form I have a toolbar with a number of buttons. Once the parent form is resized down by dragging it so that the entire toolbar with all its buttons no longer fits in the width of the window, the whole toolbar disappears. Is there a way I can make it so that as you resize it, when you get to the width of the toolbar the inner controls of the form stop resizing and stay displayed, just cut off where the window has resized to? Code is <Grid > <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <ToolBar Grid.Row="1" Height="50" Name="tbMainToolbar" VerticalAlignment="Top" MinWidth="900" > <ToolBar.Background> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="White" Offset="0.0" /> <GradientStop Color="#DCEBFF" Offset="0.25" /> <GradientStop Color="#99CCFF" Offset="0.75" /> <GradientStop Color="#99CCFF" Offset="1.0" /> </LinearGradientBrush> </ToolBar.Background> <DockPanel LastChildFill="True"> <Button Name="btnApproved" DockPanel.Dock="Left" Click="btnToolbar_Click" CommandParameter="APPROVED" Style="{StaticResource ToolbarButtonDisplay}" HelperClasses:ButtonProperties.Image="..\..\Resources\Images\APPROVEU.GIF" Content="Approve"> </Button> ... and so forth for about 20 buttons

    Read the article

  • Javascript/PHP and timezones

    - by James
    Hi, I'd like to be able to guess the user's timezone offset and whether or not daylight savings is being applied. Currently, the most definitive code that I've found for this is here: http://www.michaelapproved.com/articles/daylight-saving-time-dst-detect/ So this gives me the offset along with the DST indicator. Now, I want to use these in my PHP scripts in order to ouput the local date/time for the user....but what's best for this? I figure I have 2 options: a) Pick a random timezone which has the same offset and DST setting from the output of timezone_abbreviations_list(). Then call date_timezone_set() with this in order to apply the correct treatment to the time. b) Continue treating the date as UTC but just do some timestamp addition to add the appropriate number of hours on. My feeling is that option B is the best way. The reason for this is that with A, I could be using a timezone which although correct in terms of offset/dst, may have some obscur rules in place behind the scene that could give surprising results (I don't know of any but nonetheless I don't think I can rule it out). I'd then re-check the timezone using Javascript at the start of each session in order to capture when either the user's timezone changes (very unlikely) or they pass in to the DST period. Sorry for the brain dump - I'm really just after some sort of reassurance that the approaches above are valid. Thanks, James.

    Read the article

  • Python import error: Symbol not found, but the symbol is present in the file

    - by Autopulated
    I get this error when I try to import ssrc.spread: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so, 2): Symbol not found: __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE The file in question (_spread.so) includes the symbol: $ nm _spread.so | grep _ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE (twice because the file is a fat ppc/x86 binary) The archive header information of _spread.so is: $ otool -fahv _spread.so Fat headers fat_magic FAT_MAGIC nfat_arch 2 architecture ppc7400 cputype CPU_TYPE_POWERPC cpusubtype CPU_SUBTYPE_POWERPC_7400 capabilities 0x0 offset 4096 size 235272 align 2^12 (4096) architecture i386 cputype CPU_TYPE_I386 cpusubtype CPU_SUBTYPE_I386_ALL capabilities 0x0 offset 241664 size 229360 align 2^12 (4096) /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so (architecture ppc7400): Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flags MH_MAGIC PPC ppc7400 0x00 BUNDLE 10 1420 NOUNDEFS DYLDLINK BINDATLOAD TWOLEVEL WEAK_DEFINES BINDS_TO_WEAK /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so (architecture i386): Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flags MH_MAGIC I386 ALL 0x00 BUNDLE 11 1604 NOUNDEFS DYLDLINK BINDATLOAD TWOLEVEL WEAK_DEFINES BINDS_TO_WEAK And my python is python 2.6.4: $ which python | xargs otool -fahv Fat headers fat_magic FAT_MAGIC nfat_arch 2 architecture ppc cputype CPU_TYPE_POWERPC cpusubtype CPU_SUBTYPE_POWERPC_ALL capabilities 0x0 offset 4096 size 9648 align 2^12 (4096) architecture i386 cputype CPU_TYPE_I386 cpusubtype CPU_SUBTYPE_I386_ALL capabilities 0x0 offset 16384 size 13176 align 2^12 (4096) /Library/Frameworks/Python.framework/Versions/2.6/bin/python (architecture ppc): Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flags MH_MAGIC PPC ALL 0x00 EXECUTE 11 1268 NOUNDEFS DYLDLINK TWOLEVEL /Library/Frameworks/Python.framework/Versions/2.6/bin/python (architecture i386): Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flags MH_MAGIC I386 ALL 0x00 EXECUTE 11 1044 NOUNDEFS DYLDLINK TWOLEVEL There seems to be a difference in the ppc architecture in the files, but I'm running on an intel, so I don't see why this should cause a problem. So why might the symbol not be found?

    Read the article

  • XSP2 crashes serving static images

    - by Dawkins
    Hi, Requesting a simple HTML page with a jpg image makes XSP2 crash. If I remove the image from the HTML then the page is served OK all the time. The version is XSP2 2.0 mono 2.6.1. the version 2.4.2.2 in the same machine works fine. I have tested it in two different machines, both Windows Vista Business SP1. Anyone has experienced the same? Any clue of what can be the problem? Below is the stack trace displayed by the console: (The line in Spanish says "it has been forced the interruption of an existing connection by the remote host") EDIT: since another user is having the same problem I have submited a bug to Novell and created a litle zip to reproduce the problem: https://bugzilla.novell.com/show_bug.cgi?id=582162 Peer unexpectedly closed the connection on write. Closing our end. System.IO.IOException: Write failure ---> System.Net.Sockets.SocketException: Se ha forzado la interrupción de una conexión existente por el host remoto. at System.Net.Sockets.Socket.Send (System.Byte[] buf, Int32 offset, Int32 size , SocketFlags flags) [0x00000] in <filename unknown>:0 at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0 at Mono.WebServer.XSPWorker.Write (System.Byte[] buffer, Int32 position, Int32 size) [0x00000] in <filename unknown>:0 Peer unexpectedly closed the connection on write. Closing our end. System.ObjectDisposedException: The object was used after being disposed. at System.Net.Sockets.NetworkStream.CheckDisposed () [0x00000] in <filename un known>:0 at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0 at Mono.WebServer.XSPWorker.Write (System.Byte[] buffer, Int32 position, Int32 size) [0x00000] in <filename unknown>:0 Thank you.

    Read the article

  • jQuery code working in Safari and Chrome but not Firefox

    - by Chris Armstrong
    I'm got a site that has a long list of tweets, and as you scroll down the right column follows you down, showing stats on the tweets. (See it in action at http://www.grapevinegame.com . Click 'memorise', then 'skip' to get to the list page. Works in Safari and Chrome). I'm using jQuery to update the top-margin of the right column, increasing it as I scroll down. It seems to be working fine in webkit-based browsers, but doesn't budge in Firefox. Heres the code, the right column element is a div with id = "distance". // Listen for scroll function $(window).scroll(function () { // Calculating the position of the scrollbar var doc = $("body"), scrollPosition = $("body").scrollTop(), pageSize = $("body").height(), windowSize = $(window).height(), fullScroll = (pageSize) - windowSize; percentageScrolled = (scrollPosition / fullScroll); var entries = $("#whispers-list > li").length; // Set position of distance counter $('div#distance').css('margin-top', ($("#whispers-list").height()+$("#latest-whisper").height()+33)*percentageScrolled); // Update distance counter $('#distance-travelled').text(Math.round(distanceTravelled*(1-percentageScrolled))); $('#whispers-list li').each(function(index) { //highlight adjacent whispers if ($('#whispers-list li:nth-child('+(index+1)+')').offset().top >= $('#distance').offset().top && $('#whispers-list li:nth-child('+(index+1)+')').offset().top <= $('#distance').offset().top + $('#distance').height()) { // alert("yup"); $('#whispers-list li:nth-child('+(index+1)+') ul').fadeTo(1, 1); } else { $('#whispers-list li:nth-child('+(index+1)+') ul').fadeTo(1, 0.5); } }); }); Appreciate any help or advice!

    Read the article

  • jquery validator message styling error in IE08 only when customised using errorPlacement function

    - by John Slaytor
    Going back to the errorplacement solution by Nadia (http://stackoverflow.com/questions/860055/jquery-override-default-validation-error-message-display-css-popup-tooltip-like) I have tried it and it works like a charm in Safari and Firefox but causes IE08 to bypass the jqueryvalidator and go straight to the server side validator. My code is this - as soon as I insert 'error element.... it is unstable in IE08. All help much appreciated <script type="text/javascript"> $(document).ready(function() { $("#sampleform").validate({ rules: { dinername: "required", venue: "required", contact: "required", dinertelephone: "required", venuetime: "required", numberdiners: "required", dineremail: { required: true, email: true}, datepicker: { required: true,date: true} }, messages: { dinername: "Your name?", numberdiners: "How many guests?", dinertelephone: "Your mobile?", venue: "Which restaurant?", venuetime: "Your arrival time?", datepicker: "Your booking date?", dineremail: "Please enter a valid email address", }, errorElement: "div", errorPlacement: function(error, element) { element.before(error); offset = element.offset(); error.css('right', offset.right); error.css('right', offset.right - element.outerHeight()); } }); }); </script> <script type="text/javascript"> $(function() { $("#datepicker") .datepicker({minDate: 0, maxDate: '+6M +0D',dateFormat: 'DD, d M yy',onClose: function() {$(this).valid();} }); }); </script> The relevant webpage is http://www.johnslaytor.com.au/nilgiris/forms/bookingform/bookingform.html

    Read the article

  • Django: Save data from form in DB

    - by Anry
    I have a model: class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() For the model I created a class form: class CostForm(ModelForm): class Meta: model = Cost fields = ['date', 'cost'] view.py: def cost(request, offset): if request.method == 'POST': #HOW save data in DB? return HttpResponseRedirect('/') else: form = CostForm() In the template file determined: <form action="/cost/{{ project }}/" method="post" accept-charset="utf-8"> <label for="date">Date:</label><input type="text" name="date" value={{ current_date }} id="date" /> <label for="cost">Cost:</label><input type="text" name="cost" value="0" id="cost" /> <p><input type="submit" value="Add"></p> </form> How save data from form in DB? P.S. offset = project name Model: class Project(models.Model): title = models.CharField(max_length=150) url = models.URLField() manager = models.ForeignKey(User) timestamp = models.DateTimeField() I tried to write: def cost(request, offset): if request.method == 'POST': form = CostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.project = Project.objects.filter(title=offset) instance.date = request.date instance.cost = request.cost instance.save() return HttpResponseRedirect('/') else: form = CostForm() But it does not work :(

    Read the article

  • How to implement escape Sequence in SDL

    - by Sa'me Smd
    Im trying to use the STL library inside the SDL. but it gives me the error "undeclared identifier" Is there any way i can use "\n"or even cout<<endl; Can the function SDL_WarpMousewhich places the mouse cursor on a desired location on screen help me with this. Because i want to put a tile on the next line sequence. I hope you get the Question. Its very vague and messed up question though (sorry for that). EDIT: void putMap(SDL_Surface* tile, SDL_Surface* screen) { for(int y = 0; y < 21; y++) { for(int x = 0; x < 60; x++) { if(maze[x][y] != '#') { apply_surface( x*10 , y*10 , tile, screen); } } cout<<endl; } } c:\documents and settings\administrator\my documents\visual studio 2008\projects\craptest\craptest\main.cpp(605) : error C2065: 'cout' : undeclared identifier c:\documents and settings\administrator\my documents\visual studio 2008\projects\craptest\craptest\main.cpp(605) : error C2065: 'endl' : undeclared identifier This is my apply_surface funtion. void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination ) { //Make a temporary rectangle to hold the offsets SDL_Rect offset; //Give the offsets to the rectangle offset.x = x; offset.y = y; //Blit the surface SDL_BlitSurface( source, NULL, destination, &offset ); }

    Read the article

  • How can I mix SVG and HTML into a page?

    - by John Duff
    I've been using the jQuery.svg plugin to do some SVG rendering and it works perfectly but I also want to have the server render some SVG into the page and I can't get that to work. How do I add some SVG like below into the page so that Firefox will render it? <svg xmlns="http://www.w3.org/2000/svg" version="1.1" preserveAspectRatio="none" viewBox="0 0 100 100"> <linearGradient id="background_gradient_black" x1="0%" y1="10" x2="0%" y2="90" gradientUnits="userSpaceOnUse"> <stop offset="0%" stop-color="#000" stop-opacity="1" /> <stop offset="45%" stop-color="#444" stop-opacity="1" /> <stop offset="55%" stop-color="#444" stop-opacity="1" /> <stop offset="100%" stop-color="#000" stop-opacity="1" /> </linearGradient> <rect x="0" y="0" width="100" height="100" fill="url(#background_gradient_black)"" /> </svg> Do I need a meta tag saying that there is SVG content in the page or define the SVG namespace somehow?

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >