Search Results

Search found 299 results on 12 pages for 'pascal t'.

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

  • pascal triangle in php (anything wrong with this solution?) [migrated]

    - by zhenka
    I saw that one of the interview questions could be building a pascal triangle. Is there anything wrong with this particular solution I came up with? function pascal_r($r){ $local = array(); if($r == 1){ return array(array(1)); } else { $previous = pascal_r($r - 1); array_push($local, 1); for($i = 0; $i < $r - 2 && $r > 2; $i++){ array_push($local, $previous[$r-2][$i] + $previous[$r-2][$i + 1]); } array_push($local, 1); } array_push($previous, $local); return $previous; } print_r(pascal_r(100));

    Read the article

  • Lazarus: Can't find unit [unit] used by [program]

    - by Ree
    I'm trying to use an external library (wingraph) in a simple program. I have .o and .ppu files. I added the directory that contains them to the list of both "Other Unit Files" and "Include Files" paths under Project-Compiler Options. When building, I still get the error "Can't find unit wingraph used by [program]". The library is Windows specific and I'm compiling on Windows, too. What should I do to solve the problem? Note that I don't have extensive knowledge about Pascal itself nor its tools. I'm just trying to quickly help someone start using the library.

    Read the article

  • Unicode in fpc doesn't work

    - by user1546454
    Hi I'm Romanian and I can't write Unicode in Free Pascal Compiler. I try to write ?,î,â,a,? and it doesn't work. I tried with dos windows changed fonts, tried chcp. I even made a batch file which would do chcp 65001 and start the app. By default when I tried to write these letter I got "?" but when I started it with the batch file it just didn't write anything. I tried AnsiString, UnicodeString, UTF8String and all didn't work. And I think the problem is in the compiler. Does anyone know a solution?

    Read the article

  • Background changes by itself and procedure repeats many times until I release the mouse button

    - by Robert
    Dear community, I am a student, and I'm working on a little slots game (if the same random number comes up 3 timed, you win). I use Borland Pascal 7. I use graph to make this a bit more visual, but when I start the game my background turns from black to grey, and the other problem is that if I click the game start button, the game runs many times until I release the mouse button. How can I solve this? Here is my full program: program slots; uses mymouse,graph,crt; var gdriver,gmode,coin:integer; m:mouserec; a,b,c,coins:string; procedure gomb(x1,y1,x2,y2:integer;szoveg:string); var j,n:integer; begin setcolor(blue); rectangle(x1,y1,x2,y2); setfillstyle(1,blue); floodfill(x1+2,y1+2,blue); setcolor(0); outtextxy((x1+x2)div 2 -textwidth(szoveg) div 2 ,(y1+y2) div 2-textheight(szoveg) div 2,szoveg); end; procedure randomal(var a,b,c:string); begin randomize; STR(random(2)+1,a); STR(random(2)+1,b); STR(random(2)+1,c); end; procedure menu; begin; settextstyle(0,0,1); outtextxy(20,10,'Meno menu'); gomb(20,20,90,50,'Teglalap'); gomb(20,60,90,90,'Inditas'); gomb(20,100,90,130,'Harmadik'); gomb(20,140,90,170,'Negyedik'); end; procedure teglalap(x1,x2,y1,y2,tinta:integer); begin setcolor(tinta); rectangle(x1,x2,y1,y2); end; procedure jatek(var a,b,c:string;var coin:integer;coins:string); begin; clrscr; menu; randomal(a,b,c); if ((a=b) AND (b=c)) then coin:=coin+1 else coin:=coin-1; settextstyle(0,0,3); setbkcolor(black); outtextxy(200,20,a); outtextxy(240,20,b); outtextxy(280,20,c); STR(coin,coins); outtextxy(400,400,coins); end; procedure eger; begin; mouseinit; mouseon; menu; repeat getmouse(m); if (m.left) and (m.x20) ANd (m.x<90) and (m.y20) and (m.y<50) then teglalap(90,90,300,300,blue); if (m.left) and (m.x20) AND (m.x<90) and (m.y60) and (m.y<90) then jatek(a,b,c,coin,coins); until ((m.left) and (m.x20) ANd (m.x<140) and (m.y140) and (m.y<170)); end; begin coin:=50; gdriver:=detect; initgraph(gdriver, gmode, ''); eger; end. Thank you very much, Robert

    Read the article

  • Exchanging strings (PChar) between a Freepascal compiled DLL and a Delphi compiled EXE

    - by John Riche
    After a lot of experimentations, I found a way to exchange PChar from a FreePascal compiled DLL with a Delphi compiled EXE. I'm in charge of both the DLL and EXE source code but one MUST BE in FreePascal and the other one in Delphi. My solution involves the following methods in the DLL: function GetAString(): PChar; var aString: string; begin aString := 'My String'; result := StrAlloc(length(aString) + 1); StrPCopy(result, aString); end; procedure FreeString(aString: PChar); begin StrDispose(aString); end; And from the Delphi EXE, to call the GetAString method, I need to Call the GetAString method, save the PChar to an actual Delphi String and call the FreeString method. Is this the best way of exchanging a string from a FreePascal DLL with a Delphi EXE ? Can I avoid the call to FreeString from Delphi ? And finally, if that's the correct solution, how will it behave with Delphi 2010 and the WideString by default: do I need to force WidePChar in FreePascal too ?

    Read the article

  • Lazarus - why I can't assign event to run-time component?

    - by Garret Raziel
    Hello, I have this Lazarus program: unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls; type { TForm2 } TForm2 = class(TForm) procedure OnTlacitkoClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); tlac:TButton; private { private declarations } public { public declarations } end; var Form2: TForm2; implementation { TForm2 } procedure TForm2.OnTlacitkoClick(Sender: TObject); begin showmessage('helloworld'); end; procedure TForm2.FormCreate(Sender: TObject); var i,j:integer; begin tlac:=TButton.Create(Form2); tlac.OnClick:=OnTlacitkoClick; tlac.Parent:=Form2; tlac.Left:=100; tlac.Top:=100; end; initialization {$I unit2.lrs} end. but compiler says: unit2.pas(63,32) Error: Wrong number of parameters specified for call to "OnTlacitkoClick" in tlac.OnClick:=OnTlacitkoClick; expression. I have searched and think that this is legal expression in Delphi. I want simply to registrate OnTlacitkoClick as tlac.OnClick event,not to call this procedure. Is there somethink wrong with the code or must I do it different in Lazarus/Freepascal? Thanks.

    Read the article

  • Circular reference fix?

    - by SXMC
    Hi! I have a Player class in a separate unit as follows: TPlayer = class private ... FWorld: TWorld; ... public ... end; I also have a World class in a separate unit as follows: TWorld = class private ... FPlayer: TPlayer; ... public ... end; I have done it this way so that the Player can get data from the world via FWorld, and so that the other objects in the world can get the player data in a similar manner. As you can see this results in a circular reference (and therefore does not work). I have read that this implies bad code design, but I just can't think of any better other way. What could be a better way to do it? Cheers!

    Read the article

  • Delphi - Using DeviceIoControl passing IOCTL_DISK_GET_LENGTH_INFO to get flash media physical size (Not Partition)

    - by SuicideClutchX2
    Alright this is the result of a couple of other questions. It appears I was doing something wrong with the suggestions and at this point have come up with an error when using the suggested API to get the media size. Those new to my problem I am working at the physical disk level, not within the confines of a partition or file system. Here is the pastebin code for the main unit (Delphi 2009) - http://clutchx2.pastebin.com/iMnq8kSx Here is the application source and executable with a form built to output the status of whats going on - http://www.mediafire.com/?js8e6ci8zrjq0de Its probably easier to use the download, unless your just looking for problems within the code. I will also paste the code here. unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TfrmMain = class(TForm) edtDrive: TEdit; lblDrive: TLabel; btnMethod1: TButton; btnMethod2: TButton; lblSpace: TLabel; edtSpace: TEdit; lblFail: TLabel; edtFail: TEdit; lblError: TLabel; edtError: TEdit; procedure btnMethod1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; TDiskExtent = record DiskNumber: Cardinal; StartingOffset: Int64; ExtentLength: Int64; end; DISK_EXTENT = TDiskExtent; PDiskExtent = ^TDiskExtent; TVolumeDiskExtents = record NumberOfDiskExtents: Cardinal; Extents: array[0..0] of TDiskExtent; end; VOLUME_DISK_EXTENTS = TVolumeDiskExtents; PVolumeDiskExtents = ^TVolumeDiskExtents; var frmMain: TfrmMain; const FILE_DEVICE_DISK = $00000007; METHOD_BUFFERED = 0; FILE_ANY_ACCESS = 0; IOCTL_DISK_BASE = FILE_DEVICE_DISK; IOCTL_VOLUME_BASE = DWORD('V'); IOCTL_DISK_GET_LENGTH_INFO = $80070017; IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = ((IOCTL_VOLUME_BASE shl 16) or (FILE_ANY_ACCESS shl 14) or (0 shl 2) or METHOD_BUFFERED); implementation {$R *.dfm} function GetLD(Drive: Char): Cardinal; var Buffer : String; begin Buffer := Format('\\.\%s:',[Drive]); Result := CreateFile(PChar(Buffer),GENERIC_READ Or GENERIC_WRITE,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); If Result = INVALID_HANDLE_VALUE Then begin Result := CreateFile(PChar(Buffer),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); end; end; function GetPD(Drive: Byte): Cardinal; var Buffer : String; begin If Drive = 0 Then begin Result := INVALID_HANDLE_VALUE; Exit; end; Buffer := Format('\\.\PHYSICALDRIVE%d',[Drive]); Result := CreateFile(PChar(Buffer),GENERIC_READ Or GENERIC_WRITE,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); If Result = INVALID_HANDLE_VALUE Then begin Result := CreateFile(PChar(Buffer),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); end; end; function GetPhysicalDiskNumber(Drive: Char): Byte; var LD : DWORD; DiskExtents : PVolumeDiskExtents; DiskExtent : TDiskExtent; BytesReturned : Cardinal; begin Result := 0; LD := GetLD(Drive); If LD = INVALID_HANDLE_VALUE Then Exit; Try DiskExtents := AllocMem(Max_Path); DeviceIOControl(LD,IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,nil,0,DiskExtents,Max_Path,BytesReturned,nil); If DiskExtents^.NumberOfDiskExtents > 0 Then begin DiskExtent := DiskExtents^.Extents[0]; Result := DiskExtent.DiskNumber; end; Finally CloseHandle(LD); end; end; procedure TfrmMain.btnMethod1Click(Sender: TObject); var PD : DWORD; CardSize: Int64; BytesReturned: DWORD; CallSuccess: Boolean; begin PD := GetPD(GetPhysicalDiskNumber(edtDrive.Text[1])); If PD = INVALID_HANDLE_VALUE Then Begin ShowMessage('Invalid Physical Disk Handle'); Exit; End; CallSuccess := DeviceIoControl(PD, IOCTL_DISK_GET_LENGTH_INFO, nil, 0, @CardSize, SizeOf(CardSize), BytesReturned, nil); if not CallSuccess then begin edtError.Text := IntToStr(GetLastError()); edtFail.Text := 'True'; end else edtFail.Text := 'False'; CloseHandle(PD); end; end. I placed a second method button on the form so I can write a different set of code into the app if I feel like it. Only minimal error handling and safeguards are there is nothing that wasn't necessary for debugging this via source. I tried this on a Sony Memory Stick using a PSP as the reader because I cant find the adapter for using a duo in my machine. The target is an MS and half of my users use a PSP for a reader half dont. However this should work fine on SD cards and that is a secondary target for my work as well. I tried this on a usb memory card reader and several SD cards. Now that I have fixed my attempt I get an error returned. 50 ERROR_NOT_SUPPORTED The request is not supported. I have found an application that uses this API as well as alot of related functions for what I am trying todo. I am getting ready to look into it the application is called DriveImage and its source is here - http://sourceforge.net/projects/diskimage/ The only thing I have really noticed from that application is there use of TFileStream and using that to get a handle on the physical disk.

    Read the article

  • How to format a string to camel case in XSLT?

    - by DBA_Alex
    I'm trying to format strings in XSLT that needs to be in camel case to be used appropriately for the application I'm working with. For example: this_text would become ThisText this_long_text would become ThisLongText Is it possible to also set this up where I can send an input to the format so I do not have to recreate the format multiple times?

    Read the article

  • finishing some functions in this code

    - by osabri
    i have problem to finish some functions in this code program lab4; var inFile : text; var pArray : array[1..10]of real; //array of 10 integer values containing patterns to search in a given set of numbers var rArray : array[1..10]of integer; //array containing result of pattern search, each index in rArray coresponds to number of occurences of //pattern from pArray in sArray. var sArray : array[1..100] of real; //array containing data read from file var accuracy : real; (****************************************************************************) function errMsg:integer; begin if ParamCount < 3 then begin writeln('Too few arguments'); writeln('Usage: ./lab4 lab4.txt <accuracy> <pattern_1> <pattern_2> <pattern_n>'); errMsg:=-1; end else if ParamCount > 12 then begin writeln('Too many arguments'); writeln('Maximum number of patterns is 10'); errMsg:=-1; end else begin assign(inFile,ParamStr(1)); {$I-} reset(inFile); if ioresult<>0 then begin writeln('Cannot open ',ParamStr(1)); errMsg:=-1; end else errMsg:=0; end; end; (****************************************************************************) procedure readPattern; var errPos,idx:integer; begin if errMsg=0 then begin for idx:=1 to ParamCount-2 do begin Val(ParamStr(idx+2),pArray[idx],errPos); writeln('pArray:',pArray[idx]:2:2); end; end; end; (****************************************************************************) procedure getAccuracy; //Function should get the accuracy as the first param (after the program name) begin (here where i stopped : (( ) end; (****************************************************************************) function readSet:integer; //Function returns number of elements read from file var idx,errPos:integer; var sChar: string; begin if errMsg=0 then begin idx:=1; repeat begin readln(inFile,sChar); VAL(sChar,sArray[idx],errPos); writeln('sArray:',sArray[idx]:2:2); idx:=idx+1; end until eof(inFile)=TRUE; end; readSet:=idx-1; end; (****************************************************************************) procedure searchPattern(sNumber:integer); //Function should search and count pattern(patterns) occurence in a given set what the best solution for this part?? (****************************************************************************) procedure dispResult; //Function should display the result of pattern(patterns) search begin (****************************************************************************) begin readPattern; getAccuracy; searchPattern(readSet); dispResult; end.

    Read the article

  • How can I change standart input/output of another program?

    - by Azad Salahli
    I have a console application written in c++. It simply reads an integer from standard input(keyboard) and writes another integer to standard output(screen). Now I want to give some tests to that program and check its answers using another program. In another words, I want to write electron judge for that program. I want that program(which I want to test) to read from file and write to file without changing source code. How can I do that. I tried assigning input&output to files before executing c++ program, but it did not worked. assign(input,'temp.in'); reset(input); assign(output,'temp.out'); rewrite(output); exec('domino.exe'); close(input); close(output);

    Read the article

  • Static and Dynamic Scooping Problem

    - by Devyn
    Hi, I'm solving following code in Static and Dynamic Scooping. I got following answer but I need someone to confirm if I'm correct or not since I'm a bit confusing. I really appreciate if anyone can explain in simple way! Static => (1)8 (2)27 Dynamic => (1)10 (2)27 proc main var x,y,z; proc sub1 var x,z x := 6; z := 7; sub2; x := y*z + x; print(x); ---- (2) end; proc sub2 var x,y x := 1; y := x+z+2; print(y); ---- (1) end; begin x := 1; y:=3; z:=5; sub1; end

    Read the article

  • String literal recognition problem

    - by helicera
    Hello! I'm trying to recognize string literal by reading string per symbol. Here is a sample code: #region [String Literal (")] case '"': // {string literal ""} { // skipping '"' ChCurrent = Line.ElementAtOrDefault<Char>(++ChPosition); while(ChCurrent != '"') { Value.Append(ChCurrent); ChCurrent = Line.ElementAtOrDefault<Char>(++ChPosition); if(ChCurrent == '"') { // "" sequence only acceptable if(Line.ElementAtOrDefault<Char>(ChPosition + 1) == '"') { Value.Append(ChCurrent); // skip 2nd double quote ChPosition++; // move position next ChCurrent = Line.ElementAtOrDefault<Char>(++ChPosition); } } else if(default(Char) == ChCurrent) { // message: unterminated string throw new ScanningException(); } } ChPosition++; break; } #endregion When I run test: [Test] [ExpectedException(typeof(ScanningException))] public void ScanDoubleQuotedStrings() { this.Scanner.Run(@"""Hello Language Design""", default(System.Int32)); this.Scanner.Run(@"""Is there any problems with the """"strings""""?""", default(System.Int32)); this.Scanner.Run(@"""v#:';?325;.<>,|+_)""(*&^%$#@![]{}\|-_=""", default(System.Int32)); while(0 != this.Scanner.TokensCount - 1) { Assert.AreEqual(Token.TokenClass.StringLiteral, this.Scanner.NextToken.Class); } } It passes with success.. while I'm expecting to have an exception according to unmatched " mark in this.Scanner.Run(@"""v#:';?325;.<>,|+_)""(*&^%$#@![]{}\|-_=""", default(System.Int32)); Can anyone explain where is my mistake or give an advice on algorithm.

    Read the article

  • Delphi: EInvalidOp in neural network class (TD-lambda)

    - by user89818
    I have the following draft for a neural network class. This neural network should learn with TD-lambda. It is started by calling the getRating() function. But unfortunately, there is an EInvalidOp (invalid floading point operation) error after about 1000 iterations in the following lines: neuronsHidden[j] := neuronsHidden[j]+neuronsInput[t][i]*weightsInput[i][j]; // input -> hidden weightsHidden[j][k] := weightsHidden[j][k]+LEARNING_RATE_HIDDEN*tdError[k]*eligibilityTraceOutput[j][k]; // adjust hidden->output weights according to TD-lambda Why is this error? I can't find the mistake in my code :( Can you help me? Thank you very much in advance! unit uNeuronalesNetz; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Grids, Menus, Math; const NEURONS_INPUT = 43; // number of neurons in the input layer NEURONS_HIDDEN = 60; // number of neurons in the hidden layer NEURONS_OUTPUT = 1; // number of neurons in the output layer NEURONS_TOTAL = NEURONS_INPUT+NEURONS_HIDDEN+NEURONS_OUTPUT; // total number of neurons in the network MAX_TIMESTEPS = 42; // maximum number of timesteps possible (after 42 moves: board is full) LEARNING_RATE_INPUT = 0.25; // in ideal case: decrease gradually in course of training LEARNING_RATE_HIDDEN = 0.15; // in ideal case: decrease gradually in course of training GAMMA = 0.9; LAMBDA = 0.7; // decay parameter for eligibility traces type TFeatureVector = Array[1..43] of SmallInt; // definition of the array type TFeatureVector TArtificialNeuralNetwork = class // definition of the class TArtificialNeuralNetwork private // GENERAL SETTINGS START learningMode: Boolean; // does the network learn and change its weights? // GENERAL SETTINGS END // NETWORK CONFIGURATION START neuronsInput: Array[1..MAX_TIMESTEPS] of Array[1..NEURONS_INPUT] of Extended; // array of all input neurons (their values) for every timestep neuronsHidden: Array[1..NEURONS_HIDDEN] of Extended; // array of all hidden neurons (their values) neuronsOutput: Array[1..NEURONS_OUTPUT] of Extended; // array of output neurons (their values) weightsInput: Array[1..NEURONS_INPUT] of Array[1..NEURONS_HIDDEN] of Extended; // array of weights: input->hidden weightsHidden: Array[1..NEURONS_HIDDEN] of Array[1..NEURONS_OUTPUT] of Extended; // array of weights: hidden->output // NETWORK CONFIGURATION END // LEARNING SETTINGS START outputBefore: Array[1..NEURONS_OUTPUT] of Extended; // the network's output value in the last timestep (the one before) eligibilityTraceHidden: Array[1..NEURONS_INPUT] of Array[1..NEURONS_HIDDEN] of Array[1..NEURONS_OUTPUT] of Extended; // array of eligibility traces: hidden layer eligibilityTraceOutput: Array[1..NEURONS_TOTAL] of Array[1..NEURONS_TOTAL] of Extended; // array of eligibility traces: output layer reward: Array[1..MAX_TIMESTEPS] of Array[1..NEURONS_OUTPUT] of Extended; // the reward value for all output neurons in every timestep tdError: Array[1..NEURONS_OUTPUT] of Extended; // the network's error value for every single output neuron t: Byte; // current timestep cyclesTrained: Integer; // number of cycles trained so far (learning rates could be decreased accordingly) last50errors: Array[1..50] of Extended; // LEARNING SETTINGS END public constructor Create; // create the network object and do the initialization procedure UpdateEligibilityTraces; // update the eligibility traces for the hidden and output layer procedure tdLearning; // learning algorithm: adjust the network's weights procedure ForwardPropagation; // propagate the input values through the network to the output layer function getRating(state: TFeatureVector; explorative: Boolean): Extended; // get the rating for a given state (feature vector) function HyperbolicTangent(x: Extended): Extended; // calculate the hyperbolic tangent [-1;1] procedure StartNewCycle; // start a new cycle with everything set to default except for the weights procedure setLearningMode(activated: Boolean=TRUE); // switch the learning mode on/off procedure setInputs(state: TFeatureVector); // transfer the given feature vector to the input layer (set input neurons' values) procedure setReward(currentReward: SmallInt); // set the reward for the current timestep (with learning then or without) procedure nextTimeStep; // increase timestep t function getCyclesTrained(): Integer; // get the number of cycles trained so far procedure Visualize(imgHidden: Pointer); // visualize the neural network's hidden layer end; implementation procedure TArtificialNeuralNetwork.UpdateEligibilityTraces; var i, j, k: Integer; begin // how worthy is a weight to be adjusted? for j := 1 to NEURONS_HIDDEN do begin for k := 1 to NEURONS_OUTPUT do begin eligibilityTraceOutput[j][k] := LAMBDA*eligibilityTraceOutput[j][k]+(neuronsOutput[k]*(1-neuronsOutput[k]))*neuronsHidden[j]; for i := 1 to NEURONS_INPUT do begin eligibilityTraceHidden[i][j][k] := LAMBDA*eligibilityTraceHidden[i][j][k]+(neuronsOutput[k]*(1-neuronsOutput[k]))*weightsHidden[j][k]*neuronsHidden[j]*(1-neuronsHidden[j])*neuronsInput[t][i]; end; end; end; end; procedure TArtificialNeuralNetwork.setReward; VAR i: Integer; begin for i := 1 to NEURONS_OUTPUT do begin // +1 = player A wins // 0 = draw // -1 = player B wins reward[t][i] := currentReward; end; end; procedure TArtificialNeuralNetwork.tdLearning; var i, j, k: Integer; begin if learningMode then begin for k := 1 to NEURONS_OUTPUT do begin if reward[t][k] = 0 then begin tdError[k] := GAMMA*neuronsOutput[k]-outputBefore[k]; // network's error value when reward is 0 end else begin tdError[k] := reward[t][k]-outputBefore[k]; // network's error value in the final state (reward received) end; for j := 1 to NEURONS_HIDDEN do begin weightsHidden[j][k] := weightsHidden[j][k]+LEARNING_RATE_HIDDEN*tdError[k]*eligibilityTraceOutput[j][k]; // adjust hidden->output weights according to TD-lambda for i := 1 to NEURONS_INPUT do begin weightsInput[i][j] := weightsInput[i][j]+LEARNING_RATE_INPUT*tdError[k]*eligibilityTraceHidden[i][j][k]; // adjust input->hidden weights according to TD-lambda end; end; end; end; end; procedure TArtificialNeuralNetwork.ForwardPropagation; var i, j, k: Integer; begin for j := 1 to NEURONS_HIDDEN do begin neuronsHidden[j] := 0; for i := 1 to NEURONS_INPUT do begin neuronsHidden[j] := neuronsHidden[j]+neuronsInput[t][i]*weightsInput[i][j]; // input -> hidden end; neuronsHidden[j] := HyperbolicTangent(neuronsHidden[j]); // activation of hidden neuron j end; for k := 1 to NEURONS_OUTPUT do begin neuronsOutput[k] := 0; for j := 1 to NEURONS_HIDDEN do begin neuronsOutput[k] := neuronsOutput[k]+neuronsHidden[j]*weightsHidden[j][k]; // hidden -> output end; neuronsOutput[k] := HyperbolicTangent(neuronsOutput[k]); // activation of output neuron k end; end; procedure TArtificialNeuralNetwork.setLearningMode; begin learningMode := activated; end; constructor TArtificialNeuralNetwork.Create; var i, j, k: Integer; begin inherited Create; Randomize; // initialize random numbers generator learningMode := TRUE; cyclesTrained := -2; // only set to -2 because it will be increased twice in the beginning StartNewCycle; for j := 1 to NEURONS_HIDDEN do begin for k := 1 to NEURONS_OUTPUT do begin weightsHidden[j][k] := abs(Random-0.5); // initialize weights: 0 <= random < 0.5 end; for i := 1 to NEURONS_INPUT do begin weightsInput[i][j] := abs(Random-0.5); // initialize weights: 0 <= random < 0.5 end; end; for i := 1 to 50 do begin last50errors[i] := 0; end; end; procedure TArtificialNeuralNetwork.nextTimeStep; begin t := t+1; end; procedure TArtificialNeuralNetwork.StartNewCycle; var i, j, k, m: Integer; begin t := 1; // start in timestep 1 cyclesTrained := cyclesTrained+1; // increase the number of cycles trained so far for j := 1 to NEURONS_HIDDEN do begin neuronsHidden[j] := 0; for k := 1 to NEURONS_OUTPUT do begin eligibilityTraceOutput[j][k] := 0; outputBefore[k] := 0; neuronsOutput[k] := 0; for m := 1 to MAX_TIMESTEPS do begin reward[m][k] := 0; end; end; for i := 1 to NEURONS_INPUT do begin for k := 1 to NEURONS_OUTPUT do begin eligibilityTraceHidden[i][j][k] := 0; end; end; end; end; function TArtificialNeuralNetwork.getCyclesTrained; begin result := cyclesTrained; end; procedure TArtificialNeuralNetwork.setInputs; var k: Integer; begin for k := 1 to NEURONS_INPUT do begin neuronsInput[t][k] := state[k]; end; end; function TArtificialNeuralNetwork.getRating; begin setInputs(state); ForwardPropagation; result := neuronsOutput[1]; if not explorative then begin tdLearning; // adjust the weights according to TD-lambda ForwardPropagation; // calculate the network's output again outputBefore[1] := neuronsOutput[1]; // set outputBefore which will then be used in the next timestep UpdateEligibilityTraces; // update the eligibility traces for the next timestep nextTimeStep; // go to the next timestep end; end; function TArtificialNeuralNetwork.HyperbolicTangent; begin if x > 5500 then // prevent overflow result := 1 else result := (Exp(2*x)-1)/(Exp(2*x)+1); end; end.

    Read the article

  • Delphi Memory Management

    - by nomad311
    I haven't been able to find the answers to a couple of my Delphi memory management questions. I could test different scenarios (which I did to find out what breaks the FreeAndNil method), but its takes too long and its hard! But seriously, I would also like to know how you all (Delphi developers) handle these memory management issues. My Questions (Feel free to pose your own I'm sure the answers to them will help me too): Does FreeAndNil work for COM objects? My thoughts are I don't need it, but if all I need to do is set it to nil than why not stay consistent in my finally block and use FreeAndNil for everything? Whats the proper way to clean up static arrays (myArr : Array[0..5] of TObject). I can't FreeAndNil it, so is it good enough to just set it to nil (do I need to do that after I've FreeAnNil'd each object?)? Thanks Guys!

    Read the article

  • How can I enable Pascal casing by default when using Jackson JSON in Spring MVC?

    - by bhilstrom
    I have a project that uses Spring MVC to create and handle multiple REST endpoints. I'm currently working on using Jackson to automatically handle the seralization/deserialization of JSON using the @RequestBody and @ResponseBody annotations. I have gotten Jackson working, so I've got a starting point. My problem is that our old serialization was done manually and used Pascal casing instead of Camel casing ("MyVariable" instead of "myVariable"), and Jackson does Camel casing by default. I know that I can manually change the name for a variable using @JsonProperty. That being said, I do not consider adding "@JsonProperty" to all of my variables to be a viable long-term solution. Is there a way to make Jackson use Pascal casing when serializing and deserializing other than using the @JsonProperty annotation?

    Read the article

  • Problem with installing Nvidia display drivers on Ubuntu 13.10

    - by Pascal
    Hello everyone and thank you for taking a look at this topic! I'm currently trying out Ubuntu 13.10 but I keep hitting a wall when it comes to installing a driver. I've tried: sudo apt-get install nvidia-current This resulted in a un-bootable system. The screen just stayed black and the cursor displayed as an 'X'. After that I did had to re-install Ubuntu. The computer I'm using is an Acer-Aspire-V3 with a build in Nvidia geforce GT 630M and also with a Intel HD graphics chip-set (not sure if chip-set is the right word here). "lspci | grep VGA" output: pascal@pascal-Aspire-V3-571G:~$ lspci | grep VGA 00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09) 01:00.0 VGA compatible controller: NVIDIA Corporation GF108M [GeForce GT 630M] (rev a1) I've searched a bit here and there and found out that it would be wise to mention that this laptop is using (or so I think) Nvidia Optimus, not sure if it will add anything to the subject but at least I'll mention it just to be sure. Now to the questions: Q1 How is this caused and how can I fix it? Q2 What additional information could I provide to help you help me?

    Read the article

  • megacli forceWB

    - by Pascal den Bekker
    We are using a raid controller: LSI Logic / Symbios Logic MegaRAID SAS 2008 But there is no BBU on Board, is there a way to force the WB Cache ?? I tried following: - /opt/MegaRAID/MegaCli/MegaCli64 -LDSetProp CachedBadBBU -L0 -a0 Failed to set Write Cache OK if bad BBU on Adapter 0, VD 0. FW error description: The requested command has invalid arguments. Can anyone help? Cheers, Pascal

    Read the article

  • LLBLGen Pro feature highlights: automatic element name construction

    - by FransBouma
    (This post is part of a series of posts about features of the LLBLGen Pro system) One of the things one might take for granted but which has a huge impact on the time spent in an entity modeling environment is the way the system creates names for elements out of the information provided, in short: automatic element name construction. Element names are created in both directions of modeling: database first and model first and the more names the system can create for you without you having to rename them, the better. LLBLGen Pro has a rich, fine grained system for creating element names out of the meta-data available, which I'll describe more in detail below. First the model element related element naming features are highlighted, in the section Automatic model element naming features and after that I'll go more into detail about the relational model element naming features LLBLGen Pro has to offer in the section Automatic relational model element naming features. Automatic model element naming features When working database first, the element names in the model, e.g. entity names, entity field names and so on, are in general determined from the relational model element (e.g. table, table field) they're mapped on, as the model elements are reverse engineered from these relational model elements. It doesn't take rocket science to automatically name an entity Customer if the entity was created after reverse engineering a table named Customer. It gets a little trickier when the entity which was created by reverse engineering a table called TBL_ORDER_LINES has to be named 'OrderLine' automatically. Automatic model element naming also takes into effect with model first development, where some settings are used to provide you with a default name, e.g. in the case of navigator name creation when you create a new relationship. The features below are available to you in the Project Settings. Open Project Settings on a loaded project and navigate to Conventions -> Element Name Construction. Strippers! The above example 'TBL_ORDER_LINES' shows that some parts of the table name might not be needed for name creation, in this case the 'TBL_' prefix. Some 'brilliant' DBAs even add suffixes to table names, fragments you might not want to appear in the entity names. LLBLGen Pro offers you to define both prefix and suffix fragments to strip off of table, view, stored procedure, parameter, table field and view field names. In the example above, the fragment 'TBL_' is a good candidate for such a strip pattern. You can specify more than one pattern for e.g. the table prefix strip pattern, so even a really messy schema can still be used to produce clean names. Underscores Be Gone Another thing you might get rid of are underscores. After all, most naming schemes for entities and their classes use PasCal casing rules and don't allow for underscores to appear. LLBLGen Pro can automatically strip out underscores for you. It's an optional feature, so if you like the underscores, you're not forced to see them go: LLBLGen Pro will leave them alone when ordered to to so. PasCal everywhere... or not, your call LLBLGen Pro can automatically PasCal case names on word breaks. It determines word breaks in a couple of ways: a space marks a word break, an underscore marks a word break and a case difference marks a word break. It will remove spaces in all cases, and based on the underscore removal setting, keep or remove the underscores, and upper-case the first character of a word break fragment, and lower case the rest. Say, we keep the defaults, which is remove underscores and PasCal case always and strip the TBL_ fragment, we get with our example TBL_ORDER_LINES, after stripping TBL_ from the table name two word fragments: ORDER and LINES. The underscores are removed, the first character of each fragment is upper-cased, the rest lower-cased, so this results in OrderLines. Almost there! Pluralization and Singularization In general entity names are singular, like Customer or OrderLine so LLBLGen Pro offers a way to singularize the names. This will convert OrderLines, the result we got after the PasCal casing functionality, into OrderLine, exactly what we're after. Show me the patterns! There are other situations in which you want more flexibility. Say, you have an entity Customer and an entity Order and there's a foreign key constraint defined from the target of Order and the target of Customer. This foreign key constraint results in a 1:n relationship between the entities Customer and Order. A relationship has navigators mapped onto the relationship in both entities the relationship is between. For this particular relationship we'd like to have Customer as navigator in Order and Orders as navigator in Customer, so the relationship becomes Customer.Orders 1:n Order.Customer. To control the naming of these navigators for the various relationship types, LLBLGen Pro defines a set of patterns which allow you, using macros, to define how the auto-created navigator names will look like. For example, if you rather have Customer.OrderCollection, you can do so, by changing the pattern from {$EndEntityName$P} to {$EndEntityName}Collection. The $P directive makes sure the name is pluralized, which is not what you want if you're going for <EntityName>Collection, hence it's removed. When working model first, it's a given you'll create foreign key fields along the way when you define relationships. For example, you've defined two entities: Customer and Order, and they have their fields setup properly. Now you want to define a relationship between them. This will automatically create a foreign key field in the Order entity, which reflects the value of the PK field in Customer. (No worries if you hate the foreign key fields in your classes, on NHibernate and EF these can be hidden in the generated code if you want to). A specific pattern is available for you to direct LLBLGen Pro how to name this foreign key field. For example, if all your entities have Id as PK field, you might want to have a different name than Id as foreign key field. In our Customer - Order example, you might want to have CustomerId instead as foreign key name in Order. The pattern for foreign key fields gives you that freedom. Abbreviations... make sense of OrdNr and friends I already described word breaks in the PasCal casing paragraph, how they're used for the PasCal casing in the constructed name. Word breaks are used for another neat feature LLBLGen Pro has to offer: abbreviation support. Burt, your friendly DBA in the dungeons below the office has a hate-hate relationship with his keyboard: he can't stand it: typing is something he avoids like the plague. This has resulted in tables and fields which have names which are very short, but also very unreadable. Example: our TBL_ORDER_LINES example has a lovely field called ORD_NR. What you would like to see in your fancy new OrderLine entity mapped onto this table is a field called OrderNumber, not a field called OrdNr. What you also like is to not have to rename that field manually. There are better things to do with your time, after all. LLBLGen Pro has you covered. All it takes is to define some abbreviation - full word pairs and during reverse engineering model elements from tables/views, LLBLGen Pro will take care of the rest. For the ORD_NR field, you need two values: ORD as abbreviation and Order as full word, and NR as abbreviation and Number as full word. LLBLGen Pro will now convert every word fragment found with the word breaks which matches an abbreviation to the given full word. They're case sensitive and can be found in the Project Settings: Navigate to Conventions -> Element Name Construction -> Abbreviations. Automatic relational model element naming features Not everyone works database first: it may very well be the case you start from scratch, or have to add additional tables to an existing database. For these situations, it's key you have the flexibility that you can control the created table names and table fields without any work: let the designer create these names based on the entity model you defined and a set of rules. LLBLGen Pro offers several features in this area, which are described in more detail below. These features are found in Project Settings: navigate to Conventions -> Model First Development. Underscores, welcome back! Not every database is case insensitive, and not every organization requires PasCal cased table/field names, some demand all lower or all uppercase names with underscores at word breaks. Say you create an entity model with an entity called OrderLine. You work with Oracle and your organization requires underscores at word breaks: a table created from OrderLine should be called ORDER_LINE. LLBLGen Pro allows you to do that: with a simple checkbox you can order LLBLGen Pro to insert an underscore at each word break for the type of database you're working with: case sensitive or case insensitive. Checking the checkbox Insert underscore at word break case insensitive dbs will let LLBLGen Pro create a table from the entity called Order_Line. Half-way there, as there are still lower case characters there and you need all caps. No worries, see below Casing directives so everyone can sleep well at night For case sensitive databases and case insensitive databases there is one setting for each of them which controls the casing of the name created from a model element (e.g. a table created from an entity definition using the auto-mapping feature). The settings can have the following values: AsProjectElement, AllUpperCase or AllLowerCase. AsProjectElement is the default, and it keeps the casing as-is. In our example, we need to get all upper case characters, so we select AllUpperCase for the setting for case sensitive databases. This will produce the name ORDER_LINE. Sequence naming after a pattern Some databases support sequences, and using model-first development it's key to have sequences, when needed, to be created automatically and if possible using a name which shows where they're used. Say you have an entity Order and you want to have the PK values be created by the database using a sequence. The database you're using supports sequences (e.g. Oracle) and as you want all numeric PK fields to be sequenced, you have enabled this by the setting Auto assign sequences to integer pks. When you're using LLBLGen Pro's auto-map feature, to create new tables and constraints from the model, it will create a new table, ORDER, based on your settings I previously discussed above, with a PK field ID and it also creates a sequence, SEQ_ORDER, which is auto-assigns to the ID field mapping. The name of the sequence is created by using a pattern, defined in the Model First Development setting Sequence pattern, which uses plain text and macros like with the other patterns previously discussed. Grouping and schemas When you start from scratch, and you're working model first, the tables created by LLBLGen Pro will be in a catalog and / or schema created by LLBLGen Pro as well. If you use LLBLGen Pro's grouping feature, which allows you to group entities and other model elements into groups in the project (described in a future blog post), you might want to have that group name reflected in the schema name the targets of the model elements are in. Say you have a model with a group CRM and a group HRM, both with entities unique for these groups, e.g. Employee in HRM, Customer in CRM. When auto-mapping this model to create tables, you might want to have the table created for Employee in the HRM schema but the table created for Customer in the CRM schema. LLBLGen Pro will do just that when you check the setting Set schema name after group name to true (default). This gives you total control over where what is placed in the database from your model. But I want plural table names... and TBL_ prefixes! For now we follow best practices which suggest singular table names and no prefixes/suffixes for names. Of course that won't keep everyone happy, so we're looking into making it possible to have that in a future version. Conclusion LLBLGen Pro offers a variety of options to let the modeling system do as much work for you as possible. Hopefully you enjoyed this little highlight post and that it has given you new insights in the smaller features available to you in LLBLGen Pro, ones you might not have thought off in the first place. Enjoy!

    Read the article

  • Installing gnome shell extensions from extensions.gnome.org fails silently

    - by Pascal
    On a fresh Ubuntu install (12.04, 64-bit), after installing gnome-shell, I've tried to install some extensions from extensions.gnome.org but got no result. I've tried with Firefox and Chromium and got the same issue. Open any extension page on extensions.gnome.org. Switch extension to "ON". Agree with confirmation about installation. Nothing happens and nothing has been installed (.local/share/gnome-shell/extensions is empty). I've checked .xsession-errors, Firefox's javascript console, gnome-shell console errors (Alt-F2 + looking glass). There isn't any trace of any error.

    Read the article

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