Search Results

Search found 36506 results on 1461 pages for 'unsigned long long int'.

Page 1/1461 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • The code works but when using printf it gives me a weird answer. Help please [closed]

    - by user71458
    //Programmer-William Chen //Seventh Period Computer Science II //Problem Statement - First get the elapsed times and the program will find the //split times for the user to see. // //Algorithm- First the programmer makes the prototype and calls them in the //main function. The programmer then asks the user to input lap time data. //Secondly, you convert the splits into seconds and subtract them so you can //find the splits. Then the average is all the lap time's in seconds. Finally, //the programmer printf all the results for the user to see. #include <iostream> #include <stdlib.h> #include <math.h> #include <conio.h> #include <stdio.h> using namespace std; void thisgetsElapsedTimes( int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5); //this is prototype void thisconvertstoseconds ( int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5, int &split1, int &split2, int &split3, int &split4, int &split5);//this too void thisfindsSplits(int &m1, int &m2, int &m3, int &m4, int &m5, int &split1, int &split2, int &split3, int &split4, int &split5, int &split6, int &split7, int &split8, int &split9, int &split10);// this is part of prototype void thisisthesecondconversation (int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S,int &split2S, int &split3S, int &split4S, int &split5S, int &split1, int &split2, int &split3, int &split4, int &split5);//this gets a value void thisfindstheaverage(double &average, int &split1, int &split2, int &split3, int &split4, int &split5);//and this void thisprintsstuff( int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S, int &split2S, int &split3S, int &split4S, int &split5S, double &average); //this prints int main(int argc, char *argv[]) { int m1, m2, m3, m4, m5, s1, s2, s3, s4, s5, split1, split2, split3, split4, split5, split1M, split2M, split3M, split4M, split5M, split1S, split2S, split3S, split4S, split5S; int split6, split7, split8, split9, split10; double average; char thistakescolon; thisgetsElapsedTimes ( m1, m2, m3, m4, m5, s1, s2, s3, s4, s5); thisconvertstoseconds ( m1, m2, m3, m4, m5, s1, s2, s3, s4, s5, split1, split2, split3, split4, split5); thisfindsSplits ( m1, m2, m3, m4, m5, split1, split2, split3, split4, split5, split6, split7, split8, split9, split10); thisisthesecondconversation ( split1M, split2M, split3M, split4M, split5M, split1S, split2S, split3S, split4S, split5S, split1, split2, split3, split4, split5); thisfindstheaverage ( average, split1, split2, split3, split4, split5); thisprintsstuff ( split1M, split2M, split3M, split4M, split5M, split1S, split2S, split3S, split4S, split5S, average); // these are calling statements and they call from the main function to the other functions. system("PAUSE"); return 0; } void thisgetsElapsedTimes(int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5) { char thistakescolon; cout << "Enter the elapsed time:" << endl; cout << " Kilometer 1 "; cin m1 thistakescolon s1; cout << " Kilometer 2 "; cin m2 thistakescolon s2; cout << " Kilometer 3 " ; cin m3 thistakescolon s3; cout << " Kilometer 4 "; cin m4 thistakescolon s4; cout << " Kilometer 5 "; cin m5 thistakescolon s5; // this gets the data required to get the results needed for the user to see // . } void thisconvertstoseconds (int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5, int &split1, int &split2, int &split3, int &split4, int &split5) { split1 = (m1 * 60) + s1;//this converts for minutes to seconds for m1 split2 = (m2 * 60) + s2;//this converts for minutes to seconds for m2 split3 = (m3 * 60) + s3;//this converts for minutes to seconds for m3 split4 = (m4 * 60) + s4;//this converts for minutes to seconds for m4 split5 = (m5 * 60) + s5;//this converts for minutes to seconds for m5 } void thisfindsSplits (int &m1, int &m2, int &m3, int &m4, int &m5,int &split1, int &split2, int &split3, int &split4, int &split5, int &split6, int &split7, int &split8, int &split9, int &split10)//this is function heading { split6 = split1; //this is split for the first lap. split7 = split2 - split1;//this is split for the second lap. split8 = split3 - split2;//this is split for the third lap. split9 = split4 - split3;//this is split for the fourth lap. split10 = split5 - split4;//this is split for the fifth lap. } void thisfindstheaverage(double &average, int &split1, int &split2, int &split3, int &split4, int &split5) { average = (split1 + split2 + split3 + split4 + split5)/5; // this finds the average from all the splits in seconds } void thisisthesecondconversation (int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S,int &split2S, int &split3S, int &split4S, int &split5S, int &split1, int &split2, int &split3, int &split4, int &split5) { split1M = split1 * 60; //this finds the split times split1S = split1M - split1 * 60; //then this finds split2M = split2 * 60; //and all of this split2S = split2M - split2 * 60; //does basically split3M = split3 * 60; //the same thing split3S = split3M - split3 * 60; //all of it split4M = split4 * 60; //it's also a split4S = split4M - split4 * 60; //function split5M = split5 * 60; //and it finds the splits split5S = split5M - split5 * 60; //for each lap. } void thisprintsstuff (int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S, int &split2S, int &split3S, int &split4S, int &split5S, double &average)// this is function heading { printf("\n kilometer 1 %d" , ":02%d",'split1M','split1S'); printf("\n kilometer 2 %d" , ":02%d",'split2M','split2S'); printf("\n kilometer 3 %d" , ":02%d",'split3M','split3S'); printf("\n kilometer 4 %d" , ":02%d",'split4M','split4S'); printf("\n kilometer 5 %d" , ":02%d",'split5M','split5S'); printf("\n your average pace is ",'average',"per kilometer \n", "William Chen\n"); // this printf so the programmer // can allow the user to see // the results from the data gathered. }

    Read the article

  • Converting between unsigned and signed int safely

    - by polemic
    I have an interface between a client and a server where a client sends (1) an unsigned value, and (2) a flag which indicates if value is signed/unsigned. Server would then static cast unsigned value to appropriate type. I later found out that this is implementation defined behavior and I've been reading about it but I couldn't seem to find an appropriate solution that's completely safe? I've read about type punning, pointer conversions, and memcpy. Would simply using a union type work? A UnionType containing signed and unsigned int, along with the signed/unsigned flag. For signed values, client sets the signed part of the union, and server reads the signed part. Same for the unsigned part. Or am I completely misunderstanding something? Side question: how do I know the specific behavior in this case for a specific scenario, e.g. windriver diab on PPC? I'm a bit lost on how to find such documentation.

    Read the article

  • Pros and cons of ways of storing an unsigned int without an unsigned int data type

    - by fields
    I have values that are 64-bit unsigned ints, and I need to store them in mongodb, which has no unsigned int type. I see three main possibilities for storing them in other field types, and converting on going in and out: Using a signed int is probably easiest and most space efficient, but has the disadvantage that they're not human readable and if someone forgets to do the conversion, some of them will work, which may obscure errors. Raw binary is probably most difficult for inexperienced programmers to deal with, and also suffers from non-human-readability. A string representation is the least space efficient (~40 bytes in unicode vs 8 bytes per field), but then at least all of the possible values will map properly, and for querying only a conversion to string is required instead of a more complicated conversion. I need these values to be available from different platforms, so a single driver-specific solution isn't an option. Any major pros and cons I've missed? Which one would you use?

    Read the article

  • (int) Math.floor(x / TILESIZE) or just (int) (x / TILESIZE)

    - by Aidan Mueller
    I have a Array that stores my map data and my Tiles are 64X64. Sometimes I need to convert from pixels to units of tiles. So I was doing: int x int y public void myFunction() { getTile((int) Math.floor(x / 64), (int) Math.floor(y / 64)).doOperation(); } But I discovered by using (I'm using java BTW) System.out.println((int) (1 / 1.5)) that converting to an int automatically rounds down. This means that I can replace the (int) Math.floor with just x / 64. But if I run this on a different OS do you think it might give a different result? I'm just afraid there might be some case where this would round up and not down. Should I keep doing it the way I was and maybe make a function like convert(int i) to make it easier? Or is it OK to just do x / 64?

    Read the article

  • Why unsigned int contained negative number

    - by Daziplqa
    Hi All, I am new to C, What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negative number to an unsigned int: 1 /* 2 * ===================================================================================== 3 * 4 * Filename: prog4.c 5 * 6 * ===================================================================================== 7 */ 8 9 #include <stdio.h> 10 11 int main(void){ 12 13 int v1 =0, v2=0; 14 unsigned int sum; 15 16 v1 = 10; 17 v2 = 20; 18 19 sum = v1 - v2; 20 21 printf("The subtraction of %i from %i is %i \n" , v1, v2, sum); 22 23 return 0; 24 } The output is : The subtraction of 10 from 20 is -10

    Read the article

  • C# acting weird when reading in values from a file to an array

    - by Whitey
    This is the structure of my file: 1111111111111111111111111 2222222222222222222222222 3333333333333333333333333 4444444444444444444444444 5555555555555555555555555 6666666666666666666666666 7777777777777777777777777 8888888888888888888888888 9999999999999999999999999 0000000000000000000000000 0000000000000000000000000 0000000000000000000000000 0000000000000000000000000 0000000000000000000000000 And this is the code I'm using to read it into an array: using (StreamReader reader = new StreamReader(mapPath)) { string line; for (int i = 0; i < iMapHeight; i++) { if ((line = reader.ReadLine()) != null) { for (int j = 0; j < iMapWidth; j++) { iMap[i, j] = line[j]; } } } } I have done some debugging, and line[j] correctly iterates through each character in the currently read line. The problem lies with iMap[i, j]. After this block of code executes, this is the contents of iMap: - iMap {int[14, 25]} int[,] [0, 0] 49 int [0, 1] 49 int [0, 2] 49 int [0, 3] 49 int [0, 4] 49 int [0, 5] 49 int [0, 6] 49 int [0, 7] 49 int [0, 8] 49 int [0, 9] 49 int [0, 10] 49 int [0, 11] 49 int [0, 12] 49 int [0, 13] 49 int [0, 14] 49 int [0, 15] 49 int [0, 16] 49 int [0, 17] 49 int [0, 18] 49 int [0, 19] 49 int [0, 20] 49 int [0, 21] 49 int [0, 22] 49 int [0, 23] 49 int [0, 24] 49 int [1, 0] 50 int [1, 1] 50 int [1, 2] 50 int [1, 3] 50 int [1, 4] 50 int [1, 5] 50 int [1, 6] 50 int [1, 7] 50 int [1, 8] 50 int [1, 9] 50 int [1, 10] 50 int [1, 11] 50 int [1, 12] 50 int [1, 13] 50 int [1, 14] 50 int [1, 15] 50 int [1, 16] 50 int [1, 17] 50 int [1, 18] 50 int [1, 19] 50 int [1, 20] 50 int [1, 21] 50 int [1, 22] 50 int [1, 23] 50 int [1, 24] 50 int [2, 0] 51 int [2, 1] 51 int [2, 2] 51 int [2, 3] 51 int [2, 4] 51 int [2, 5] 51 int [2, 6] 51 int [2, 7] 51 int [2, 8] 51 int [2, 9] 51 int [2, 10] 51 int [2, 11] 51 int [2, 12] 51 int [2, 13] 51 int [2, 14] 51 int [2, 15] 51 int [2, 16] 51 int [2, 17] 51 int [2, 18] 51 int [2, 19] 51 int [2, 20] 51 int [2, 21] 51 int [2, 22] 51 int [2, 23] 51 int [2, 24] 51 int [3, 0] 52 int [3, 1] 52 int [3, 2] 52 int [3, 3] 52 int [3, 4] 52 int [3, 5] 52 int [3, 6] 52 int [3, 7] 52 int [3, 8] 52 int [3, 9] 52 int [3, 10] 52 int [3, 11] 52 int [3, 12] 52 int [3, 13] 52 int [3, 14] 52 int [3, 15] 52 int [3, 16] 52 int [3, 17] 52 int [3, 18] 52 int [3, 19] 52 int [3, 20] 52 int [3, 21] 52 int [3, 22] 52 int [3, 23] 52 int [3, 24] 52 int [4, 0] 53 int [4, 1] 53 int [4, 2] 53 int [4, 3] 53 int [4, 4] 53 int [4, 5] 53 int [4, 6] 53 int [4, 7] 53 int [4, 8] 53 int [4, 9] 53 int [4, 10] 53 int [4, 11] 53 int [4, 12] 53 int [4, 13] 53 int [4, 14] 53 int [4, 15] 53 int [4, 16] 53 int [4, 17] 53 int [4, 18] 53 int [4, 19] 53 int [4, 20] 53 int [4, 21] 53 int [4, 22] 53 int [4, 23] 53 int [4, 24] 53 int [5, 0] 54 int [5, 1] 54 int [5, 2] 54 int [5, 3] 54 int [5, 4] 54 int [5, 5] 54 int [5, 6] 54 int [5, 7] 54 int [5, 8] 54 int [5, 9] 54 int [5, 10] 54 int [5, 11] 54 int [5, 12] 54 int [5, 13] 54 int [5, 14] 54 int [5, 15] 54 int [5, 16] 54 int [5, 17] 54 int [5, 18] 54 int [5, 19] 54 int [5, 20] 54 int [5, 21] 54 int [5, 22] 54 int [5, 23] 54 int [5, 24] 54 int [6, 0] 55 int [6, 1] 55 int [6, 2] 55 int [6, 3] 55 int [6, 4] 55 int [6, 5] 55 int [6, 6] 55 int [6, 7] 55 int [6, 8] 55 int [6, 9] 55 int [6, 10] 55 int [6, 11] 55 int [6, 12] 55 int [6, 13] 55 int [6, 14] 55 int [6, 15] 55 int [6, 16] 55 int [6, 17] 55 int [6, 18] 55 int [6, 19] 55 int [6, 20] 55 int [6, 21] 55 int [6, 22] 55 int [6, 23] 55 int [6, 24] 55 int [7, 0] 56 int [7, 1] 56 int [7, 2] 56 int [7, 3] 56 int [7, 4] 56 int [7, 5] 56 int [7, 6] 56 int [7, 7] 56 int [7, 8] 56 int [7, 9] 56 int [7, 10] 56 int [7, 11] 56 int [7, 12] 56 int [7, 13] 56 int [7, 14] 56 int [7, 15] 56 int [7, 16] 56 int [7, 17] 56 int [7, 18] 56 int [7, 19] 56 int [7, 20] 56 int [7, 21] 56 int [7, 22] 56 int [7, 23] 56 int [7, 24] 56 int [8, 0] 57 int [8, 1] 57 int [8, 2] 57 int [8, 3] 57 int [8, 4] 57 int [8, 5] 57 int [8, 6] 57 int [8, 7] 57 int [8, 8] 57 int [8, 9] 57 int [8, 10] 57 int [8, 11] 57 int [8, 12] 57 int [8, 13] 57 int [8, 14] 57 int [8, 15] 57 int [8, 16] 57 int [8, 17] 57 int [8, 18] 57 int [8, 19] 57 int [8, 20] 57 int [8, 21] 57 int [8, 22] 57 int [8, 23] 57 int [8, 24] 57 int [9, 0] 48 int [9, 1] 48 int [9, 2] 48 int [9, 3] 48 int [9, 4] 48 int [9, 5] 48 int [9, 6] 48 int [9, 7] 48 int [9, 8] 48 int [9, 9] 48 int [9, 10] 48 int [9, 11] 48 int [9, 12] 48 int [9, 13] 48 int [9, 14] 48 int [9, 15] 48 int [9, 16] 48 int [9, 17] 48 int [9, 18] 48 int [9, 19] 48 int [9, 20] 48 int [9, 21] 48 int [9, 22] 48 int [9, 23] 48 int [9, 24] 48 int [10, 0] 48 int [10, 1] 48 int [10, 2] 48 int [10, 3] 48 int [10, 4] 48 int [10, 5] 48 int [10, 6] 48 int [10, 7] 48 int [10, 8] 48 int [10, 9] 48 int [10, 10] 48 int [10, 11] 48 int [10, 12] 48 int [10, 13] 48 int [10, 14] 48 int [10, 15] 48 int [10, 16] 48 int [10, 17] 48 int [10, 18] 48 int [10, 19] 48 int [10, 20] 48 int [10, 21] 48 int [10, 22] 48 int [10, 23] 48 int [10, 24] 48 int [11, 0] 48 int [11, 1] 48 int [11, 2] 48 int [11, 3] 48 int [11, 4] 48 int [11, 5] 48 int [11, 6] 48 int [11, 7] 48 int [11, 8] 48 int [11, 9] 48 int [11, 10] 48 int [11, 11] 48 int [11, 12] 48 int [11, 13] 48 int [11, 14] 48 int [11, 15] 48 int [11, 16] 48 int [11, 17] 48 int [11, 18] 48 int [11, 19] 48 int [11, 20] 48 int [11, 21] 48 int [11, 22] 48 int [11, 23] 48 int [11, 24] 48 int [12, 0] 48 int [12, 1] 48 int [12, 2] 48 int [12, 3] 48 int [12, 4] 48 int [12, 5] 48 int [12, 6] 48 int [12, 7] 48 int [12, 8] 48 int [12, 9] 48 int [12, 10] 48 int [12, 11] 48 int [12, 12] 48 int [12, 13] 48 int [12, 14] 48 int [12, 15] 48 int [12, 16] 48 int [12, 17] 48 int [12, 18] 48 int [12, 19] 48 int [12, 20] 48 int [12, 21] 48 int [12, 22] 48 int [12, 23] 48 int [12, 24] 48 int [13, 0] 48 int [13, 1] 48 int [13, 2] 48 int [13, 3] 48 int [13, 4] 48 int [13, 5] 48 int [13, 6] 48 int [13, 7] 48 int [13, 8] 48 int [13, 9] 48 int [13, 10] 48 int [13, 11] 48 int [13, 12] 48 int [13, 13] 48 int [13, 14] 48 int [13, 15] 48 int [13, 16] 48 int [13, 17] 48 int [13, 18] 48 int [13, 19] 48 int [13, 20] 48 int [13, 21] 48 int [13, 22] 48 int [13, 23] 48 int [13, 24] 48 int Sorry for the lame formatting, but it's huge :P I have no idea where it's getting these values from, does anyone have an explanation? Thanks :)

    Read the article

  • ld: symbol(s) not found with OpenSSL (libssl)

    - by Benjamin
    Hi all, I'm trying to build TorTunnel on my mac. I've successfully installed the Boost library and its development files. TorTunnel also requires the OpenSSL and its development files. I've got them installed in /usr/lib/libssl.dylib and /usr/include/openssl/. When I run the make command this is the error i'm getting: g++ -ggdb -g -O2 -lssl -lboost_system-xgcc42-mt-1_38 -o torproxy TorProxy.o HybridEncryption.o Connection.o Cell.o Directory.o ServerListing.o Util.o Circuit.o CellEncrypter.o RelayCellDispatcher.o CellConsumer.o ProxyShuffler.o CreateCell.o CreatedCell.o TorTunnel.o SocksConnection.o Network.o Undefined symbols: "_BN_hex2bn", referenced from: Circuit::initializeDhParameters() in Circuit.o "_BN_free", referenced from: Circuit::~Circuit()in Circuit.o Circuit::~Circuit()in Circuit.o CreatedCell::getKeyMaterial(unsigned char**, unsigned char**)in CreatedCell.o "_DH_generate_key", referenced from: Circuit::initializeDhParameters() in Circuit.o "_PEM_read_bio_RSAPublicKey", referenced from: ServerListing::getOnionKey() in ServerListing.o "_BIO_s_mem", referenced from: Connection::initializeSSL() in Connection.o Connection::initializeSSL() in Connection.o "_DH_free", referenced from: Circuit::~Circuit()in Circuit.o "_BIO_ctrl_pending", referenced from: Connection::writeFromBuffer(boost::function)in Connection.o "_RSA_size", referenced from: HybridEncryption::encryptInSingleChunk(unsigned char*, int, unsigned char**, int*, rsa_st*)in HybridEncryption.o HybridEncryption::encryptInHybridChunk(unsigned char*, int, unsigned char**, int*, rsa_st*)in HybridEncryption.o HybridEncryption::encrypt(unsigned char*, int, unsigned char**, int*, rsa_st*)in HybridEncryption.o "_RSA_public_encrypt", referenced from: HybridEncryption::encryptInSingleChunk(unsigned char*, int, unsigned char**, int*, rsa_st*)in HybridEncryption.o HybridEncryption::encryptInHybridChunk(unsigned char*, int, unsigned char**, int*, rsa_st*)in HybridEncryption.o "_BN_num_bits", referenced from: CreateCell::CreateCell(unsigned short, dh_st*, rsa_st*)in CreateCell.o CreatedCell::getKeyMaterial(unsigned char**, unsigned char**)in CreatedCell.o CreatedCell::getKeyMaterial(unsigned char**, unsigned char**)in CreatedCell.o CreatedCell::isValid() in CreatedCell.o "_SHA1", referenced from: CellEncrypter::expandKeyMaterial(unsigned char*, int, unsigned char*, int)in CellEncrypter.o "_BN_bn2bin", referenced from: CreateCell::CreateCell(unsigned short, dh_st*, rsa_st*)in CreateCell.o "_BN_bin2bn", referenced from: CreatedCell::getKeyMaterial(unsigned char**, unsigned char**)in CreatedCell.o "_DH_compute_key", referenced from: CreatedCell::getKeyMaterial(unsigned char**, unsigned char**)in CreatedCell.o "_BIO_new", referenced from: Connection::initializeSSL() in Connection.o Connection::initializeSSL() in Connection.o "_BIO_new_mem_buf", referenced from: ServerListing::getOnionKey() in ServerListing.o "_AES_ctr128_encrypt", referenced from: HybridEncryption::AES_encrypt(unsigned char*, int, unsigned char*, unsigned char*, int)in HybridEncryption.o CellEncrypter::aesOperate(Cell&, aes_key_st*, unsigned char*, unsigned char*, unsigned int*)in CellEncrypter.o "_BIO_read", referenced from: Connection::writeFromBuffer(boost::function)in Connection.o "_SHA1_Update", referenced from: CellEncrypter::calculateDigest(SHAstate_st*, RelayCell&, unsigned char*)in CellEncrypter.o CellEncrypter::initKeyMaterial(unsigned char*)in CellEncrypter.o CellEncrypter::initKeyMaterial(unsigned char*)in CellEncrypter.o "_SHA1_Final", referenced from: CellEncrypter::calculateDigest(SHAstate_st*, RelayCell&, unsigned char*)in CellEncrypter.o "_DH_size", referenced from: CreatedCell::getKeyMaterial(unsigned char**, unsigned char**)in CreatedCell.o "_DH_new", referenced from: Circuit::initializeDhParameters() in Circuit.o "_BIO_write", referenced from: Connection::readIntoBufferComplete(boost::function, boost::system::error_code const&, unsigned long)in Connection.o "_RSA_free", referenced from: Circuit::~Circuit()in Circuit.o "_BN_dup", referenced from: Circuit::initializeDhParameters() in Circuit.o Circuit::initializeDhParameters() in Circuit.o "_BN_new", referenced from: Circuit::initializeDhParameters() in Circuit.o Circuit::initializeDhParameters() in Circuit.o "_SHA1_Init", referenced from: CellEncrypter::CellEncrypter()in CellEncrypter.o CellEncrypter::CellEncrypter()in CellEncrypter.o "_RAND_bytes", referenced from: HybridEncryption::encryptInHybridChunk(unsigned char*, int, unsigned char**, int*, rsa_st*)in HybridEncryption.o Util::getRandomId() in Util.o "_AES_set_encrypt_key", referenced from: HybridEncryption::AES_encrypt(unsigned char*, int, unsigned char*, unsigned char*, int)in HybridEncryption.o CellEncrypter::initKeyMaterial(unsigned char*)in CellEncrypter.o CellEncrypter::initKeyMaterial(unsigned char*)in CellEncrypter.o "_BN_set_word", referenced from: Circuit::initializeDhParameters() in Circuit.o "_RSA_new", referenced from: ServerListing::getOnionKey() in ServerListing.o ld: symbol(s) not found collect2: ld returned 1 exit status make: *** [torproxy] Error 1 Any idea how I could fix it?

    Read the article

  • Understanding C# async / await (1) Compilation

    - by Dixin
    Now the async / await keywords are in C#. Just like the async and ! in F#, this new C# feature provides great convenience. There are many nice documents talking about how to use async / await in specific scenarios, like using async methods in ASP.NET 4.5 and in ASP.NET MVC 4, etc. In this article we will look at the real code working behind the syntax sugar. According to MSDN: The async modifier indicates that the method, lambda expression, or anonymous method that it modifies is asynchronous. Since lambda expression / anonymous method will be compiled to normal method, we will focus on normal async method. Preparation First of all, Some helper methods need to make up. internal class HelperMethods { internal static int Method(int arg0, int arg1) { // Do some IO. WebClient client = new WebClient(); Enumerable.Repeat("http://weblogs.asp.net/dixin", 10) .Select(client.DownloadString).ToArray(); int result = arg0 + arg1; return result; } internal static Task<int> MethodTask(int arg0, int arg1) { Task<int> task = new Task<int>(() => Method(arg0, arg1)); task.Start(); // Hot task (started task) should always be returned. return task; } internal static void Before() { } internal static void Continuation1(int arg) { } internal static void Continuation2(int arg) { } } Here Method() is a long running method doing some IO. Then MethodTask() wraps it into a Task and return that Task. Nothing special here. Await something in async method Since MethodTask() returns Task, let’s try to await it: internal class AsyncMethods { internal static async Task<int> MethodAsync(int arg0, int arg1) { int result = await HelperMethods.MethodTask(arg0, arg1); return result; } } Because we used await in the method, async must be put on the method. Now we get the first async method. According to the naming convenience, it is called MethodAsync. Of course a async method can be awaited. So we have a CallMethodAsync() to call MethodAsync(): internal class AsyncMethods { internal static async Task<int> CallMethodAsync(int arg0, int arg1) { int result = await MethodAsync(arg0, arg1); return result; } } After compilation, MethodAsync() and CallMethodAsync() becomes the same logic. This is the code of MethodAsyc(): internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MethodAsync(int arg0, int arg1) { MethodAsyncStateMachine methodAsyncStateMachine = new MethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; methodAsyncStateMachine.Builder.Start(ref methodAsyncStateMachine); return methodAsyncStateMachine.Builder.Task; } } It just creates and starts a state machine MethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Result; private TaskAwaiter<int> awaitor; void IAsyncStateMachine.MoveNext() { try { if (this.State != 0) { this.awaitor = HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaitor.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaitor, ref this); return; } } else { this.State = -1; } this.Result = this.awaitor.GetResult(); } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); return; } this.State = -2; this.Builder.SetResult(this.Result); } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0) { this.Builder.SetStateMachine(param0); } } The generated code has been cleaned up so it is readable and can be compiled. Several things can be observed here: The async modifier is gone, which shows, unlike other modifiers (e.g. static), there is no such IL/CLR level “async” stuff. It becomes a AsyncStateMachineAttribute. This is similar to the compilation of extension method. The generated state machine is very similar to the state machine of C# yield syntax sugar. The local variables (arg0, arg1, result) are compiled to fields of the state machine. The real code (await HelperMethods.MethodTask(arg0, arg1)) is compiled into MoveNext(): HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(). CallMethodAsync() will create and start its own state machine CallMethodAsyncStateMachine: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(CallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> CallMethodAsync(int arg0, int arg1) { CallMethodAsyncStateMachine callMethodAsyncStateMachine = new CallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; callMethodAsyncStateMachine.Builder.Start(ref callMethodAsyncStateMachine); return callMethodAsyncStateMachine.Builder.Task; } } CallMethodAsyncStateMachine has the same logic as MethodAsyncStateMachine above. The detail of the state machine will be discussed soon. Now it is clear that: async /await is a C# level syntax sugar. There is no difference to await a async method or a normal method. A method returning Task will be awaitable. State machine and continuation To demonstrate more details in the state machine, a more complex method is created: internal class AsyncMethods { internal static async Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; } } In this method: There are multiple awaits. There are code before the awaits, and continuation code after each await After compilation, this multi-await method becomes the same as above single-await methods: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; multiCallMethodAsyncStateMachine.Builder.Start(ref multiCallMethodAsyncStateMachine); return multiCallMethodAsyncStateMachine.Builder.Task; } } It creates and starts one single state machine, MultiCallMethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Arg2; public int Arg3; public int ResultOfAwait1; public int ResultOfAwait2; public int ResultToReturn; private TaskAwaiter<int> awaiter; void IAsyncStateMachine.MoveNext() { try { switch (this.State) { case -1: HelperMethods.Before(); this.awaiter = AsyncMethods.MethodAsync(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 0: this.ResultOfAwait1 = this.awaiter.GetResult(); HelperMethods.Continuation1(this.ResultOfAwait1); this.awaiter = AsyncMethods.MethodAsync(this.Arg2, this.Arg3).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 1; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 1: this.ResultOfAwait2 = this.awaiter.GetResult(); HelperMethods.Continuation2(this.ResultOfAwait2); this.ResultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; this.State = -2; this.Builder.SetResult(this.ResultToReturn); break; } } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); } } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { this.Builder.SetStateMachine(stateMachine); } } The above code is already cleaned up, but there are still a lot of things. More clean up can be done, and the state machine can be very simple: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { // State: // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End public int State; public TaskCompletionSource<int> ResultToReturn; // int resultToReturn ... public int Arg0; // int Arg0 public int Arg1; // int arg1 public int Arg2; // int arg2 public int Arg3; // int arg3 public int ResultOfAwait1; // int resultOfAwait1 ... public int ResultOfAwait2; // int resultOfAwait2 ... private Task<int> currentTaskToAwait; /// <summary> /// Moves the state machine to its next state. /// </summary> void IAsyncStateMachine.MoveNext() { try { switch (this.State) { // Orginal code is splitted by "case"s: // case -1: // HelperMethods.Before(); // MethodAsync(Arg0, arg1); // case 0: // int resultOfAwait1 = await ... // HelperMethods.Continuation1(resultOfAwait1); // MethodAsync(arg2, arg3); // case 1: // int resultOfAwait2 = await ... // HelperMethods.Continuation2(resultOfAwait2); // int resultToReturn = resultOfAwait1 + resultOfAwait2; // return resultToReturn; case -1: // -1 is begin. HelperMethods.Before(); // Code before 1st await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg0, this.Arg1); // 1st task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 0. this.State = 0; IAsyncStateMachine this1 = this; // Cannot use "this" in lambda so create a local variable. this.currentTaskToAwait.ContinueWith(_ => this1.MoveNext()); // Callback break; case 0: // Now 1st await is done. this.ResultOfAwait1 = this.currentTaskToAwait.Result; // Get 1st await's result. HelperMethods.Continuation1(this.ResultOfAwait1); // Code after 1st await and before 2nd await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg2, this.Arg3); // 2nd task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 1. this.State = 1; IAsyncStateMachine this2 = this; // Cannot use "this" in lambda so create a local variable. this.currentTaskToAwait.ContinueWith(_ => this2.MoveNext()); // Callback break; case 1: // Now 2nd await is done. this.ResultOfAwait2 = this.currentTaskToAwait.Result; // Get 2nd await's result. HelperMethods.Continuation2(this.ResultOfAwait2); // Code after 2nd await. int resultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; // Code after 2nd await. // End with resultToReturn. this.State = -2; // -2 is end. this.ResultToReturn.SetResult(resultToReturn); break; } } catch (Exception exception) { // End with exception. this.State = -2; // -2 is end. this.ResultToReturn.SetException(exception); } } /// <summary> /// Configures the state machine with a heap-allocated replica. /// </summary> /// <param name="stateMachine">The heap-allocated replica.</param> [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { // No core logic. } } Only Task and TaskCompletionSource are involved in this version. And MultiCallMethodAsync() can be simplified to: [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync_(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, ResultToReturn = new TaskCompletionSource<int>(), // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End State = -1 }; (multiCallMethodAsyncStateMachine as IAsyncStateMachine).MoveNext(); // Original code are in this method. return multiCallMethodAsyncStateMachine.ResultToReturn.Task; } Now the whole state machine becomes very clear - it is about callback: Original code are split into pieces by “await”s, and each piece is put into each “case” in the state machine. Here the 2 awaits split the code into 3 pieces, so there are 3 “case”s. The “piece”s are chained by callback, that is done by Builder.AwaitUnsafeOnCompleted(callback), or currentTaskToAwait.ContinueWith(callback) in the simplified code. A previous “piece” will end with a Task (which is to be awaited), when the task is done, it will callback the next “piece”. The state machine’s state works with the “case”s to ensure the code “piece”s executes one after another. Callback Since it is about callback, the simplification  can go even further – the entire state machine can be completely purged. Now MultiCallMethodAsync() becomes: internal static Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(); try { // Oringinal code begins. HelperMethods.Before(); MethodAsync(arg0, arg1).ContinueWith(await1 => { int resultOfAwait1 = await1.Result; HelperMethods.Continuation1(resultOfAwait1); MethodAsync(arg2, arg3).ContinueWith(await2 => { int resultOfAwait2 = await2.Result; HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; // Oringinal code ends. taskCompletionSource.SetResult(resultToReturn); }); }); } catch (Exception exception) { taskCompletionSource.SetException(exception); } return taskCompletionSource.Task; } Please compare with the original async / await code: HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; Yeah that is the magic of C# async / await: Await is literally pretending to wait. In a await expression, a Task object will be return immediately so that caller is not blocked. The continuation code is compiled as that Task’s callback code. When that task is done, continuation code will execute. Please notice that many details inside the state machine are omitted for simplicity, like context caring, etc. If you want to have a detailed picture, please do check out the source code of AsyncTaskMethodBuilder and TaskAwaiter.

    Read the article

  • Understanding C# async / await (1) Compilation

    - by Dixin
    Now the async / await keywords are in C#. Just like the async and ! in F#, this new C# feature provides great convenience. There are many nice documents talking about how to use async / await in specific scenarios, like using async methods in ASP.NET 4.5 and in ASP.NET MVC 4, etc. In this article we will look at the real code working behind the syntax sugar. According to MSDN: The async modifier indicates that the method, lambda expression, or anonymous method that it modifies is asynchronous. Since lambda expression / anonymous method will be compiled to normal method, we will focus on normal async method. Preparation First of all, Some helper methods need to make up. internal class HelperMethods { internal static int Method(int arg0, int arg1) { // Do some IO. WebClient client = new WebClient(); Enumerable.Repeat("http://weblogs.asp.net/dixin", 10) .Select(client.DownloadString).ToArray(); int result = arg0 + arg1; return result; } internal static Task<int> MethodTask(int arg0, int arg1) { Task<int> task = new Task<int>(() => Method(arg0, arg1)); task.Start(); // Hot task (started task) should always be returned. return task; } internal static void Before() { } internal static void Continuation1(int arg) { } internal static void Continuation2(int arg) { } } Here Method() is a long running method doing some IO. Then MethodTask() wraps it into a Task and return that Task. Nothing special here. Await something in async method Since MethodTask() returns Task, let’s try to await it: internal class AsyncMethods { internal static async Task<int> MethodAsync(int arg0, int arg1) { int result = await HelperMethods.MethodTask(arg0, arg1); return result; } } Because we used await in the method, async must be put on the method. Now we get the first async method. According to the naming convenience, it is named MethodAsync. Of course a async method can be awaited. So we have a CallMethodAsync() to call MethodAsync(): internal class AsyncMethods { internal static async Task<int> CallMethodAsync(int arg0, int arg1) { int result = await MethodAsync(arg0, arg1); return result; } } After compilation, MethodAsync() and CallMethodAsync() becomes the same logic. This is the code of MethodAsyc(): internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MethodAsync(int arg0, int arg1) { MethodAsyncStateMachine methodAsyncStateMachine = new MethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; methodAsyncStateMachine.Builder.Start(ref methodAsyncStateMachine); return methodAsyncStateMachine.Builder.Task; } } It just creates and starts a state machine, MethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Result; private TaskAwaiter<int> awaitor; void IAsyncStateMachine.MoveNext() { try { if (this.State != 0) { this.awaitor = HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaitor.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaitor, ref this); return; } } else { this.State = -1; } this.Result = this.awaitor.GetResult(); } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); return; } this.State = -2; this.Builder.SetResult(this.Result); } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0) { this.Builder.SetStateMachine(param0); } } The generated code has been refactored, so it is readable and can be compiled. Several things can be observed here: The async modifier is gone, which shows, unlike other modifiers (e.g. static), there is no such IL/CLR level “async” stuff. It becomes a AsyncStateMachineAttribute. This is similar to the compilation of extension method. The generated state machine is very similar to the state machine of C# yield syntax sugar. The local variables (arg0, arg1, result) are compiled to fields of the state machine. The real code (await HelperMethods.MethodTask(arg0, arg1)) is compiled into MoveNext(): HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(). CallMethodAsync() will create and start its own state machine CallMethodAsyncStateMachine: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(CallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> CallMethodAsync(int arg0, int arg1) { CallMethodAsyncStateMachine callMethodAsyncStateMachine = new CallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; callMethodAsyncStateMachine.Builder.Start(ref callMethodAsyncStateMachine); return callMethodAsyncStateMachine.Builder.Task; } } CallMethodAsyncStateMachine has the same logic as MethodAsyncStateMachine above. The detail of the state machine will be discussed soon. Now it is clear that: async /await is a C# language level syntax sugar. There is no difference to await a async method or a normal method. As long as a method returns Task, it is awaitable. State machine and continuation To demonstrate more details in the state machine, a more complex method is created: internal class AsyncMethods { internal static async Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; } } In this method: There are multiple awaits. There are code before the awaits, and continuation code after each await After compilation, this multi-await method becomes the same as above single-await methods: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; multiCallMethodAsyncStateMachine.Builder.Start(ref multiCallMethodAsyncStateMachine); return multiCallMethodAsyncStateMachine.Builder.Task; } } It creates and starts one single state machine, MultiCallMethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Arg2; public int Arg3; public int ResultOfAwait1; public int ResultOfAwait2; public int ResultToReturn; private TaskAwaiter<int> awaiter; void IAsyncStateMachine.MoveNext() { try { switch (this.State) { case -1: HelperMethods.Before(); this.awaiter = AsyncMethods.MethodAsync(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 0: this.ResultOfAwait1 = this.awaiter.GetResult(); HelperMethods.Continuation1(this.ResultOfAwait1); this.awaiter = AsyncMethods.MethodAsync(this.Arg2, this.Arg3).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 1; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 1: this.ResultOfAwait2 = this.awaiter.GetResult(); HelperMethods.Continuation2(this.ResultOfAwait2); this.ResultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; this.State = -2; this.Builder.SetResult(this.ResultToReturn); break; } } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); } } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { this.Builder.SetStateMachine(stateMachine); } } Once again, the above state machine code is already refactored, but it still has a lot of things. More clean up can be done if we only keep the core logic, and the state machine can become very simple: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { // State: // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End public int State; public TaskCompletionSource<int> ResultToReturn; // int resultToReturn ... public int Arg0; // int Arg0 public int Arg1; // int arg1 public int Arg2; // int arg2 public int Arg3; // int arg3 public int ResultOfAwait1; // int resultOfAwait1 ... public int ResultOfAwait2; // int resultOfAwait2 ... private Task<int> currentTaskToAwait; /// <summary> /// Moves the state machine to its next state. /// </summary> public void MoveNext() // IAsyncStateMachine member. { try { switch (this.State) { // Original code is split by "await"s into "case"s: // case -1: // HelperMethods.Before(); // MethodAsync(Arg0, arg1); // case 0: // int resultOfAwait1 = await ... // HelperMethods.Continuation1(resultOfAwait1); // MethodAsync(arg2, arg3); // case 1: // int resultOfAwait2 = await ... // HelperMethods.Continuation2(resultOfAwait2); // int resultToReturn = resultOfAwait1 + resultOfAwait2; // return resultToReturn; case -1: // -1 is begin. HelperMethods.Before(); // Code before 1st await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg0, this.Arg1); // 1st task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 0. this.State = 0; MultiCallMethodAsyncStateMachine that1 = this; // Cannot use "this" in lambda so create a local variable. this.currentTaskToAwait.ContinueWith(_ => that1.MoveNext()); break; case 0: // Now 1st await is done. this.ResultOfAwait1 = this.currentTaskToAwait.Result; // Get 1st await's result. HelperMethods.Continuation1(this.ResultOfAwait1); // Code after 1st await and before 2nd await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg2, this.Arg3); // 2nd task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 1. this.State = 1; MultiCallMethodAsyncStateMachine that2 = this; this.currentTaskToAwait.ContinueWith(_ => that2.MoveNext()); break; case 1: // Now 2nd await is done. this.ResultOfAwait2 = this.currentTaskToAwait.Result; // Get 2nd await's result. HelperMethods.Continuation2(this.ResultOfAwait2); // Code after 2nd await. int resultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; // Code after 2nd await. // End with resultToReturn. this.State = -2; // -2 is end. this.ResultToReturn.SetResult(resultToReturn); break; } } catch (Exception exception) { // End with exception. this.State = -2; // -2 is end. this.ResultToReturn.SetException(exception); } } /// <summary> /// Configures the state machine with a heap-allocated replica. /// </summary> /// <param name="stateMachine">The heap-allocated replica.</param> [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) // IAsyncStateMachine member. { // No core logic. } } Only Task and TaskCompletionSource are involved in this version. And MultiCallMethodAsync() can be simplified to: [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, ResultToReturn = new TaskCompletionSource<int>(), // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End State = -1 }; multiCallMethodAsyncStateMachine.MoveNext(); // Original code are moved into this method. return multiCallMethodAsyncStateMachine.ResultToReturn.Task; } Now the whole state machine becomes very clean - it is about callback: Original code are split into pieces by “await”s, and each piece is put into each “case” in the state machine. Here the 2 awaits split the code into 3 pieces, so there are 3 “case”s. The “piece”s are chained by callback, that is done by Builder.AwaitUnsafeOnCompleted(callback), or currentTaskToAwait.ContinueWith(callback) in the simplified code. A previous “piece” will end with a Task (which is to be awaited), when the task is done, it will callback the next “piece”. The state machine’s state works with the “case”s to ensure the code “piece”s executes one after another. Callback If we focus on the point of callback, the simplification  can go even further – the entire state machine can be completely purged, and we can just keep the code inside MoveNext(). Now MultiCallMethodAsync() becomes: internal static Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(); try { // Oringinal code begins. HelperMethods.Before(); MethodAsync(arg0, arg1).ContinueWith(await1 => { int resultOfAwait1 = await1.Result; HelperMethods.Continuation1(resultOfAwait1); MethodAsync(arg2, arg3).ContinueWith(await2 => { int resultOfAwait2 = await2.Result; HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; // Oringinal code ends. taskCompletionSource.SetResult(resultToReturn); }); }); } catch (Exception exception) { taskCompletionSource.SetException(exception); } return taskCompletionSource.Task; } Please compare with the original async / await code: HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; Yeah that is the magic of C# async / await: Await is not to wait. In a await expression, a Task object will be return immediately so that execution is not blocked. The continuation code is compiled as that Task’s callback code. When that task is done, continuation code will execute. Please notice that many details inside the state machine are omitted for simplicity, like context caring, etc. If you want to have a detailed picture, please do check out the source code of AsyncTaskMethodBuilder and TaskAwaiter.

    Read the article

  • Ivar definitions show 'long' type encoding as 'long long' type encoding

    - by Frank C.
    I've found what I think may be a bug with Ivar and Objective-C runtime. I'm using XCode 3.2.1 and associated libraries, developing a 64 bit app on X86_64 (MacBook Pro). Where I would expect the type encoding for the following "longVal" to be 'l', the Ivar encoding is showing a 'q' (which is a 'long long'). Anyone else seeing this? Simplified code and output follows: Code: #import <Foundation/Foundation.h> #import <objc/runtime.h> @interface Bug : NSObject { long longVal; long long longerVal; } @property (nonatomic,assign) long longVal; @property (nonatomic,assign) long long longerVal; @end @implementation Bug @synthesize longVal,longerVal; @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; unsigned int ivarCount=0; Ivar *ivars= class_copyIvarList([Bug class], &ivarCount); for(unsigned int x=0;x<ivarCount;x++) { NSLog(@"Name [%@] encoding [%@]", [NSString stringWithCString:ivar_getName(ivars[x]) encoding:NSUTF8StringEncoding], [NSString stringWithCString:ivar_getTypeEncoding(ivars[x]) encoding:NSUTF8StringEncoding]); } [pool drain]; return 0; } And here is output from debug console: This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000 Loading program into debugger… sharedlibrary apply-load-rules all Program loaded. run [Switching to process 6048] Running… 2010-03-17 22:16:29.138 ivarbug[6048:a0f] Name [longVal] encoding [q] 2010-03-17 22:16:29.146 ivarbug[6048:a0f] Name [longerVal] encoding [q] (gdb) continue Not a pretty picture! -- Frank

    Read the article

  • java converting int to short

    - by changed
    Hi I am calculating 16 bit checksum on my data which i need to send to server where it has to recalculate and match with the provided checksum. Checksum value that i am getting is in int but i have only 2 bytes for sending the value.So i am casting int to short while calling shortToBytes method. This works fine till checksum value is less than 32767 thereafter i am getting negative values. Thing is java does not have unsigned primitives, so i am not able to send values greater than max value of signed short allowed. How can i do this, converting int to short and send over the network without worrying about truncation and signed & unsigned int. Also on both the side i have java program running. private byte[] shortToBytes(short sh) { byte[] baValue = new byte[2]; ByteBuffer buf = ByteBuffer.wrap(baValue); return buf.putShort(sh).array(); } private short bytesToShort(byte[] buf, int offset) { byte[] baValue = new byte[2]; System.arraycopy(buf, offset, baValue, 0, 2); return ByteBuffer.wrap(baValue).getShort(); }

    Read the article

  • Initialization of std::vector<unsigned int> with a list of consecutive unsigned integers

    - by Thomas
    I want to use a special method to initialize a std::vector<unsigned int> which is described in a C++ book I use as a reference (the German book 'Der C++ Programmer' by Ulrich Breymann, in case that matters). In that book is a section on sequence types of the STL, referring in particular to list, vector and deque. In this section he writes that there are two special constructors of such sequence types, namely, if Xrefers to such a type, X(n, t) // creates a sequence with n copies of t X(i, j) // creates a sequence from the elements of the interval [i, j) I want to use the second one for an interval of unsigned int, that is std::vector<unsigned int> l(1U, 10U); to get a list initialized with {1,2,...,9}. What I get, however, is a vector with one unsigned int with value 10 :-| Does the second variant exist, and if yes, how do I force that it is called?

    Read the article

  • Should I redesign my code when collegues says so?

    - by Kirill V. Lyadvinsky
    I wrote a function recently that finds maximum of two ints. Here is a code: int get_max (int(*a)(int(*)(int(*)()),int(*)(int(*)(int**))), int(*b)(int(*) (int(*)()),int*,int(*)(int(*)()))){return (int)((((int(*)(int(*)(int(*)()),int( *)(int(*)())))a)> ((int(*)(int(*)(int(*)()),int(*)(int(*)())))b))?((int(*)( int(*)(int(*)()),int(*)(int(*)())))a):((int(*)(int(*)(int(*)()),int(*)(int(*)( ))))b));} int main() { int x = get_max( (int(*)(int(*)(int(*)()),int(*)(int(*)(int**)))) 500, (int(*)(int(*)(int(*)()),int*,int(*)(int(*)()))) 100 ); cout << x << endl; // prints 500 as expected return 0; } It works fine, but my collegue says that I shouldn't use C style casts. But I think that all that modern static_cast's and reinterpret_cast's will make my code too cumbersome. Who's right? Should I redesign my code using C++ style casts or original code is OK?

    Read the article

  • Invalid conversion from int to int

    - by FOXMULDERIZE
    #include <iostream> #include<fstream> using namespace std; void showvalues(int,int,int []); void showvalues2(int,int); void sumtotal(int,int); int main() { const int SIZE_A= 9; int arreglo[SIZE_A]; ifstream archivo_de_entrada; archivo_de_entrada.open("numeros.txt"); int count,suma,total,a,b,c,d,e,f; int total1=0; int total2=0; //lee/// for(count =0 ;count < SIZE_A;count++) archivo_de_entrada>>arreglo[count] ; archivo_de_entrada.close(); showvalues(0,3,9); HERE IS THE PROBLEM showvalues2(5,8); sumtotal(total1,total2); system("pause"); return 0; } void showvalues(int a,int b,int v) { //muestra//////////////////////// cout<< "los num son "; for(count = a ;count <= b;count++) total1 = total1 + arreglo[count]; cout <<total1<<" "; cout <<endl; } void showvalues2(int c,int d) { ////////////////////////////// cout<< "los num 2 son "; for(count =5 ;count <=8;count++) total2 = total2 + arreglo[count]; cout <<total2<<" "; cout <<endl; } void sumtotal(int e,int f) { ///////////////////////////////// cout<<"la suma de t1 y t2 es "; total= total1 + total2; cout<<total; cout <<endl; }

    Read the article

  • Is it possible to add -pedantic to GCC command line, yet have it not warn about 'long long'

    - by doublep
    I'm using mostly GCC to develop my library, but I'd like to ensure cross-compiler compatibility and especially standard conformance as much as possible. For this, I have add several -W... flags to command line. I'd also add -pedantic, but I have a problem with its warning about long long type. The latter is important for my library and is properly guarded with #if code, i.e. is not compiled on compilers that don't know it anyway. In short: can I have GCC in -pedantic mode warn about any extension except long long?

    Read the article

  • SQL SERVER – Storing 64-bit Unsigned Integer Value in Database

    - by Pinal Dave
    Here is a very interesting question I received in an email just another day. Some questions just are so good that it makes me wonder how come I have not faced it first hand. Anyway here is the question - “Pinal, I am migrating my database from MySQL to SQL Server and I have faced unique situation. I have been using Unsigned 64-bit integer in MySQL but when I try to migrate that column to SQL Server, I am facing an issue as there is no datatype which I find appropriate for my column. It is now too late to change the datatype and I need immediate solution. One chain of thought was to change the data type of the column from Unsigned 64-bit (BIGINT) to VARCHAR(n) but that will just change the data type for me such that I will face quite a lot of performance related issues in future. In SQL Server we also have the BIGINT data type but that is Signed 64-bit datatype. BIGINT datatype in SQL Server have range of -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807). However, my digit is much larger than this number. Is there anyway, I can store my big 64-bit Unsigned Integer without loosing much of the performance of by converting it to VARCHAR.” Very interesting question, for the sake of the argument, we can ask user that there should be no need of such a big number or if you are taking about identity column I really doubt that if your table will grow beyond this table. Here the real question which I found interesting was how to store 64-bit unsigned integer value in SQL Server without converting it to String data type. After thinking a bit, I found a fairly simple answer. I can use NUMERIC data type. I can use NUMERIC(20) datatype for 64-bit unsigned integer value, NUMERIC(10) datatype for 32-bit unsigned integer value and NUMERIC(5) datatype for 16-bit unsigned integer value. Numeric datatype supports 38 maximum of 38 precision. Now here is another thing to keep in mind. Using NUMERIC datatype will indeed accept the 64-bit unsigned integer but in future if you try to enter negative value, it will also allow the same. Hence, you will need to put any additional constraint over column to only accept positive integer there. Here is another big concern, SQL Server will store the number as numeric and will treat that as a positive integer for all the practical purpose. You will have to write in your application logic to interpret that as a 64-bit Unsigned Integer. On another side if you are using unsigned integers in your application, there are good chance that you already have logic taking care of the same. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology Tagged: SQL Datatype

    Read the article

  • Get the signed/unsigned variant of an integer template parameter without explicit traits

    - by Blair Holloway
    I am looking to define a template class whose template parameter will always be an integer type. The class will contain two members, one of type T, and the other as the unsigned variant of type T -- i.e. if T == int, then T_Unsigned == unsigned int. My first instinct was to do this: template <typename T> class Range { typedef unsigned T T_Unsigned; // does not compile public: Range(T min, T_Unsigned range); private: T m_min; T_Unsigned m_range; }; But it doesn't work. I then thought about using partial template specialization, like so: template <typename T> struct UnsignedType {}; // deliberately empty template <> struct UnsignedType<int> { typedef unsigned int Type; }; template <typename T> class Range { typedef UnsignedType<T>::Type T_Unsigned; /* ... */ }; This works, so long as you partially specialize UnsignedType for every integer type. It's a little bit of additional copy-paste work (slash judicious use of macros), but serviceable. However, I'm now curious - is there another way of determining the signed-ness of an integer type, and/or using the unsigned variant of a type, without having to manually define a Traits class per-type? Or is this the only way to do it?

    Read the article

  • Need help implementing an Android service that does http long polling

    - by Erdal
    I've seen persistent TCP connections implemented (http://devtcg.blogspot.com/2009/01/push-services-implementing-persistent.html), but my needs are a little different. I need an Android service that always runs in the background and keeps a long polling connection to an HTTP server and communicates with it using JSON over POST method. Does anyone have anything similar to this?

    Read the article

  • Twice as long and half as long

    - by PointsToShare
    We are in a project and we hit some snags. What’s a snag? An activity that takes longer than expected. Actually it takes longer than the time assigned to it by an over pressed PM who accepts an impossible time table and tries his best to make it possible, but I digress (again!).  So we have snags and we also have the opposite. Let’s call these “cinches”. The question is: how does a combination of snags and cinches affect the project timeline? Well, there is no simple answer. It depends on the projects dependencies as we see in the PERT chart. If all the snags are in the critical path and all the cinches are elsewhere then the cinches don’t help at all. In fact any snag in the critical path will delay the project.  Conversely, a cinch in the critical path will expedite it. A snag outside the critical path might be serious enough to even change the critical path. Thus without the PERT chart, we cannot really tell. Still there is a principle involved – Time and speed are non-linear! Twice as long adds a full unit, half as long only takes ½ unit away. Let’s just investigate a simple project. It consists of two activities – S and C - each estimated to take a week. Alas, S is a snag and really needs twice the time allotted and – a sigh of relief – C is a cinch and will take half the time allotted, so everything is Hun-key-dory, or is it?  Even here the PERT chart is important. We have 2 cases: 1: S depends on C (or vice versa) as in when the two activities are assigned to one employee. Here the estimated time was 1 + 1 and the actual time was 2 + ½ and we are ½ week late or 25% late. 2: S and C are done in parallel. Here the estimated time was 1, but the actual time is 2 – we are a whole week or 100% late. Let’s change the equation a little. S need 1.5 and C needs .5 so in case 1, we have the loss fully compensated by the gain, but in case 2 we are still behind. There are cases where this really makes no difference. This is when the critical path is not affected and we have enough slack in the other paths to counteract the difference between its snags and cinches – Let’s call this difference DSC. So if the slack is greater than DSC the project will not suffer. Conclusion: There is no general rule about snags and cinches. We need to examine each case within its project, still as we saw in the 4 examples above; the snag is generally more powerful than the cinch. Long live Murphy! That’s All Folks

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >