Search Results

Search found 6123 results on 245 pages for 'unsigned char'.

Page 62/245 | < Previous Page | 58 59 60 61 62 63 64 65 66 67 68 69  | Next Page >

  • struct.error: unpack requires a string argument of length 4

    - by Thomas O
    Python says I need 4 bytes for a format code of "BH": struct.error: unpack requires a string argument of length 4 Here is the code, I am putting in 3 bytes as I think is needed: major, minor = struct.unpack("BH", self.fp.read(3)) "B" = Unsigned char (1 byte) + "H" unsigned short (2 bytes) = 3 bytes (!?) struct.calcsize("BH") says 4 bytes.

    Read the article

  • Padding error - when using AES Encryption in Java and Decryption in C

    - by user234445
    Hi All, I have a problem while decrypting the xl file in rijndael 'c' code (The file got encrypted in Java through JCE) and this problem is happening only for the excel files types which having formula's. Remaining all file type encryption/decryption is happening properly. (If i decrypt the same file in java the output is coming fine.) While i am dumped a file i can see the difference between java decryption and 'C' file decryption. od -c -b filename(file decrypted in C) 0034620 005 006 \0 \0 \0 \0 022 \0 022 \0 320 004 \0 \0 276 4 005 006 000 000 000 000 022 000 022 000 320 004 000 000 276 064 0034640 \0 \0 \0 \0 \f \f \f \f \f \f \f \f \f \f \f \f 000 000 000 000 014 014 014 014 014 014 014 014 014 014 014 014 0034660 od -c -b filename(file decrypted in Java) 0034620 005 006 \0 \0 \0 \0 022 \0 022 \0 320 004 \0 \0 276 4 005 006 000 000 000 000 022 000 022 000 320 004 000 000 276 064 0034640 \0 \0 \0 \0 000 000 000 000 0034644 (the above is the difference between the dumped files) The following java code i used to encrypt the file. public class AES { /** * Turns array of bytes into string * * @param buf Array of bytes to convert to hex string * @return Generated hex string */ public static void main(String[] args) throws Exception { File file = new File("testxls.xls"); byte[] lContents = new byte[(int) file.length()]; try { FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(lContents); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(256); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey skey = kgen.generateKey(); //byte[] raw = skey.getEncoded(); byte[] raw = "aabbccddeeffgghhaabbccddeeffgghh".getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(lContents); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(lContents); FileOutputStream f1 = new FileOutputStream("testxls_java.xls"); f1.write(original); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } I used the following file for decryption in 'C'. #include <stdio.h> #include "rijndael.h" #define KEYBITS 256 #include <stdio.h> #include "rijndael.h" #define KEYBITS 256 int main(int argc, char **argv) { unsigned long rk[RKLENGTH(KEYBITS)]; unsigned char key[KEYLENGTH(KEYBITS)]; int i; int nrounds; char dummy[100] = "aabbccddeeffgghhaabbccddeeffgghh"; char *password; FILE *input,*output; password = dummy; for (i = 0; i < sizeof(key); i++) key[i] = *password != 0 ? *password++ : 0; input = fopen("doc_for_logu.xlsb", "rb"); if (input == NULL) { fputs("File read error", stderr); return 1; } output = fopen("ori_c_res.xlsb","w"); nrounds = rijndaelSetupDecrypt(rk, key, 256); while (1) { unsigned char plaintext[16]; unsigned char ciphertext[16]; int j; if (fread(ciphertext, sizeof(ciphertext), 1, input) != 1) break; rijndaelDecrypt(rk, nrounds, ciphertext, plaintext); fwrite(plaintext, sizeof(plaintext), 1, output); } fclose(input); fclose(output); }

    Read the article

  • Calculating CPU frequency in C with RDTSC always returns 0

    - by Nazgulled
    Hi, The following piece of code was given to us from our instructor so we could measure some algorithms performance: #include <stdio.h> #include <unistd.h> static unsigned cyc_hi = 0, cyc_lo = 0; static void access_counter(unsigned *hi, unsigned *lo) { asm("rdtsc; movl %%edx,%0; movl %%eax,%1" : "=r" (*hi), "=r" (*lo) : /* No input */ : "%edx", "%eax"); } void start_counter() { access_counter(&cyc_hi, &cyc_lo); } double get_counter() { unsigned ncyc_hi, ncyc_lo, hi, lo, borrow; double result; access_counter(&ncyc_hi, &ncyc_lo); lo = ncyc_lo - cyc_lo; borrow = lo > ncyc_lo; hi = ncyc_hi - cyc_hi - borrow; result = (double) hi * (1 << 30) * 4 + lo; return result; } However, I need this code to be portable to machines with different CPU frequencies. For that, I'm trying to calculate the CPU frequency of the machine where the code is being run like this: int main(void) { double c1, c2; start_counter(); c1 = get_counter(); sleep(1); c2 = get_counter(); printf("CPU Frequency: %.1f MHz\n", (c2-c1)/1E6); printf("CPU Frequency: %.1f GHz\n", (c2-c1)/1E9); return 0; } The problem is that the result is always 0 and I can't understand why. I'm running Linux (Arch) as guest on VMware. On a friend's machine (MacBook) it is working to some extent; I mean, the result is bigger than 0 but it's variable because the CPU frequency is not fixed (we tried to fix it but for some reason we are not able to do it). He has a different machine which is running Linux (Ubuntu) as host and it also reports 0. This rules out the problem being on the virtual machine, which I thought it was the issue at first. Any ideas why this is happening and how can I fix it?

    Read the article

  • Foreign key,local key?

    - by user198729
    CREATE TABLE products ( id integer unsigned auto_increment primary key ) ENGINE=INNODB; CREATE TABLE orders ( id integer PRIMARY KEY auto_increment, product_id integer unsigned, quantity integer, INDEX product_id_idx (product_id), FOREIGN KEY (product_id) REFERENCES products (id) ) ENGINE=INNODB; Here the products and orders obviously have some kind of relation--foreign key relation. Also a coin has two sides,so I'm doubting how do we say which table is the foreign key side or local key side?

    Read the article

  • handling filename* parameters with spaces via RFC 5987 results in '+' in filenames

    - by Peter Friend
    I have some legacy code I am dealing with (so no I can't just use a URL with an encoded filename component) that allows a user to download a file from our website. Since our filenames are often in many different languages they are all stored as UTF-8. I wrote some code to handle the RFC5987 conversion to a proper filename* parameter. This works great until I have a filename with non-ascii characters and spaces. Per RFC, the space character is not part of attr_char so it gets encoded as %20. I have new versions of Chrome as well as Firefox and they are all converting to %20 to + on download. I have tried not encoding the space and putting the encoded filename in quotes and get the same result. I have sniffed the response coming from the server to verify that the servlet container wasn't mucking with my headers and they look correct to me. The RFC even has examples that contain %20. Am I missing something, or do all of these browsers have a bug related to this? Many thanks in advance. The code I use to encode the filename is below. Peter public static boolean bcsrch(final char[] chars, final char c) { final int len = chars.length; int base = 0; int last = len - 1; /* Last element in table */ int p; while (last >= base) { p = base + ((last - base) >> 1); if (c == chars[p]) return true; /* Key found */ else if (c < chars[p]) last = p - 1; else base = p + 1; } return false; /* Key not found */ } public static String rfc5987_encode(final String s) { final int len = s.length(); final StringBuilder sb = new StringBuilder(len << 1); final char[] digits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; final char[] attr_char = {'!','#','$','&','\'','+','-','.','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','^','_','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','|', '~'}; for (int i = 0; i < len; ++i) { final char c = s.charAt(i); if (bcsrch(attr_char, c)) sb.append(c); else { final char[] encoded = {'%', 0, 0}; encoded[1] = digits[0x0f & (c >>> 4)]; encoded[2] = digits[c & 0x0f]; sb.append(encoded); } } return sb.toString(); } Update Here is a screen shot of the download dialog I get for a file with Chinese characters with spaces as mentioned in my comment.

    Read the article

  • Linked list in C

    - by ScReYm0
    I am still new at lists in C and i got a big problem... First i wanna show you my code for inserting item to the list: void input_books_info(int number_of_books, BOOK *current) { int i; for(i = 0; i < number_of_books; i++) { while(current->next != NULL) current = current->next; current->next = (BOOK *)malloc(sizeof(BOOK)); printf_s("%d book catalog number: ", i + 1); scanf_s("%s", &current->next->catalog_number , 20); printf_s("%d book title: ", i + 1); scanf_s("%s", current->next->title ,80); printf_s("%d book author: ", i + 1); scanf_s("%s", current->next->author ,40); printf_s("%d book publisher: ", i+1); scanf_s("%s", current->next->publisher,80); printf_s("%d book price: ", i + 1); scanf_s("%f", &current->next->price, 5); printf_s("%d book year published: ", i + 1); scanf_s("%d", &current->next->year_published, 5); current->next->next = NULL; printf_s("\n\n"); } } And this is my main function: void main (void) { int number_of_books, t = 1; char book_catalog_number[STRMAX]; char book_title[STRMAX]; char book_author[STRMAX]; char reading_file[STRMAX]; char saving_file[STRMAX]; first = malloc(sizeof(BOOK)); first->next = NULL; /* printf_s("Enter file name: "); gets(saving_file); first->next = book_open(first, saving_file); */ while(t) { char m; printf_s("1. Input \n0. Exit \n\n"); printf_s("Choose operation: "); m = getch(); switch(m) { case '1': printf_s("\ninput number of books: "); scanf_s("%d", &number_of_books); input_books_info(number_of_books, first); printf_s("\n"); break; default: printf_s("\nNo entry found!\n\n\n\n\n"); break; } } } and last maybe here is the problem the printing function: void print_books_info(BOOK *current) { while(current->next != NULL && current != NULL) { printf_s("%s, ", current->next->catalog_number); printf_s("%s, ", current->author); printf_s("%s, ", current->next->title); printf_s("%s, ", current->next->author); printf_s("%s, ", current->next->publisher); printf_s("%.2f, ", current->next->price); printf_s("%d", current->next->year_published); printf_s("\n\n"); current = current->next; } } And my problem is that, when i run the app, program is moving good. But when I start the app, the program is storing only first input of data second and third are lost ... Can you help me to figure out it... ???

    Read the article

  • Variable sized packet structs with vectors

    - by Rev316
    Lately I've been diving into network programming, and I'm having some difficulty constructing a packet with a variable "data" property. Several prior questions have helped tremendously, but I'm still lacking some implementation details. I'm trying to avoid using variable sized arrays, and just use a vector. But I can't get it to be transmitted correctly, and I believe it's somewhere during serialization. Now for some code. Packet Header class Packet { public: void* Serialize(); bool Deserialize(void *message); unsigned int sender_id; unsigned int sequence_number; std::vector<char> data; }; Packet ImpL typedef struct { unsigned int sender_id; unsigned int sequence_number; std::vector<char> data; } Packet; void* Packet::Serialize(int size) { Packet* p = (Packet *) malloc(8 + 30); p->sender_id = htonl(this->sender_id); p->sequence_number = htonl(this->sequence_number); p->data.assign(size,'&'); //just for testing purposes } bool Packet::Deserialize(void *message) { Packet *s = (Packet*)message; this->sender_id = ntohl(s->sender_id); this->sequence_number = ntohl(s->sequence_number); this->data = s->data; } During execution, I simply create a packet, assign it's members, and send/receive accordingly. The above methods are only responsible for serialization. Unfortunately, the data never gets transferred. Couple of things to point out here. I'm guessing the malloc is wrong, but I'm not sure how else to compute it (i.e. what other value it would be). Other than that, I'm unsure of the proper way to use a vector in this fashion, and would love for someone to show me how (code examples please!) :) Edit: I've awarded the question to the most comprehensive answer regarding the implementation with a vector data property. Appreciate all the responses!

    Read the article

  • Why is it useful to count the number of bits?

    - by Scorchin
    I've seen the numerous questions about counting the number of set bits in a insert type of input, but why is it useful? For those looking for algorithms about bit counting, look here: http://stackoverflow.com/questions/1517848/counting-common-bits-in-a-sequence-of-unsigned-longs http://stackoverflow.com/questions/472325/fastest-way-to-count-number-of-bit-transitions-in-an-unsigned-int http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer

    Read the article

  • What could cause a Labwindows/CVI C program to hate the number 2573?

    - by Adam Bard
    Using Windows So I'm reading from a binary file a list of unsigned int data values. The file contains a number of datasets listed sequentially. Here's the function to read a single dataset from a char* pointing to the start of it: function read_dataset(char* stream, t_dataset *dataset){ //...some init, including setting dataset->size; for(i=0;i<dataset->size;i++){ dataset->samples[i] = *((unsigned int *) stream); stream += sizeof(unsigned int); } //... } Where read_dataset in such a context as this: //... char buff[10000]; t_dataset* dataset = malloc( sizeof( *dataset) ); unsigned long offset = 0; for(i=0;i<number_of_datasets; i++){ fseek(fd_in, offset, SEEK_SET); if( (n = fread(buff, sizeof(char), sizeof(*dataset), fd_in)) != sizeof(*dataset) ){ break; } read_dataset(buff, *dataset); // Do something with dataset here. It's screwed up before this, I checked. offset += profileSize; } //... Everything goes swimmingly until my loop reads the number 2573. All of a sudden it starts spitting out random and huge numbers. For example, what should be ... 1831 2229 2406 2637 2609 2573 2523 2247 ... becomes ... 1831 2229 2406 2637 2609 0xDB00000A 0xC7000009 0xB2000008 ... If you think those hex numbers look suspicious, you're right. Turns out the hex values for the values that were changed are really familiar: 2573 -> 0xA0D 2523 -> 0x9DB 2247 -> 0x8C7 So apparently this number 2573 causes my stream pointer to gain a byte. This remains until the next dataset is loaded and parsed, and god forbid it contain a number 2573. I have checked a number of spots where this happens, and each one I've checked began on 2573. I admit I'm not so talented in the world of C. What could cause this is completely and entirely opaque to me.

    Read the article

  • Accidental Complexity in OpenSSL HMAC functions

    - by Hassan Syed
    SSL Documentation Analaysis This question is pertaining the usage of the HMAC routines in OpenSSL. Since Openssl documentation is a tad on the weak side in certain areas, profiling has revealed that using the: unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len, const unsigned char *d, int n, unsigned char *md, unsigned int *md_len); From here, shows 40% of my library runtime is devoted to creating and taking down **HMAC_CTX's behind the scenes. There are also two additional function to create and destroy a HMAC_CTX explicetly: HMAC_CTX_init() initialises a HMAC_CTX before first use. It must be called. HMAC_CTX_cleanup() erases the key and other data from the HMAC_CTX and releases any associated resources. It must be called when an HMAC_CTX is no longer required. These two function calls are prefixed with: The following functions may be used if the message is not completely stored in memory My data fits entirely in memory, so I choose the HMAC function -- the one whose signature is shown above. The context, as described by the man page, is made use of by using the following two functions: HMAC_Update() can be called repeatedly with chunks of the message to be authenticated (len bytes at data). HMAC_Final() places the message authentication code in md, which must have space for the hash function output. The Scope of the Application My application generates a authentic (HMAC, which is also used a nonce), CBC-BF encrypted protocol buffer string. The code will be interfaced with various web-servers and frameworks Windows / Linux as OS, nginx, Apache and IIS as webservers and Python / .NET and C++ web-server filters. The description above should clarify that the library needs to be thread safe, and potentially have resumeable processing state -- i.e., lightweight threads sharing a OS thread (which might leave thread local memory out of the picture). The Question How do I get rid of the 40% overhead on each invocation in a (1) thread-safe / (2) resume-able state way ? (2) is optional since I have all of the source-data present in one go, and can make sure a digest is created in place without relinquishing control of the thread mid-digest-creation. So, (1) can probably be done using thread local memory -- but how do I resuse the CTX's ? does the HMAC_final() call make the CTX reusable ?. (2) optional: in this case I would have to create a pool of CTX's. (3) how does the HMAC function do this ? does it create a CTX in the scope of the function call and destroy it ? Psuedocode and commentary will be useful.

    Read the article

  • PHP & MySQL deleting multiple rows script problem.

    - by oReiLLy
    I'm trying to delete two tables rows from two different tables at once when a user clicks the delete button, but for some reason I cant get the table rows to delete can some one help me figure out what is wrong with my script? Thanks Here is the MySQL tables. CREATE TABLE cases ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, file VARCHAR(255) NOT NULL, case VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE users_cases ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, cases_id INT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, PRIMARY KEY (id) ); Here is the PHP & MySQL script. if(isset($_POST['delete_case'])) { $cases_ids = array(); $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT cases.*, users_cases.* FROM cases INNER JOIN users_cases ON users_cases.cases_id = cases.id WHERE users_cases.user_id='$user_id'"); if (!$dbc) { print mysqli_error($mysqli); } else { while($row = mysqli_fetch_array($dbc)){ $cases_ids[] = $row["cases_id"]; } } foreach($_POST['delete_id'] as $di) { if(in_array($di, $cases_ids)) { $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"DELETE FROM users_cases WHERE cases_id = '$delete_id'"); $dbc2 = mysqli_query($mysqli,"DELETE FROM cases WHERE id = '$delete_id'"); } } } Here is the XHTML. <li> <input type="text" name="file[]" size="25" /> <input type="text" name="case[]" size="25" /> <input type="text" name="name[]" size="25" /> <input type="hidden" name="delete_id" value="' . $row['cases_id'] . '" /> </li> <li> <input type="text" name="file[]" size="25" /> <input type="text" name="case[]" size="25" /> <input type="text" name="name[]" size="25" /> <input type="hidden" name="delete_id" value="' . $row['cases_id'] . '" /> </li> <li> <input type="text" name="file[]" size="25" /> <input type="text" name="case[]" size="25" /> <input type="text" name="name[]" size="25" /> <input type="hidden" name="delete_id" value="' . $row['cases_id'] . '" /> </li>

    Read the article

  • How can I optimize the import of this dataset in mysql?

    - by GeoffreyF67
    I've got the following table schema: CREATE TABLE `alexa` ( `id` int(10) unsigned NOT NULL, `rank` int(10) unsigned NOT NULL, `domain` varchar(63) NOT NULL, `domainStatus` varchar(6) DEFAULT NULL, PRIMARY KEY (`rank`), KEY `domain` (`domain`), KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 It takes several minutes to import the data. To me that seems rather slow as we're only talking about a million rows of data. What can I do to optimize the insert of this data? (already using disable keys) G-Man

    Read the article

  • access elements of a void *?

    - by user146780
    I have a void pointer and want to access elements from it. How could I transform a void * into an unsigned byte pointer so I can access its elements (which I know are actually unsigned bytes). Thanks Using C++

    Read the article

  • (static initialization order?!) problems with factory pattern

    - by smerlin
    Why does following code raise an exception (in createObjects call to map::at) alternativly the code (and its output) can be viewed here intererestingly the code works as expected if the commented lines are uncommented with both microsoft and gcc compiler (see here), this even works with initMap as ordinary static variable instead of static getter. The only reason for this i can think of is that the order of initialization of the static registerHelper_ object (factory_helper_)and the std::map object (initMap) are wrong, however i cant see how that could happen, because the map object is constructed on first usage and thats in factory_helper_ constructor, so everything should be alright shouldnt it ? I am even more suprised that those doNothing() lines fix the issue, because that call to doNothing() would happen after the critical section (which currently fails) is passed anyway. EDIT: debugging showed, that without the call to factory_helper_.doNothing(), the constructor of factory_helper_ is never called. #include <iostream> #include <string> #include <map> #define FACTORY_CLASS(classtype) \ extern const char classtype##_name_[] = #classtype; \ class classtype : FactoryBase<classtype,classtype##_name_> namespace detail_ { class registerHelperBase { public: registerHelperBase(){} protected: static std::map<std::string, void * (*)(void)>& getInitMap() { static std::map<std::string, void * (*)(void)>* initMap = 0; if(!initMap) initMap= new std::map<std::string, void * (*)(void)>(); return *initMap; } }; template<class TParent, const char* ClassName> class registerHelper_ : registerHelperBase { static registerHelper_ help_; public: //void doNothing(){} registerHelper_(){ getInitMap()[std::string(ClassName)]=&TParent::factory_init_; } }; template<class TParent, const char* ClassName> registerHelper_<TParent,ClassName> registerHelper_<TParent,ClassName>::help_; } class Factory : detail_::registerHelperBase { private: Factory(); public: static void* createObject(const std::string& objclassname) { return getInitMap().at(objclassname)(); } }; template <class TClass, const char* ClassName> class FactoryBase { private: static detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> factory_helper_; static void* factory_init_(){ return new TClass();} public: friend class detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName>; FactoryBase(){ //factory_helper_.doNothing(); } virtual ~FactoryBase(){}; }; template <class TClass, const char* ClassName> detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> FactoryBase<TClass,ClassName>::factory_helper_; FACTORY_CLASS(Test) { public: Test(){} }; int main(int argc, char** argv) { try { Test* test = (Test*) Factory::createObject("Test"); } catch(const std::exception& ex) { std::cerr << "caught std::exception: "<< ex.what() << std::endl; } #ifdef _MSC_VER system("pause"); #endif return 0; }

    Read the article

  • Explain why MickroC pic18f4550 HID example works

    - by Dr Deo
    MickroC compiler has a library for HID(Human Interface Device) usb communication. In the supplied samples, they specify that the buffers below should be in USB ram and use a pic18f4550. unsigned char readbuff[64] absolute 0x500; // Buffers should be in USB RAM, please consult datasheet unsigned char writebuff[64] absolute 0x540; But the pic18f4550 datasheet says USB ram ranges from 400h to 4FFh So why does their example work when their buffers appear not to be between 400h to 4FFh? Link to full source

    Read the article

  • C - circular character buffer w/ pthreads

    - by Matt
    I have a homework assignment where I have to implement a circular buffer and add and remove chars with separate threads: #include <pthread.h> #include <stdio.h> #define QSIZE 10 pthread_cond_t full,/* count == QSIZE */ empty,/* count == 0 */ ready; pthread_mutex_t m, n; /* implements critical section */ unsigned int iBuf, /* tail of circular queue */ oBuf; /* head of circular queue */ int count; /* count characters */ char buf [QSIZE]; /* the circular queue */ void Put(char s[]) {/* add "ch"; wait if full */ pthread_mutex_lock(&m); int size = sizeof(s)/sizeof(char); printf("size: %d", size); int i; for(i = 0; i < size; i++) { while (count >= QSIZE) pthread_cond_wait(&full, &m);/* is there empty slot? */ buf[iBuf] = s[i]; /* store the character */ iBuf = (iBuf+1) % QSIZE; /* increment mod QSIZE */ count++; if (count == 1) pthread_cond_signal(&empty);/* new character available */ } pthread_mutex_unlock(&m); } char Get() {/* remove "ch" from queue; wait if empty */ char ch; pthread_mutex_lock(&m); while (count <= 0) pthread_cond_wait(&empty, &m);/* is a character present? */ ch = buf[oBuf]; /* retrieve from the head of the queue */ oBuf = (oBuf+1) % QSIZE; count--; if (count == QSIZE-1) pthread_cond_signal(&full);/* signal existence of a slot */ pthread_mutex_unlock(&m); return ch; } void * p1(void *arg) { int i; for (i = 0; i < 5; i++) { Put("hella"); } } void * p2(void *arg) { int i; for (i = 0; i < 5; i++) { Put("goodby"); } } int main() { pthread_t t1, t2; void *r1, *r2; oBuf = 0; iBuf = 0; count=0; /* all slots are empty */ pthread_cond_init(&full, NULL); pthread_cond_init(&empty, NULL); pthread_mutex_init(&m, NULL); pthread_create(&t1, NULL, p1, &r1); pthread_create(&t2, NULL, p2, &r2); printf("Main"); char c; int i = 0; while (i < 55) { c = Get(); printf("%c",c); i++; } pthread_join(t1, &r1); pthread_join(t2, &r2); return 0; } I shouldn't have to change the logic much at all, the requirements are pretty specific. I think my problem lies in the Put() method. I think the first thread is going in and blocking the critical section and causing a deadlock. I was thinking I should make a scheduling attribute? Of course I could be wrong. I am pretty new to pthreads and concurrent programming, so I could really use some help spotting my error.

    Read the article

  • PInvokeStackImbalance C# call to unmanaged C++ function

    - by user287498
    After switching to VS2010, the managed debug assistant is displaying an error about an unbalanced stack from a call to an unmanaged C++ function from a C# application. The usuals suspects don't seem to be causing the issue. Is there something else I should check? The VS2008 built C++ dll and C# application never had a problem, no weird or mysterious bugs - yeah, I know that doesn't mean much. Here are the things that were checked: The dll name is correct. The entry point name is correct and has been verified with depends.exe - the code has to use the mangled name and it does. The calling convention is correct. The sizes and types all seem to be correct. The character set is correct. There doesn't seem to be any issues after ignoring the error and there isn't an issue when running outside the debugger. C#: [DllImport("Correct.dll", EntryPoint = "SuperSpecialOpenFileFunc", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern short SuperSpecialOpenFileFunc(ref SuperSpecialStruct stuff); [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct SuperSpecialStruct { public int field1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string field2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] public string field3; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] public string field4; public ushort field5; public ushort field6; public ushort field7; public short field8; public short field9; public uint field10; public short field11; }; C++: short SuperSpecialOpenFileFunc(SuperSpecialStruct * stuff); struct SuperSpecialStruct { int field1; char field2[256]; char field3[20]; char field4[10]; unsigned short field5; unsigned short field6; unsigned short field7; short field8; short field9; unsigned int field10; short field11; }; Here is the error: Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'Managed application path'. Additional Information: A call to PInvoke function 'SuperSpecialOpenFileFunc' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

    Read the article

  • Zend Table Relationship Modeling with Composite Key

    - by emeraldjava
    I have a table with a composite primary key using four columns. mysql> describe leaguesummary; +------------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------------+------------------+------+-----+---------+----------------+ | leagueid | int(10) unsigned | NO | PRI | NULL | auto_increment | | leaguetype | enum('I','T') | NO | PRI | NULL | | | leagueparticipantid | int(10) unsigned | NO | PRI | NULL | | | leaguestandard | int(10) unsigned | NO | | NULL | | | leaguedivision | varchar(5) | NO | PRI | NULL | | | leagueposition | int(10) unsigned | NO | | NULL | | I have the league object modelled as so (all plain enough mappings) <?php class Model_DbTable_League extends Zend_Db_Table_Abstract { protected $_name = 'league'; protected $_primary = 'id'; protected $_dependentTables = array('Model_DbTable_LeagueSummary'); And I've started like this on the new model class. I've mapped a simple reference map which returns all rows linked to the league id. // http://files.zend.com/help/Zend-Framework/zend.db.table.relationships.html // http://naneau.nl/2007/04/21/a-zend-framework-tutorial-part-one/ class Model_DbTable_LeagueSummary extends Zend_Db_Table_Abstract { protected $_name = "leaguesummary"; protected $_primary = array('leagueid', 'leaguetype','leagueparticipantid','leaguedivision'); protected $_referenceMap = array( 'Summary' => array( 'columns' => array('leagueid'), 'refTableClass' => 'Model_DbTable_League', 'refColumns' => array('id') ), ..... ); } ?> The simple case works when called from my controller public function listAction() { // action body $leagueTable = new Model_DbTable_League(); $this->view->leagues = $leagueTable->getLeagues(); $league = $leagueTable->getLeague(6); // work $summary = $league->findDependentRowset('Model_DbTable_LeagueSummary','Summary'); Zend_Debug::dump($summary,"",true); I'm not sure how i can define extra _referenceMap keys which will take extra contraint ket values. I would like to be able to define a set called 'MenA' in which the type and division values are hardcoded, and the league id is taken from the initial rowset. 'MenA' =>array( 'columns' => array('leagueid','leaguetype','leaguedivision'), 'refTableClass' => 'Model_DbTable_League', 'refColumns' => array("id","I","A") ) Is this style of mapping possible ie hardcoding the values into the 'refColumns'. The second crazy idea i had was to pass the variable values in as part of the third param of the findDependentRowset() method. $menA = $league->findDependentRowset('Model_DbTable_LeagueSummary','MenA',array("I","A")); Any suggestions on how I might use the Zend DB Table Relationship mapping correctly to do this would be appreciated. I'm not interested in the plain, old and ugly $db-select(a,b,c)-where(..) style solution.

    Read the article

  • Is it good practice to use std::size_t all over the place?

    - by dehmann
    I have a lot of constants in my code that are unsigned numbers, e.g. counters, frequency cutoffs, lengths, etc. I started using std::size_t for all of these, instead of int or unsigned int. Is that the right thing to do? I started it because the STL containers use it for their sizes, it's used for string position, etc.

    Read the article

  • Variable declarations in header files - static or not?

    - by Rob
    When refactoring away some #defines I came across declarations similar to the following in a C++ header file: static const unsigned int VAL = 42; const unsigned int ANOTHER_VAL = 37; The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic #ifndef HEADER #define HEADER #endif trick (if that matters). Does the static mean only one copy of VAL is created, in case the header is included by more than one source file?

    Read the article

  • How can I share dynamic data between Applications?

    - by Ehsan
    Hi, I use CreateFileMapping, but this method does not useful,because only static structure can be shared by this method. for example this method is good for following structure: struct MySharedData { unsigned char Flag; int Buff[10]; }; but it's not good for : struct MySharedData { unsigned char Flag; int *Buff; }; would be thankful if somebody guide me on this, Thanks in advance!

    Read the article

  • How to store array data in MySQL database using PHP & MySQL?

    - by Cyn
    I'm new to php and mysql and I'm trying to learn how to store the following array data from three different arrays friend[], hair_type[], hair_color[] using MySQL and PHP an example would be nice. Thanks Here is the HTML code. <input type="text" name="friend[]" id="friend[]" /> <select id="hair_type[]" name="hair_type[]"> <option value="Hair Type" selected="selected">Hair Type</option> <option value="Straight">Straight</option> <option value="Curly">Curly</option> <option value="Wavey">Wavey</option> <option value="Bald">Bald</option> </select> <select id="hair_color[]" name="hair_color[]"> <option value="Hair Color" selected="selected">Hair Color</option> <option value="Brown">Brown</option> <option value="Black">Black</option> <option value="Red">Red</option> <option value="Blonde">Blonde</option> </select> <input type="text" name="friend[]" id="friend[]" /> <select id="hair_type[]" name="hair_type[]"> <option value="Hair Type" selected="selected">Hair Type</option> <option value="Straight">Straight</option> <option value="Curly">Curly</option> <option value="Wavey">Wavey</option> <option value="Bald">Bald</option> </select> <select id="hair_color[]" name="hair_color[]"> <option value="Hair Color" selected="selected">Hair Color</option> <option value="Brown">Brown</option> <option value="Black">Black</option> <option value="Red">Red</option> <option value="Blonde">Blonde</option> </select> Here is the MySQL tables below. CREATE TABLE friends_hair ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, hair_id INT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, PRIMARY KEY (id) ); CREATE TABLE hair_types ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, friend TEXT NOT NULL, hair_type TEXT NOT NULL, hair_color TEXT NOT NULL, PRIMARY KEY (id) );

    Read the article

  • Using setters On Int?

    - by fuzzygoat
    Just curious, given: unsigned int pulseCounter_001; @property(nonatomic, assign)unsigned int pulseCounter_001; @synthesize pulseCounter_001; Is there any reason to use: [self setPulseCounter_001:0]; Or just use: pulseCounter_001 = 0; Style wise I think the latter says "we are setting an int" better, just curious as to any overheads involved in each? gary

    Read the article

  • Fundamental types

    - by smerlin
    I always thought the following types are "fundamental types", so i thought my anwser to this question would be correct, but surprisingly it got downvoted... Searching the web, i found this. So, IBM says aswell those types are fundamental types.. Well how do you interpret the Standard, are following types (and similar types), "fundamental types" according to the c++ standard ? unsigned int signed char long double long long long long int unsigned long long int

    Read the article

< Previous Page | 58 59 60 61 62 63 64 65 66 67 68 69  | Next Page >