Search Results

Search found 29841 results on 1194 pages for 'random number generator'.

Page 38/1194 | < Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >

  • Splitting a string with variable number of spaces VBA

    - by GVBA
    I have a file with a bunch of number in columns. These numbers are separated by variable number of spaces. I want to skip the first line and get all the other lines and separte each number on the line. Finally, I want to write each number on Excel. I've been able to get the lines and write them on Excel but I can't separate each number (I'm getting the whole line as one string). Does any body know how to split a string that has a variable number of spaces? Here is my code. Sub Test() r = 0 With New Scripting.FileSystemObject With .OpenTextFile("C:\Users\User\Desktop\File.tab", ForReading) If Not .AtEndOfStream Then .SkipLine Do Until .AtEndOfStream ActiveCell.Offset(r, 0) = Split(.ReadLine, vbCrLf) r = r + 1 Loop End With End With End Sub

    Read the article

  • How can I know whether my C++ string variable is a number or not

    - by user342580
    I have a string of class string string str; how can I check if it is a number or not, str can only have 3 possible types described below like abcd or a number like 123.4 or a number with a parenthesis attach to the end it for example 456) note the parenthesis at the end of "str" is the only possible combination of number and none number where the bottom two are considered valid numbers, I know I could use lexical_cast if only the first 2 cases occur, but how about considering all 3 possible cases to occur? I don't need to do anything fancy with str, I just need to know whether it is a valid number as I described

    Read the article

  • Select rows in random order and then reverse it

    - by Faruz
    I need to select rows in random order and return a query which holds the rows in both regular order and in reverse order. This is done to simulate a fantasy draft for a basketball game I'm working on. For example, I need a result set as followed: team1 1 team2 2 team6 3 team9 4 team9 5 team6 6 team2 7 team1 8 As you can see, the first four teams are random then then following four are in reverse order. Hope I managed to explain the problem, if not - please comment and I'll explain further.

    Read the article

  • batch - append either date/time of creation or random to end of filename

    - by Maclovin
    Hi Damsel in distress needing help with a batch-script. I have a bunch of files that one system creates. Either in one of 2 directories, or in the directory above that. The naming is apparently not very important, so It's a bit random. 2 questions for you batch-geniuses out there. a) How can I append date/time of creation to the end of the filename with a batch-script? b) How can I append a random filename (so I make the files unique) with a batch-script? Thanks in advance, dudes and dudettes. Yours sincerely, the Maclovin!

    Read the article

  • find number range in java

    - by Gandalf StormCrow
    How to get number range in java? for instance how can verify is the number 2389 within 10 numbers from 2400. its not but 2389 is. Ok here is the rephrase : Number 1000 is the range number 990 is comming in the loop, I return true because the between 990 and 1000 is 10 numbers diference. In comes the next number 989 range is always 1000, I return false because the between 989 and 1000 is 11 numbers diference. In comes the next number 1013 range is always 1000, I return false because the between 1013 and 1000 is 13 numbers diference.

    Read the article

  • Java print binary number using bit-wise operator

    - by user69514
    Hi I am creating a method that will take a number and print it along with its binary representation. The problems is that my method prints all 0's for any positive number, and all 1's for any negative number private static void display( int number ){ System.out.print(number + "\t"); int mask = 1 << 31; for(int i=1; i<=32; i++) { if( (mask & number) != 0 ) System.out.print(1); else System.out.print(0); if( (i % 4) == 0 ) System.out.print(" "); } }

    Read the article

  • php random image file name

    - by bush man
    Okay im using a snippet I found on google to take a users uploaded image and put it in my directory under Content But Im worried about duplicates so I was going have it upload the image as a Random number well here is my code you can probably understand what im going for through it anyways <label for="file">Profile Pic:</label> <input type="file" name="ProfilePic" id="ProfilePic" /><br /> <input type="submit" name="submit" value="Submit" /> $ProfilePicName = $_FILES["ProfilePic"]["name"]; $ProfilePicType = $_FILES["ProfilePic"]["type"]; $ProfilePicSize = $_FILES["ProfilePic"]["size"]; $ProfilePicTemp = $_FILES["ProfilePic"]["tmp_name"]; $ProfilePicError = $_FILES["ProfilePic"]["error"]; $RandomAccountNumber = mt_rand(1, 99999); echo $RandomAccountNumber; move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType); And then basicly after all this Im going try to get it to put that random number in my database

    Read the article

  • Create set of random JPGs

    - by Kylar
    Here's the scenario, I want to create a set of random, small jpg's - anywhere between 50 bytes and 8k in size - the actual visual content of the jpeg is irrelevant as long as they're valid. I need to generate a thousand or so, and they all have to be unique - even if they're only different by a single pixel. Can I just write a jpeg header/footer and some random bytes in there? I'm not able to use existing photos or sets of photos from the web. The second issue is that the set of images has to be different for each run of the program. I'd prefer to do this in python, as the wrapping scripts are in Python. I've looked for python code to generate jpg's from scratch, and didn't find anything, so pointers to libraries are just as good.

    Read the article

  • question about random select

    - by davit-datuashvili
    here is code print number in decreasing order import java.util.*; public class select { public static void Select(int m,int n){ Random r=new Random(); if (m>0) if (r.nextInt(0x3fff8001) % n <m ){ System.out.println(n-1); Select(m-1,n-1); } else{ Select(m,n-1); } } public static void main(String[]args){ int m=35; int n=200; Select(m,n); } } and question is how to changes code such that print number in increasing order? please help

    Read the article

  • Python: Random integer

    - by user3696440
    I been hitting a wall thats been keeping me from tinkering on a game. class Damage: def shortsword(): shortsword=randint(1,6)+1 shortsword=int(shortsword) return shortsword I been wanting this number to pop up as part of a message on print and then use the same number as part of another function to help with subtracting of health on the target. Though each time I grab this it is always going to change.

    Read the article

  • Generate unique hashes for django models

    - by becomingGuru
    I want to use unique hashes for each model rather than ids. I implemented the following function to use it across the board easily. import random,hashlib from base64 import urlsafe_b64encode def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False): while 1: uuid_number = str(random.random())[2:] uuid = hashlib.sha256(uuid_number).hexdigest() if use_sha else uuid_number uuid = uuid[:length] if urlencode: uuid = urlsafe_b64encode(uuid)[:-1] hash_id_dict = {field_name:uuid} try: model_object.__class__.objects.get(**hash_id_dict) except model_object.__class__.DoesNotExist: setattr(model_object,field_name,uuid) return I'm seeking feedback, how else could I do it? How can I improve it? What is good bad and ugly about it?

    Read the article

  • Unique Alpha numeric generator

    - by AAA
    Hi, I want to give our users in the database a unique alpha-numeric id. I am using the code below, will this always generate a unique id? Below is the updated version of the code: old php: // Generate Guid function NewGuid() { $s = strtoupper(md5(uniqid(rand(),true))); $guidText = substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4). '-' . substr($s,16,4). '-' . substr($s,20); return $guidText; } // End Generate Guid $Guid = NewGuid(); echo $Guid; echo "<br><br><br>"; New PHP: // Generate Guid function NewGuid() { $s = strtoupper(uniqid("something",true)); $guidText = substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4). '-' . substr($s,16,4). '-' . substr($s,20); return $guidText; } // End Generate Guid $Guid = NewGuid(); echo $Guid; echo "<br><br><br>"; Will the second (new php) code guarantee 100% uniqueness. Final code: PHP // Generate Guid function NewGuid() { $s = strtoupper(uniqid(rand(),true)); $guidText = substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4). '-' . substr($s,16,4). '-' . substr($s,20); return $guidText; } // End Generate Guid $Guid = NewGuid(); echo $Guid; $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; function base_encode($num, $alphabet) { $base_count = strlen($alphabet); $encoded = ''; while ($num >= $base_count) { $div = $num/$base_count; $mod = ($num-($base_count*intval($div))); $encoded = $alphabet[$mod] . $encoded; $num = intval($div); } if ($num) $encoded = $alphabet[$num] . $encoded; return $encoded; } function base_decode($num, $alphabet) { $decoded = 0; $multi = 1; while (strlen($num) > 0) { $digit = $num[strlen($num)-1]; $decoded += $multi * strpos($alphabet, $digit); $multi = $multi * strlen($alphabet); $num = substr($num, 0, -1); } return $decoded; } echo base_encode($Guid, $alphabet); } So for more stronger uniqueness, i am using the $Guid as the key generator. That should be ok right?

    Read the article

  • Randomly generate sound from onClick and onShake events?

    - by Aaron
    I've literally looked everywhere on the net and found very little clarification on how to do this. Pretty much, I have 8 sound files laid out in an array.xml file and I need to play a randomly chosen file ONCE per or onClick or onShake. First off, what technique should I use to achieve this? ARRAY-RANDOM- STRING-PLAY? RANDOM INT-PLAY? RANDOM INT-STRING-PLAY? Any kind of direction will help greatly cause I'm almost 3 weeks worth of research into this. *NOTE: MediaPlayer mp = MediaPlayer.create(JelloMan.this, R.raw.sound) ...is what I'm stuck on being you can't replace the "R.raw" part with a string...

    Read the article

  • reuse generators

    - by wiso
    I need to check the central limit with dices. Rool D dices. Sum the results. Repeat the same thing for N times. Change D and repeat. There's no need to store random values so I want to use only generators. The problem is that generators are consuming, I can't resuging them more times. Now my code use explicit for and I don't like it. dice_numbers = (1, 2, 10, 100, 1000) repetitions = 10000 for dice_number in dice_numbers: # how many dice to sum sum_container = [] for r in range(repetitions): rool_sum = sum((random.randint(1,6) for _ in range(dice_number))) sum_container.append(rool_sum) plot_histogram(sum_container) I want to create something like for r in repetitions: rools_generator = (random.randint(1,6) for _ in range(dice_number) sum_generator = (sum(rools_generator) for _ in range(r)) but the second time I resuse rools_generator it is condumed. I need to construct generator class?

    Read the article

  • Autocorrelation returns random results with mic input (using a high pass filter)

    - by Niall
    Hello, Sorry to ask a similar question to the one i asked before (FFT Problem (Returns random results)), but i've looked up pitch detection and autocorrelation and have found some code for pitch detection using autocorrelation. Im trying to do pitch detection of a users singing. Problem is, it keeps returning random results. I've got some code from http://code.google.com/p/yaalp/ which i've converted to C++ and modified (below). My sample rate is 2048, and data size is 1024. I'm detecting pitch of both a sine wave and mic input. The frequency of the sine wave is 726.0, and its detecting it to be 722.950820 (which im ok with), but its detecting the pitch of the mic as a random number from around 100 to around 1050. I'm now using a High pass filter to remove the DC offset, but it's not working. Am i doing it right, and if so, what else can i do to fix it? Any help would be greatly appreciated! double* doHighPassFilter(short *buffer) { // Do FFT: int bufferLength = 1024; float *real = malloc(bufferLength*sizeof(float)); float *real2 = malloc(bufferLength*sizeof(float)); for(int x=0;x<bufferLength;x++) { real[x] = buffer[x]; } fft(real, bufferLength); for(int x=0;x<bufferLength;x+=2) { real2[x] = real[x]; } for (int i=0; i < 30; i++) //Set freqs lower than 30hz to zero to attenuate the low frequencies real2[i] = 0; // Do inverse FFT: inversefft(real2,bufferLength); double* real3 = (double*)real2; return real3; } double DetectPitch(short* data) { int sampleRate = 2048; //Create sine wave double *buffer = malloc(1024*sizeof(short)); double amplitude = 0.25 * 32768; //0.25 * max length of short double frequency = 726.0; for (int n = 0; n < 1024; n++) { buffer[n] = (short)(amplitude * sin((2 * 3.14159265 * n * frequency) / sampleRate)); } doHighPassFilter(data); printf("Pitch from sine wave: %f\n",detectPitchCalculation(buffer, 50.0, 1000.0, 1, 1)); printf("Pitch from mic: %f\n",detectPitchCalculation(data, 50.0, 1000.0, 1, 1)); return 0; } // These work by shifting the signal until it seems to correlate with itself. // In other words if the signal looks very similar to (signal shifted 200 data) than the fundamental period is probably 200 data // Note that the algorithm only works well when there's only one prominent fundamental. // This could be optimized by looking at the rate of change to determine a maximum without testing all periods. double detectPitchCalculation(double* data, double minHz, double maxHz, int nCandidates, int nResolution) { //-------------------------1-------------------------// // note that higher frequency means lower period int nLowPeriodInSamples = hzToPeriodInSamples(maxHz, 2048); int nHiPeriodInSamples = hzToPeriodInSamples(minHz, 2048); if (nHiPeriodInSamples <= nLowPeriodInSamples) printf("Bad range for pitch detection."); if (1024 < nHiPeriodInSamples) printf("Not enough data."); double *results = new double[nHiPeriodInSamples - nLowPeriodInSamples]; //-------------------------2-------------------------// for (int period = nLowPeriodInSamples; period < nHiPeriodInSamples; period += nResolution) { double sum = 0; // for each sample, find correlation. (If they are far apart, small) for (int i = 0; i < 1024 - period; i++) sum += data[i] * data[i + period]; double mean = sum / 1024.0; results[period - nLowPeriodInSamples] = mean; } //-------------------------3-------------------------// // find the best indices int *bestIndices = findBestCandidates(nCandidates, results, nHiPeriodInSamples - nLowPeriodInSamples - 1); //note findBestCandidates modifies parameter // convert back to Hz double *res = new double[nCandidates]; for (int i=0; i < nCandidates;i++) res[i] = periodInSamplesToHz(bestIndices[i]+nLowPeriodInSamples, 2048); double pitch2 = res[0]; free(res); free(results); return pitch2; } /// Finds n "best" values from an array. Returns the indices of the best parts. /// (One way to do this would be to sort the array, but that could take too long. /// Warning: Changes the contents of the array!!! Do not use result array afterwards. int* findBestCandidates(int n, double* inputs,int length) { //int length = inputs.Length; if (length < n) printf("Length of inputs is not long enough."); int *res = new int[n]; double minValue = 0; for (int c = 0; c < n; c++) { // find the highest. double fBestValue = minValue; int nBestIndex = -1; for (int i = 0; i < length; i++) { if (inputs[i] > fBestValue) { nBestIndex = i; fBestValue = inputs[i]; } } // record this highest value res[c] = nBestIndex; // now blank out that index. if(nBestIndex!=-1) inputs[nBestIndex] = minValue; } return res; } int hzToPeriodInSamples(double hz, int sampleRate) { return (int)(1 / (hz / (double)sampleRate)); } double periodInSamplesToHz(int period, int sampleRate) { return 1 / (period / (double)sampleRate); } Thanks, Niall. Edit: Changed the code to implement a high pass filter with a cutoff of 30hz (from What Are High-Pass and Low-Pass Filters?, can anyone tell me how to convert the low-pass filter using convolution to a high-pass one?) but it's still returning random results. Plugging it into a VST host and using VST plugins to compare spectrums isn't an option to me unfortunately.

    Read the article

  • Maths Question: number of different permutations

    - by KingCong
    This is more of a maths question than programming but I figure a lot of people here are pretty good at maths! :) My question is: Given a 9 x 9 grid (81 cells) that must contain the numbers 1 to 9 each exactly 9 times, how many different grids can be produced. The order of the numbers doesn't matter, for example the first row could contain nine 1's etc. This is related to Sudoku and we know the number of valid Sudoku grids is 6.67×10^21, so since my problem isn't constrained like Sudoku by having to have each of the 9 numbers in each row, column and box then the answer should be greater than 6.67×10^21. My first thought was that the answer is 81! however on further reflection this assume that the 81 number possible for each cell are different, distinct number. They are not, there are 81 possible numbers for each cell but only 9 possible different numbers. My next thought was then that each of the cells in the first row can be any number between 1 and 9. If by chance the first row happened to be all the same number, say all 1s, then each cell in the second row could only have 8 possibilites, 2-9. If this continued down until the last row then number of different permutations could be calculated by 9^2 * 8^2 * 7^2 ..... * 1^2. However this doesn't work if each row doesn't contain 9 of the same number. It's been quite a while since I studied this stuff and I can't think of a way to work it out, I'd appreciate any help anyone can offer.

    Read the article

  • QTableWidget::itemAt() returns seemingly random items

    - by Jordan Milne
    I've just started using Qt, so please bear with me. When I use QTableWidget-getItemAt(), it returns a different item from if I used currentItemChanged and clicked the same item. I believe it's necessary to use itemAt() since I need to get the first column of whatever row was clicked. Some example code is below: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QList<QString> rowContents; rowContents << "Foo" << "Bar" << "Baz" << "Qux" << "Quux" << "Corge" << "Grault" << "Garply" << "Waldo" << "Fred"; for(int i =0; i < 10; ++i) { ui->tableTest->insertRow(i); ui->tableTest->setItem(i, 0, new QTableWidgetItem(rowContents[i])); ui->tableTest->setItem(i, 1, new QTableWidgetItem(QString::number(i))); } } //... void MainWindow::on_tableTest_currentItemChanged(QTableWidgetItem* current, QTableWidgetItem* previous) { ui->lblColumn->setText(QString::number(current->column())); ui->lblRow->setText(QString::number(current->row())); ui->lblCurrentItem->setText(current->text()); ui->lblCurrentCell->setText(ui->tableTest->itemAt(current->column(), current->row())->text()); } For the item at 1x9, lblCurrentItem displays "9" (as it should,) whereas lblCurrentCell displays "Quux". Am I doing something wrong?

    Read the article

  • Why doesn't java.lang.Number implement Comparable?

    - by Julien Chastang
    Does anyone know why java.lang.Number does not implement Comparable? This means that you cannot sort Numbers with Collections.sort which seems to me a little strange. Post discussion update: Thanks for all the helpful responses. I ended up doing some more research about this topic. The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns. For a bit of review, java.lang.Number is the abstract super-type of AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long and Short. On that list, AtomicInteger and AtomicLong to do not implement Comparable. Digging around, I discovered that it is not a good practice to implement Comparable on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both AtomicLong and AtomicInteger are mutable. The API designers had the forethought to not have Number implement Comparable because it would have constrained implementation of future subtypes. Indeed, AtomicLong and AtomicInteger were added in Java 1.5 long after java.lang.Number was initially implemented. Apart from mutability, there are probably other considerations here too. A compareTo implementation in Number would have to promote all numeric values to BigDecimal because it is capable of accommodating all the Number sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.

    Read the article

  • How can I make a simple path generator?

    - by user360737
    Hi all, I have a link that I have to repeat 50 times, for each folder, and I have 15 folders.the link that I have to repeat looks like this: <a href="update/images/Cars/car (x).JPG" rel="lightbox[cars]"></a> now, the jpg files are named car 1- car 50. and I would really like to be able to generate this script so that I can input the path "update/images/Cars/" the picture title (car) and the input the number of times that I need this link, and then have it spit out something that looks like this: <a href="update/images/Cars/car (1).JPG" rel="lightbox[cars]"></a> <a href="update/images/Cars/car (2).JPG" rel="lightbox[cars]"></a> <a href="update/images/Cars/car (3).JPG" rel="lightbox[cars]"></a> <a href="update/images/Cars/car (4).JPG" rel="lightbox[cars]"></a> <a href="update/images/Cars/car (5).JPG" rel="lightbox[cars]"></a> <a href="update/images/Cars/car (6).JPG" rel="lightbox[cars]"></a> and then it keeps repeating, I'm assuming this can be done with a counter, but I'm not sure. Thanks!

    Read the article

  • c# STILL returning wrong number of cores

    - by Justin
    Ok, so I posted in In C# GetEnvironmentVariable("NUMBER_OF_PROCESSORS") returns the wrong number asking about how to get the correct number of cores in C#. Some helpful people directed me to a couple of questions where similar questions were asked but I have already tried those solutions. My question was then closed as being the same as another question, which is true, it is, but the solution given there didn't work. So I'm opening another one hoping that someone may be able to help realising that the other solutions DID NOT work. That question was How to find the Number of CPU Cores via .NET/C#? which used WMI to try to get the correct number of cores. Well, here's the output from the code given there: Number Of Cores: 32 Number Of Logical Processors: 32 Number Of Physical Processors: 4 As per my last question, the machine is a 64 core AMD Opteron 6276 (4x16 cores) running Windows Server 2008 R2 HPC edition. Regardless of what I do Windows always seems to return 32 cores even though 64 are available. I have confirmed the machine is only using 32 and if I hardcode 64 cores, then the machine uses all of them. I'm wondering if there might be an issue with the way the AMD CPUs are detected. FYI, in case you haven't read the last question, if I type echo %NUMBER_OF_PROCESSORS" at the command line, it returns 64. It just won't do it in a programming environment. Thanks, Justin UPDATE: Outputting PROCESSOR_ARCHITECTURE returns AMD64 from the command line, but x86 from the program. The program is 32-bit running on 64-bit hardware. I was asked to compile it to 64-bit but it still shows 32 cores.

    Read the article

  • Generating random thumbnails with PHP+FFMPEG

    - by MrGhost
    I am trying to generate thumbnails from movies using FFMPEG and the FFMPEG-PHP extension. My script works OK however takes 20 minutes just to generate 5-10 thumbnails! The script works by generating random numbers which are used as frame numbers later. All numbers generated are within the movies frame count. Can you work out why this script is taking 20 mins to finish? <?php //Dont' timeout set_time_limit(0); //Load the file (This can be any file - still takes ages) $mov = new ffmpeg_movie('1486460.mp4'); //Get the total frames within the movie $total_frames = $mov->getFrameCount(); //Loop 5 times to generate random frame times for ($i = 1; $i <= 5; ) { // Generate a number within 200 and the total number of frames. $frame = mt_rand(200,$total_frames); $getframe = $mov->getFrame($frame); // Check if the frame exists within the movie // If it does, place the frame number inside an array and break the current loop if($getframe){ $frames[$frame] = $getframe ; $i++; } } //For each frame found generate a thumbnail foreach ($frames as $key => $getframe) { $gd_image = $getframe->toGDImage(); imagejpeg($gd_image, "images/shot_".$key.'.jpeg'); imagedestroy($gd_image); echo $key.'<br/>'; } ?> The script SHOULD be generating frame numbers which are valid? Anything within START - END should be valid frame numbers? Yet the loop takes ages!

    Read the article

< Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >