Search Results

Search found 1232 results on 50 pages for 'len'.

Page 9/50 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Why is it assumed that send may return with less than requested data transmitted on a blocking socke

    - by Ernelli
    The standard method to send data on a stream socket has always been to call send with a chunk of data to write, check the return value to see if all data was sent and then keep calling send again until the whole message has been accepted. For example this is a simple example of a common scheme: int send_all(int sock, unsigned char *buffer, int len) { int nsent; while(len 0) { nsent = send(sock, buffer, len, 0); if(nsent == -1) // error return -1; buffer += nsent; len -= nsent; } return 0; // ok, all data sent } Even the BSD manpage mentions that ...If no messages space is available at the socket to hold the message to be transmitted, then send() normally blocks... Which indicates that we should assume that send may return without sending all data. Now I find this rather broken but even W. Richard Stevens assumes this in his standard reference book about network programming, not in the beginning chapters, but the more advanced examples uses his own writen (write all data) function instead of calling write. Now I consider this still to be more or less broken, since if send is not able to transmit all data or accept the data in the underlying buffer and the socket is blocking, then send should block and return when the whole send request has been accepted. I mean, in the code example above, what will happen if send returns with less data sent is that it will be called right again with a new request. What has changed since last call? At max a few hundred CPU cycles have passed so the buffer is still full. If send now accepts the data why could'nt it accept it before? Otherwise we will end upp with an inefficient loop where we are trying to send data on a socket that cannot accept data and keep trying, or else? So it seems like the workaround, if needed, results in heavily inefficient code and in those circumstances blocking sockets should be avoided at all an non blocking sockets together with select should be used instead.

    Read the article

  • Populate struct values with function argument

    - by adohertyd
    I am working on a program and part of it requires me to create a struct called DETAILS with the fields name, age, and height. I want to populate the record with data using a function argument. When I run my code I get compiler errors. I have put the errors in comment form beside the lines it is returned for but I can't fix them. Really could do with some help here guys thanks so much. Here is my code: #include <cstdlib> #include <iostream> #include <iomanip> using namespace std; const int LEN=100; struct DETAILS { char name[LEN]; int age; double height; }; person fillperson(struct DETAILS, char[LEN], int, double); int main() { struct person David; fillperson(David, "David Greene", 38, 180.0); //deprecated conversion from string constant to char * [-Wwrite-Strings] } person fillperson(struct DETAILS, char[LEN] name, int age, double height) //expected , or ... before 'name' { cin>>David.name>>name; cin>>David.age>>age; cin>>David.height>>height; cout<<"Done"<<endl; }

    Read the article

  • Unexpected performance curve from CPython merge sort

    - by vkazanov
    I have implemented a naive merge sorting algorithm in Python. Algorithm and test code is below: import time import random import matplotlib.pyplot as plt import math from collections import deque def sort(unsorted): if len(unsorted) <= 1: return unsorted to_merge = deque(deque([elem]) for elem in unsorted) while len(to_merge) > 1: left = to_merge.popleft() right = to_merge.popleft() to_merge.append(merge(left, right)) return to_merge.pop() def merge(left, right): result = deque() while left or right: if left and right: elem = left.popleft() if left[0] > right[0] else right.popleft() elif not left and right: elem = right.popleft() elif not right and left: elem = left.popleft() result.append(elem) return result LOOP_COUNT = 100 START_N = 1 END_N = 1000 def test(fun, test_data): start = time.clock() for _ in xrange(LOOP_COUNT): fun(test_data) return time.clock() - start def run_test(): timings, elem_nums = [], [] test_data = random.sample(xrange(100000), END_N) for i in xrange(START_N, END_N): loop_test_data = test_data[:i] elapsed = test(sort, loop_test_data) timings.append(elapsed) elem_nums.append(len(loop_test_data)) print "%f s --- %d elems" % (elapsed, len(loop_test_data)) plt.plot(elem_nums, timings) plt.show() run_test() As much as I can see everything is OK and I should get a nice N*logN curve as a result. But the picture differs a bit: Things I've tried to investigate the issue: PyPy. The curve is ok. Disabled the GC using the gc module. Wrong guess. Debug output showed that it doesn't even run until the end of the test. Memory profiling using meliae - nothing special or suspicious. ` I had another implementation (a recursive one using the same merge function), it acts the similar way. The more full test cycles I create - the more "jumps" there are in the curve. So how can this behaviour be explained and - hopefully - fixed? UPD: changed lists to collections.deque UPD2: added the full test code UPD3: I use Python 2.7.1 on a Ubuntu 11.04 OS, using a quad-core 2Hz notebook. I tried to turn of most of all other processes: the number of spikes went down but at least one of them was still there.

    Read the article

  • Java: split a List into two sub-Lists?

    - by Chris Conway
    What's the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It's OK to mutate the original List, so no copying should be necessary. The method signature could be /** Split a list into two sublists. The original list will be modified to * have size i and will contain exactly the same elements at indices 0 * through i-1 as it had originally; the returned list will have size * len-i (where len is the size of the original list before the call) * and will have the same elements at indices 0 through len-(i+1) as * the original list had at indices i through len-1. */ <T> List<T> split(List<T> list, int i); [EDIT] List.subList returns a view on the original list, which becomes invalid if the original is modified. So split can't use subList unless it also dispenses with the original reference (or, as in Marc Novakowski's answer, uses subList but immediately copies the result).

    Read the article

  • undefined reference to function, despite giving reference in c

    - by Jamie Edwards
    I'm following a tutorial, but when it comes to compiling and linking the code I get the following error: /tmp/cc8gRrVZ.o: In function `main': main.c:(.text+0xa): undefined reference to `monitor_clear' main.c:(.text+0x16): undefined reference to `monitor_write' collect2: ld returned 1 exit status make: *** [obj/main.o] Error 1 What that is telling me is that I haven't defined both 'monitor_clear' and 'monitor_write'. But I have, in both the header and source files. They are as follows: monitor.c: // monitor.c -- Defines functions for writing to the monitor. // heavily based on Bran's kernel development tutorials, // but rewritten for JamesM's kernel tutorials. #include "monitor.h" // The VGA framebuffer starts at 0xB8000. u16int *video_memory = (u16int *)0xB8000; // Stores the cursor position. u8int cursor_x = 0; u8int cursor_y = 0; // Updates the hardware cursor. static void move_cursor() { // The screen is 80 characters wide... u16int cursorLocation = cursor_y * 80 + cursor_x; outb(0x3D4, 14); // Tell the VGA board we are setting the high cursor byte. outb(0x3D5, cursorLocation >> 8); // Send the high cursor byte. outb(0x3D4, 15); // Tell the VGA board we are setting the low cursor byte. outb(0x3D5, cursorLocation); // Send the low cursor byte. } // Scrolls the text on the screen up by one line. static void scroll() { // Get a space character with the default colour attributes. u8int attributeByte = (0 /*black*/ << 4) | (15 /*white*/ & 0x0F); u16int blank = 0x20 /* space */ | (attributeByte << 8); // Row 25 is the end, this means we need to scroll up if(cursor_y >= 25) { // Move the current text chunk that makes up the screen // back in the buffer by a line int i; for (i = 0*80; i < 24*80; i++) { video_memory[i] = video_memory[i+80]; } // The last line should now be blank. Do this by writing // 80 spaces to it. for (i = 24*80; i < 25*80; i++) { video_memory[i] = blank; } // The cursor should now be on the last line. cursor_y = 24; } } // Writes a single character out to the screen. void monitor_put(char c) { // The background colour is black (0), the foreground is white (15). u8int backColour = 0; u8int foreColour = 15; // The attribute byte is made up of two nibbles - the lower being the // foreground colour, and the upper the background colour. u8int attributeByte = (backColour << 4) | (foreColour & 0x0F); // The attribute byte is the top 8 bits of the word we have to send to the // VGA board. u16int attribute = attributeByte << 8; u16int *location; // Handle a backspace, by moving the cursor back one space if (c == 0x08 && cursor_x) { cursor_x--; } // Handle a tab by increasing the cursor's X, but only to a point // where it is divisible by 8. else if (c == 0x09) { cursor_x = (cursor_x+8) & ~(8-1); } // Handle carriage return else if (c == '\r') { cursor_x = 0; } // Handle newline by moving cursor back to left and increasing the row else if (c == '\n') { cursor_x = 0; cursor_y++; } // Handle any other printable character. else if(c >= ' ') { location = video_memory + (cursor_y*80 + cursor_x); *location = c | attribute; cursor_x++; } // Check if we need to insert a new line because we have reached the end // of the screen. if (cursor_x >= 80) { cursor_x = 0; cursor_y ++; } // Scroll the screen if needed. scroll(); // Move the hardware cursor. move_cursor(); } // Clears the screen, by copying lots of spaces to the framebuffer. void monitor_clear() { // Make an attribute byte for the default colours u8int attributeByte = (0 /*black*/ << 4) | (15 /*white*/ & 0x0F); u16int blank = 0x20 /* space */ | (attributeByte << 8); int i; for (i = 0; i < 80*25; i++) { video_memory[i] = blank; } // Move the hardware cursor back to the start. cursor_x = 0; cursor_y = 0; move_cursor(); } // Outputs a null-terminated ASCII string to the monitor. void monitor_write(char *c) { int i = 0; while (c[i]) { monitor_put(c[i++]); } } void monitor_write_hex(u32int n) { s32int tmp; monitor_write("0x"); char noZeroes = 1; int i; for (i = 28; i > 0; i -= 4) { tmp = (n >> i) & 0xF; if (tmp == 0 && noZeroes != 0) { continue; } if (tmp >= 0xA) { noZeroes = 0; monitor_put (tmp-0xA+'a' ); } else { noZeroes = 0; monitor_put( tmp+'0' ); } } tmp = n & 0xF; if (tmp >= 0xA) { monitor_put (tmp-0xA+'a'); } else { monitor_put (tmp+'0'); } } void monitor_write_dec(u32int n) { if (n == 0) { monitor_put('0'); return; } s32int acc = n; char c[32]; int i = 0; while (acc > 0) { c[i] = '0' + acc%10; acc /= 10; i++; } c[i] = 0; char c2[32]; c2[i--] = 0; int j = 0; while(i >= 0) { c2[i--] = c[j++]; } monitor_write(c2); } monitor.h: // monitor.h -- Defines the interface for monitor.h // From JamesM's kernel development tutorials. #ifndef MONITOR_H #define MONITOR_H #include "common.h" // Write a single character out to the screen. void monitor_put(char c); // Clear the screen to all black. void monitor_clear(); // Output a null-terminated ASCII string to the monitor. void monitor_write(char *c); #endif // MONITOR_H common.c: // common.c -- Defines some global functions. // From JamesM's kernel development tutorials. #include "common.h" // Write a byte out to the specified port. void outb ( u16int port, u8int value ) { asm volatile ( "outb %1, %0" : : "dN" ( port ), "a" ( value ) ); } u8int inb ( u16int port ) { u8int ret; asm volatile ( "inb %1, %0" : "=a" ( ret ) : "dN" ( port ) ); return ret; } u16int inw ( u16int port ) { u16int ret; asm volatile ( "inw %1, %0" : "=a" ( ret ) : "dN" ( port ) ); return ret; } // Copy len bytes from src to dest. void memcpy(u8int *dest, const u8int *src, u32int len) { const u8int *sp = ( const u8int * ) src; u8int *dp = ( u8int * ) dest; for ( ; len != 0; len-- ) *dp++ =*sp++; } // Write len copies of val into dest. void memset(u8int *dest, u8int val, u32int len) { u8int *temp = ( u8int * ) dest; for ( ; len != 0; len-- ) *temp++ = val; } // Compare two strings. Should return -1 if // str1 < str2, 0 if they are equal or 1 otherwise. int strcmp(char *str1, char *str2) { int i = 0; int failed = 0; while ( str1[i] != '\0' && str2[i] != '\0' ) { if ( str1[i] != str2[i] ) { failed = 1; break; } i++; } // Why did the loop exit? if ( ( str1[i] == '\0' && str2[i] != '\0' || (str1[i] != '\0' && str2[i] =='\0' ) ) failed =1; return failed; } // Copy the NULL-terminated string src into dest, and // return dest. char *strcpy(char *dest, const char *src) { do { *dest++ = *src++; } while ( *src != 0 ); } // Concatenate the NULL-terminated string src onto // the end of dest, and return dest. char *strcat(char *dest, const char *src) { while ( *dest != 0 ) { *dest = *dest++; } do { *dest++ = *src++; } while ( *src != 0 ); return dest; } common.h: // common.h -- Defines typedefs and some global functions. // From JamesM's kernel development tutorials. #ifndef COMMON_H #define COMMON_H // Some nice typedefs, to standardise sizes across platforms. // These typedefs are written for 32-bit x86. typedef unsigned int u32int; typedef int s32int; typedef unsigned short u16int; typedef short s16int; typedef unsigned char u8int; typedef char s8int; void outb ( u16int port, u8int value ); u8int inb ( u16int port ); u16int inw ( u16int port ); #endif //COMMON_H main.c: // main.c -- Defines the C-code kernel entry point, calls initialisation routines. // Made for JamesM's tutorials <www.jamesmolloy.co.uk> #include "monitor.h" int main(struct multiboot *mboot_ptr) { monitor_clear(); monitor_write ( "hello, world!" ); return 0; } here is my makefile: C_SOURCES= main.c monitor.c common.c S_SOURCES= boot.s C_OBJECTS=$(patsubst %.c, obj/%.o, $(C_SOURCES)) S_OBJECTS=$(patsubst %.s, obj/%.o, $(S_SOURCES)) CFLAGS=-nostdlib -nostdinc -fno-builtin -fno-stack-protector -m32 -Iheaders LDFLAGS=-Tlink.ld -melf_i386 --oformat=elf32-i386 ASFLAGS=-felf all: kern/kernel .PHONY: clean clean: -rm -f kern/kernel kern/kernel: $(S_OBJECTS) $(C_OBJECTS) ld $(LDFLAGS) -o $@ $^ $(C_OBJECTS): obj/%.o : %.c gcc $(CFLAGS) $< -o $@ vpath %.c source $(S_OBJECTS): obj/%.o : %.s nasm $(ASFLAGS) $< -o $@ vpath %.s asem Hopefully this will help you understand what is going wrong and how to fix it :L Thanks in advance. Jamie.

    Read the article

  • libpcap read packet size

    - by spicyramen
    I started to write an application which will read RTP/H.264 video packets from an existing .pcap file, I need to read the packet size. I tried to use packet-len or header-len, but it never displays the right number of bytes for packets (I'm using wireshark to verify packet size - under Length column). How to do it? This is part of my code: while (packet = pcap_next(handle,&header)) { u_char *pkt_ptr = (u_char *)packet; struct ip *ip_hdr = (struct ip *)pkt_ptr; //point to an IP header structure struct pcap_pkthdr *pkt_hdr =(struct pcap_pkthdr *)packet; unsigned int packet_length = pkt_hdr->len; unsigned int ip_length = ntohs(ip_hdr->ip_len); printf("Packet # %i IP Header length: %d bytes, Packet length: %d bytes\n",pkt_counter,ip_length,packet_length); Packet # 0 IP Header length: 180 bytes, Packet length: 104857664 bytes Packet # 1 IP Header length: 52 bytes, Packet length: 104857600 bytes Packet # 2 IP Header length: 100 bytes, Packet length: 104857600 bytes Packet # 3 IP Header length: 100 bytes, Packet length: 104857664 bytes Packet # 4 IP Header length: 52 bytes, Packet length: 104857600 bytes Packet # 5 IP Header length: 100 bytes, Packet length: 104857600 bytes Another option I tried is to use: pkt_ptr- I get: read_pcapfile.c:67:43: error: request for member ‘len’ in something not a structure or union

    Read the article

  • Lazy Sequences that "Look Ahead" for Project Euler Problem 14

    - by ivar
    I'm trying to solve Project Euler Problem 14 in a lazy way. Unfortunately, I may be trying to do the impossible: create a lazy sequence that is both lazy, yet also somehow 'looks ahead' for values it hasn't computed yet. The non-lazy version I wrote to test correctness was: (defn chain-length [num] (loop [len 1 n num] (cond (= n 1) len (odd? n) (recur (inc len) (+ 1 (* 3 n))) true (recur (inc len) (/ n 2))))) Which works, but is really slow. Of course I could memoize that: (def memoized-chain (memoize (fn [n] (cond (= n 1) 1 (odd? n) (+ 1 (memoized-chain (+ 1 (* 3 n)))) true (+ 1 (memoized-chain (/ n 2))))))) However, what I really wanted to do was scratch my itch for understanding the limits of lazy sequences, and write a function like this: (def lazy-chain (letfn [(chain [n] (lazy-seq (cons (if (odd? n) (+ 1 (nth lazy-chain (dec (+ 1 (* 3 n))))) (+ 1 (nth lazy-chain (dec (/ n 2))))) (chain (+ n 1)))))] (chain 1))) Pulling elements from this will cause a stack overflow for n2, which is understandable if you think about why it needs to look 'into the future' at n=3 to know the value of the tenth element in the lazy list because (+ 1 (* 3 n)) = 10. Since lazy lists have much less overhead than memoization, I would like to know if this kind of thing is possible somehow via even more delayed evaluation or queuing?

    Read the article

  • Querying the Datastore in python

    - by Ray
    Greetings! I am trying to work with a single column in the datatstore, I can view and display the contents, like this - q = test.all() q.filter("adjclose =", "adjclose") q = db.GqlQuery("SELECT * FROM test") results = q.fetch(5) for p in results: p1 = p.adjclose print "The value is --> %f" % (p.adjclose) however i need to calculate the historical values with the adjclose column, and I am not able to get over the errors for c in range(len(p1)-1): TypeError: object of type 'float' has no len() here is my code! for c in range(len(p1)-1): p1.append(p1[c+1]-p1[c]/p1[c]) p2 = (p1[c+1]-p1[c]/p1[c]) print "the p1 value<-- %f" % (p2) print "dfd %f" %(p1) new to python, any help will be greatly appreciated! thanks in advance Ray HERE IS THE COMPLETE CODE class CalHandler(webapp.RequestHandler): def get(self): que = db.GqlQuery("SELECT * from test") user_list = que.fetch(limit=100) doRender( self, 'memberscreen2.htm', {'user_list': user_list} ) q = test.all() q.filter("adjclose =", "adjclose") q = db.GqlQuery("SELECT * FROM test") results = q.fetch(5) for p in results: p1 = p.adjclose print "The value is --> %f" % (p.adjclose) for c in range(len(p1)-1): p1.append(p1[c+1]-p1[c]/p1[c]) print "the p1 value<--> %f" % (p2) print "dfd %f" %(p1)

    Read the article

  • Devexpress Repository ComboBoxEdit loosing cursor position. Edit.SelectionStart Not being assigned

    - by user575219
    I am having an issue with my comboBoxEdit in a gridcontrol. I am using Winforms Devepress 11.2. I clicked in the text of an existing Repository comboBoxEdit, and typed in "appear backwards", however, it displayed as "sdrawkcab raeppa" like it would in a mirror. There are some posts about this topic but none of the solutions seem to work The reason for this is the following foreach (GridColumn column in this.gvNotes.Columns) { var columnEdit = column.ColumnEdit; if (columnEdit != null) { column.ColumnEdit.EditValueChanged += this.PostEditValueChanged; } } private void PostEditValueChanged(object sender, EventArgs e) { this.gvNotes.PostEditor(); } This PostEditor ensures the save button is enabled when the user is still in the current cell. The user does not need to leave the cell or change column for the changes to be posted to the grid. So this is what I did: private void PostEditValueChanged(object sender, EventArgs e) { ComboBoxEdit edit = this.gridNotes.FocusedView.ActiveEditor as ComboBoxEdit; if (edit != null) { int len = edit.SelectionLength; int start = edit.SelectionStart; gridNotes.FocusedView.PostEditor(); edit.SelectionLength = len; edit.SelectionStart = start; } This did not solve the problem of the cursor resetting to the start position. Edit.SelectionStart is not being assinged to the len value.Even though len changes to 1 edit.SelectionStart remains at 0 Does anyone know what event needs to be handled to not loose the cursor position?

    Read the article

  • Simplifying for-if messes with better structure?

    - by HH
    # Description: you are given a bitwise pattern and a string # you need to find the number of times the pattern matches in the string # any one liner or simple pythonic solution? import random def matchIt(yourString, yourPattern): """find the number of times yourPattern occurs in yourString""" count = 0 matchTimes = 0 # How can you simplify the for-if structures? for coin in yourString: #return to base if count == len(pattern): matchTimes = matchTimes + 1 count = 0 #special case to return to 2, there could be more this type of conditions #so this type of if-conditionals are screaming for a havoc if count == 2 and pattern[count] == 1: count = count - 1 #the work horse #it could be simpler by breaking the intial string of lenght 'l' #to blocks of pattern-length, the number of them is 'l - len(pattern)-1' if coin == pattern[count]: count=count+1 average = len(yourString)/matchTimes return [average, matchTimes] # Generates the list myString =[] for x in range(10000): myString= myString + [int(random.random()*2)] pattern = [1,0,0] result = matchIt(myString, pattern) print("The sample had "+str(result[1])+" matches and its size was "+str(len(myString))+".\n" + "So it took "+str(result[0])+" steps in average.\n" + "RESULT: "+str([a for a in "FAILURE" if result[0] != 8])) # Sample Output # # The sample had 1656 matches and its size was 10000. # So it took 6 steps in average. # RESULT: ['F', 'A', 'I', 'L', 'U', 'R', 'E']

    Read the article

  • null terminating a string

    - by robUK
    Hello, gcc 4.4.4 c89 just wondering what is the standard way to null terminate a string. i.e. However, when I use the NULL I get the warning message. *dest++ = 0; *dest++ = '\0'; *dest++ = NULL; /* Warning: Assignment takes integer from pointer without a cast */ source code I am using: size_t s_strscpy(char *dest, const char *src, const size_t len) { /* Copy the contents from src to dest */ size_t i = 0; for(i = 0; i < len; i++) *dest++ = *src++; /* Null terminate dest */ *dest++ = 0; return i; } Just another quick question. I deliberately commented out the line that null terminates. However, it still correctly printed out the contents of the dest. The caller of this function would send the length of the string by either included the NULL or not. i.e. strlen(src) + 1 or stlen(src). size_t s_strscpy(char *dest, const char *src, const size_t len) { /* Copy the contents from src to dest */ size_t i = 0; /* Don't copy the null terminator */ for(i = 0; i < len - 1; i++) *dest++ = *src++; /* Don't add the Null terminator */ /* *dest++ = 0; */ return i; } Many thanks for any advice,

    Read the article

  • Prog error: for replacing spaces with "%20"

    - by assasinC
    below is the prog i am compiling for replacing spaces with "%20" but when I run it output window shows blank and a message "arrays5.exe has occurred a prob" #include <iostream> #include<cstring> using namespace std; void method(char str[], int len) //replaces spaces with "%20" { int spaces, newlen,i; for (i=0;i<len;i++) if(str[i]==' ') spaces++; newlen=len+spaces*2; str[newlen]=0; for (i=len-1;i>=0;i--) { if(str[i]==' ') { str[newlen-1]='0'; str[newlen-2]='2'; str[newlen-3]='%'; newlen=newlen-3; } else { str[newlen-1]=str[i]; newlen=newlen-1; } } } int main() { char str[20]="sa h "; method(str,5); cout <<str<<endl; return 0; } Please help me finding the error.Thanks

    Read the article

  • How can I override list methods to do vector addition and subtraction in python?

    - by Bobble
    I originally implemented this as a wrapper class around a list, but I was annoyed by the number of operator() methods I needed to provide, so I had a go at simply subclassing list. This is my test code: class CleverList(list): def __add__(self, other): copy = self[:] for i in range(len(self)): copy[i] += other[i] return copy def __sub__(self, other): copy = self[:] for i in range(len(self)): copy[i] -= other[i] return copy def __iadd__(self, other): for i in range(len(self)): self[i] += other[i] return self def __isub__(self, other): for i in range(len(self)): self[i] -= other[i] return self a = CleverList([0, 1]) b = CleverList([3, 4]) print('CleverList does vector arith: a, b, a+b, a-b = ', a, b, a+b, a-b) c = a[:] print('clone test: e = a[:]: a, e = ', a, c) c += a print('OOPS: augmented addition: c += a: a, c = ', a, c) c -= b print('OOPS: augmented subtraction: c -= b: b, c, a = ', b, c, a) Normal addition and subtraction work in the expected manner, but there are problems with the augmented addition and subtraction. Here is the output: >>> CleverList does vector arith: a, b, a+b, a-b = [0, 1] [3, 4] [3, 5] [-3, -3] clone test: e = a[:]: a, e = [0, 1] [0, 1] OOPS: augmented addition: c += a: a, c = [0, 1] [0, 1, 0, 1] Traceback (most recent call last): File "/home/bob/Documents/Python/listTest.py", line 35, in <module> c -= b TypeError: unsupported operand type(s) for -=: 'list' and 'CleverList' >>> Is there a neat and simple way to get augmented operators working in this example?

    Read the article

  • Pickled my dictionary from ZODB but i got a less in size one?

    - by Someone Someoneelse
    I use ZODB and i want to copy my 'database_1.fs' file to another 'database_2.fs', so I opened the root dictionary of that 'database_1.fs' and I (pickle.dump) it in a text file. Then I (pickle.load) it in a dictionary-variable, in the end I update the root dictionary of the other 'database_2.fs' with the dictionary-variable. It works, but I wonder why the size of the 'database_1.fs' not equal to the size of the other 'database_2.fs'. They are still copies of each other. def openstorage(store): #opens the database data={} data['file']=filestorage data['db']=DB(data['file']) data['conn']=data['db'].open() data['root']=data['conn'].root() return data def getroot(dicty): return dicty['root'] def closestorage(dicty): #close the database after Saving transaction.commit() dicty['file'].close() dicty['db'].close() dicty['conn'].close() transaction.get().abort() then that's what i do:- import pickle loc1='G:\\database_1.fs' op1=openstorage(loc1) root1=getroot(op1) loc2='G:database_2.fs' op2=openstorage(loc2) root2=getroot(op2) >>> len(root1) 215 >>> len(root2) 0 pickle.dump( root1, open( "save.txt", "wb" )) item=pickle.load( open( "save.txt", "rb" ) ) #now item is a dictionary root2.update(item) closestorage(op1) closestorage(op2) #after I open both of the databases #I get the same keys in both databases #But `database_2.fs` is smaller that `database_2.fs` in size I mean. >>> len(root2)==len(root1)==215 #they have the same keys True Note: (1) there are persistent dictionaries and lists in the original database_1.fs (2) both of them have the same length and the same indexes.

    Read the article

  • Python script not working when run from browser directly

    - by splatterdash
    I'm trying to run this script: import re, os def build_pool(cwd): global xtn_pool, file_pool xtn, xtn_pool = re.compile('\\.[0-9a-zA-Z]{1,4}$'), [] file_pool = [files for files in os.listdir(cwd) if os.path.isfile(files) and xtn.search(files)] # Lists all the file extension in the folder for file in file_pool: if not xtn_pool.__contains__(xtn.search(file).group()): xtn_pool.append(xtn.search(file).group()) return xtn_pool.sort(), file_pool if __name__ == '__main__': import sys #if path is given, change working directory to path if len(sys.argv) >= 2: os.chdir(sys.argv[1]) build_pool(os.getcwd()) #if no path is given when running, do renaming in current folder else: build_pool(os.getcwd()) print('The folder contains the following extensions: ') for i in range(0, len(xtn_pool)): print(repr(i+1) + '. ' + xtn_pool[i][1:]) opt = int(input('Which one would you like to replace? ')) xtn_pick = xtn_pool[opt-1] # Lists all the file with the chosen extension xtn_file_pool = [file for file in file_pool if file.endswith(xtn_pick)] print('There are {0} files with the {1} extension.'.format(len(xtn_file_pool), xtn_pick)) xtn_new = input('Input replacement extension: ') # The actual renaming process for file in xtn_file_pool: os.rename(file, file[:-len(xtn_pick)+1] + xtn_new) directly from my file browser (Nautilus), but for some reason it's not working. When I run it from terminal (python3 scriptname.py) it works fine as intended. But when I just click the script file in Nautilus, choose 'Run in Terminal', it always stops after asking 'Input replacement extension: '. How can I make this script run without using the terminal?

    Read the article

  • Creating a new variable in C from only part of an existing u_char

    - by Alex Kloss
    I'm writing some C code to parse IEEE 802.11 frames, but I'm stuck trying to create a new variable whose length depends on the size of the frame itself. Here's the code I currently have: int frame_body_len = pkt_hdr->len - radio_hdr->len - wifi_hdr_len - 4; u_char *frame_body = (u_char *) (packet + radio_hdr->len + wifi_hdr_len); Basically, the frame consists of a header, a body, and a checksum at the end. I can calculate the length of the frame body by taking the length of the packet and subtracting the length of the two headers that appear before it (radio_hdr->len and wifi_hdr_len respectively), plus 4 bytes at the end for the checksum. However, how can I create the frame_body variable without the trailing checksum? Right now, I'm initializing it with the contents of the packet starting at the position after the two headers, but is there some way to start at that position and end 4 bytes before the end of packet? packet is a pointer to a u_char, if it helps. I'm a new C programmer, so any and all advice about my code you can give me would be much appreciated. Thanks!

    Read the article

  • Error in value of default parameter [Bug in Visual C++ 2008?]

    - by HellBoy
    I am facing following issue while trying to use template in my code I have some C++ code which i call from C functions. Problem is I am getting different values in the following code for statement 1 and 2. Type id : unsigned int statement 1 : 4 statement 2 : 1 C++ Code : template <typename T> void func(T* value, unsigned int len = sizeof(T)) { cout << "Type id : " << typeid(T).name() << endl; cout << "statement 1 " << sizeof(T) << endl; cout << "statement 2 " << len << endl; } template <typename T> void func1(T data) { T val = data; func(&val); } C Code : void test(void *ptr, unsigned int len) { switch(len) { case 1: func1(*(static_cast<uint32_t *>(ptr)) break; } } This happens only on windows. On Linux it works fine.

    Read the article

  • method works fine, until it is called in a function, then UnboundLocalError

    - by user1776100
    I define a method called dist, to calculate the distance between two points which I does it correctly when directly using the method. However, when I get a function to call it to calculate the distance between two points, I get UnboundLocalError: local variable 'minkowski_distance' referenced before assignment edit sorry, I just realised, this function does work. However I have another method calling it that doesn't. I put the last method at the bottom This is the method: class MinkowskiDistance(Distance): def __init__(self, dist_funct_name_str = 'Minkowski distance', p=2): self.p = p def dist(self, obj_a, obj_b): distance_to_power_p=0 p=self.p for i in range(len(obj_a)): distance_to_power_p += abs((obj_a[i]-obj_b[i]))**(p) minkowski_distance = (distance_to_power_p)**(1/p) return minkowski_distance and this is the function: (it basically splits the tuples x and y into their number and string components and calculates the distance between the numeric part of x and y and then the distance between the string parts, then adds them. def total_dist(x, y, p=2, q=2): jacard = QGramDistance(q=q) minkowski = MinkowskiDistance(p=p) x_num = [] x_str = [] y_num = [] y_str = [] #I am spliting each vector into its numerical parts and its string parts so that the distances #of each part can be found, then summed together. for i in range(len(x)): if type(x[i]) == float or type(x[i]) == int: x_num.append(x[i]) y_num.append(y[i]) else: x_str.append(x[i]) y_str.append(y[i]) num_dist = minkowski.dist(x_num,y_num) str_dist = I find using some more steps #I am simply adding the two types of distance to get the total distance: return num_dist + str_dist class NearestNeighbourClustering(Clustering): def __init__(self, data_file, clust_algo_name_str='', strip_header = "no", remove = -1): self.data_file= data_file self.header_strip = strip_header self.remove_column = remove def run_clustering(self, max_dist, p=2, q=2): K = {} #dictionary of clusters data_points = self.read_data_file() K[0]=[data_points[0]] k=0 #I added the first point in the data to the 0th cluster #k = number of clusters minus 1 n = len(data_points) for i in range(1,n): data_point_in_a_cluster = "no" for c in range(k+1): distances_from_i = [total_dist(data_points[i],K[c][j], p=p, q=q) for j in range(len(K[c]))] d = min(distances_from_i) if d <= max_dist: K[c].append(data_points[i]) data_point_in_a_cluster = "yes" if data_point_in_a_cluster == "no": k += 1 K[k]=[data_points[i]] return K

    Read the article

  • Finding k elements of length-n list that sum to less than t in O(nlogk) time

    - by tresbot
    This is from Programming Pearls ed. 2, Column 2, Problem 8: Given a set of n real numbers, a real number t, and an integer k, how quickly can you determine whether there exists a k-element subset of the set that sums to at most t? One easy solution is to sort and sum the first k elements, which is our best hope to find such a sum. However, in the solutions section Bentley alludes to a solution that takes nlog(k) time, though he gives no hints for how to find it. I've been struggling with this; one thought I had was to go through the list and add all the elements less than t/k (in O(n) time); say there are m1 < k such elements, and they sum to s1 < t. Then we are left needing k - m1 elements, so we can scan through the list again in O(n) time looking for all elements less than (t - s1)/(k - m1). Add in again, to get s2 and m2, then again if m2 < k, look for all elements less than (t - s2)/(k - m2). So: def kSubsetSumUnderT(inList, k, t): outList = [] s = 0 m = 0 while len(outList) < k: toJoin = [i for i in inList where i < (t - s)/(k - m)] if len(toJoin): if len(toJoin) >= k - m: toJoin.sort() if(s0 + sum(toJoin[0:(k - m - 1)]) < t: return True return False outList = outList + toJoin s += sum(toJoin) m += len(toJoin) else: return False My intuition is that this might be the O(nlog(k)) algorithm, but I am having a hard time proving it to myself. Thoughts?

    Read the article

  • replacing space with %20

    - by Codenotguru
    The following program replaces all spaces with %20.the compilation works fine but the program terminates during the runtime.Any help??? #include<iostream> #include<string> using namespace std; void removeSpaces(string url){ int len=url.length(); int i,count=0; while(i<=len){ if(url[i]==' ') count++; i++; } int length2=len+(count*2); string newarr[length2]; for(int j=len-1;j>=0;j--){ if(url[j]==' ') { newarr[length2-1]='0'; newarr[length2-2]='2'; newarr[length2-3]='%'; length2=length2-3; } else { newarr[length2-1]=url[j]; length2=length2-1; } } cout<<"\nThe number of spaces in the url is:"<<count; cout<<"\nThe replaced url is:"<<newarr; } int main(){ string url="http://www.ya h o o.com/"; removeSpaces(url); }

    Read the article

  • MYSQL stored function - create function (function definition) problem using FORMAT

    - by Jason Fonseca
    Hi all, I keep receiving an error with the following code. I am trying to make a function that will format a field (content=0.0032) into a varchar/percent (content=0.32%). At the moment i'm just trying to get format to work, and it throws up an error "Error Code : 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'len);" The function definition for "Format" is "Format(X,d)" where x is the number and d is the number of decimal places to round too. It then should output a string ###,###,###.## etc. My code is as follows: DROP FUNCTION IF EXISTS percent; DELIMITER $$ CREATE /*[DEFINER = { user | CURRENT_USER }]*/ FUNCTION `auau7859_aba`.`percent`(num DOUBLE, len INT) RETURNS VARCHAR(10) DETERMINISTIC BEGIN RETURN FORMAT(num,len); END$$ DELIMITER ; Save me...Luke

    Read the article

  • Checking existence of file types via extensions bash.

    - by Tommy
    Hi, I need to test if various file types exist in a directory. I've tried $ [ -f *.$fileext] where fileext is the file extension but that does not seem to work. Both of these methods work function checkext() { fileext=$1 ls *.$fileext>/dev/null 2>&1 if [ $? -eq 0 ] then echo "We have $fileext files!" else echo "We don't have any $fileext files!" fi } and function checkext2() { extention=$1 filescheck=(`ls *.$1`) len=${#filescheck[*]} if [ $len -gt 0 ] then echo "We have $extention files!" else if [ $len -eq 0 ] then echo "We don't have any $extention files!" else echo "Error" fi fi } The second method is less tidy as any ls error is shown so I prefer method 1. Could people please suggest any improvements, more elegant solutions e.t.c

    Read the article

  • Problem reading hexadecimal buffer from C socket

    - by Olaseni
    I'm using the SDL_net sockets API to create a server and client. I can easily read a string buffer, but when I try to send hexadecimal data, recv gets the length, but I cannot seem to be a able to read the buffer contents. IPaddress ip; TCPsocket server,client; int bufSize = 1024; char message[bufSize]; int len; server = SDLNet_TCP_Open(&ip); client = SDLNet_TCP_Accept(server); len = SDLNet_TCP_Recv(client,message,bufSize); Here's a snippet. the buffer length "len" is set (i.e. message length) but I can't get to the data contents in the message buffer. Some sample bind_transmitter PDU data was sent by a random client to the server at that port. I can't read the PDU (SMPP).

    Read the article

  • Setting glutBitmapCharacter color?

    - by colordot
    Just wondering if someone can help me track down my issue with the following code where the text color is not being set correctly (its just rendering whatever color is in the background) void RenderText(int x, int y, const char *string) { int i, len; glUseProgram(0); glLoadIdentity(); glColor3f(1.0f, 1.0f, 1.0f); glTranslatef(0.0f, 0.0f, -5.0f); glRasterPos2i(x, y); glDisable(GL_TEXTURE_2D); for (i = 0, len = strlen(string); i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_8_BY_13, (int)string[i]); } glEnable(GL_TEXTURE_2D); } I've checked all the usual things (I think), disabling texturing, setting color before rasterPos'ing, etc Ive disabled shaders but Im still having issues

    Read the article

  • Safari Javascript parent.frames.length

    - by Engwan
    I get a parse error from Safari with this code: for (var i=0; i<parent.frames.length; i++){...} doing alert(parent.frames.length); works and outputs the correct value which is 5. I also tried but failed: var len = parent.frames.length alert(len); //Correct for (var i=0; i<len; i++){...} //Parse Error When i type this code into the console directly, it works fine. And it also works fine in other browsers. What seems to be the problem?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >