Search Results

Search found 637 results on 26 pages for 'p1'.

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

  • VB6 ADO Command to SQL Server

    - by Emtucifor
    I'm getting an inexplicable error with an ADO command in VB6 run against a SQL Server 2005 database. Here's some code to demonstrate the problem: Sub ADOCommand() Dim Conn As ADODB.Connection Dim Rs As ADODB.Recordset Dim Cmd As ADODB.Command Dim ErrorAlertID As Long Dim ErrorTime As Date Set Conn = New ADODB.Connection Conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=database;Data Source=server" Conn.CursorLocation = adUseClient Conn.Open Set Rs = New ADODB.Recordset Rs.CursorType = adOpenStatic Rs.LockType = adLockReadOnly Set Cmd = New ADODB.Command With Cmd .Prepared = False .CommandText = "ErrorAlertCollect" .CommandType = adCmdStoredProc .NamedParameters = True .Parameters.Append .CreateParameter("@ErrorAlertID", adInteger, adParamOutput) .Parameters.Append .CreateParameter("@CreateTime", adDate, adParamOutput) Set .ActiveConnection = Conn Rs.Open Cmd ErrorAlertID = .Parameters("@ErrorAlertID").Value ErrorTime = .Parameters("@CreateTime").Value End With Debug.Print Rs.State ' Shows 0 - Closed Debug.Print Rs.RecordCount ' Of course this fails since the recordset is closed End Sub So this code was working not too long ago but now it's failing on the last line with the error: Run-time error '3704': Operation is not allowed when the object is closed Why is it closed? I just opened it and the SP returns rows. I ran a trace and this is what the ADO library is actually submitting to the server: declare @p1 int set @p1=1 declare @p2 datetime set @p2=''2010-04-22 15:31:07:770'' exec ErrorAlertCollect @ErrorAlertID=@p1 output,@CreateTime=@p2 output select @p1, @p2 Running this as a separate batch from my query editor yields: Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '2010'. Of course there's an error. Look at the double single quotes in there. What the heck could be causing that? I tried using adDBDate and adDBTime as data types for the date parameter, and they give the same results. When I make the parameters adParamInputOutput, then I get this: declare @p1 int set @p1=default declare @p2 datetime set @p2=default exec ErrorAlertCollect @ErrorAlertID=@p1 output,@CreateTime=@p2 output select @p1, @p2 Running that as a separate batch yields: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'default'. Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'default'. What the heck? SQL Server doesn't support this kind of syntax. You can only use the DEFAULT keyword in the actual SP execution statement. I should note that removing the extra single quotes from the above statement makes the SP run fine. ... Oh my. I just figured it out. I guess it's worth posting anyway.

    Read the article

  • how to save django object using dictionary?

    - by shahjapan
    is there a way that I can save the model by using dictionary for e.g. this is working fine, p1 = Poll.objects.get(pk=1) p1.name = 'poll2' p1.descirption = 'poll2 description' p1.save() but what if I have dictionary like { 'name': 'poll2', 'description: 'poll2 description' } is there a simple way to save the such dictionary direct to Poll

    Read the article

  • python popen and mysql import

    - by khelll
    I'm doing the following: from subprocess import PIPE from subprocess import Popen file = 'dump.sql.gz' p1 = Popen(["gzip", "-cd" ,file], stdout=PIPE) print "Importing temporary file %s" % file p2 = Popen(["mysql","--default-character-set=utf8", "--user=root" , "--password=something", "--host=localhost", "--port=3306" , 'my_db'],stdin=p1.stdout, stdout=PIPE,stderr=PIPE) err = p1.communicate()[1] if err: print err err = p2.communicate()[1] if err: print err But the db is not being populated. No errors are shown, also I have checked p1.stdout and it has the file contents. Any ideas?

    Read the article

  • Passing arguments to scope_procedure in searchlogic

    - by Greg
    I'd like to use searchlogic's scope_procedure feature like so class MyModelObject < ActiveRecord::Base scope_procedure :my_scope_proc, lambda { |p1, p2| { :conditions => "p1 >= #{p1} AND p2 < #{p2}" }} end Then, I am doing the search: scope = MyModelObject.search(:my_scope_proc => true) scope.all The above code obviously doesn't work because I didn't pass p1 and p2 parameters to my named scope. I can't figure out how to pass parameters to the named scope.

    Read the article

  • Which of these queries is preferable?

    - by bread
    I've written the same query as a subquery and a self-join. Is there any obvious argument for one over the other here? SUBQUERY: SELECT prod_id, prod_name FROM products WHERE vend_id = (SELECT vend_id FROM products WHERE prod_id = ‘DTNTR’); SELF-JOIN: SELECT p1.prod_id, p1.prod_name FROM products p1, products p2 WHERE p1.vend_id = p2.vend_id AND p2.prod_id = ‘DTNTR’;

    Read the article

  • Creating New Object of Other Class dynamicly ?

    - by Meko
    I am trying to create new object of other class in a for loop. like for(int i =0;i<10;i++){ Computer p1=new Computer(10,20); } and when I try anywhere to reach p1.someAction(); it say you must declare p1. But if I declare it on top of program how can I create again in loop? I also try only Computer p1; but it gave exeption ..

    Read the article

  • activating the class need help.... :)

    - by asm_debuger
    this is my code... i dont anderstend way the class dont work... import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.GridLayout; import java.awt.Panel; public class Caldesinger { public Panel p1=new Panel(); public Button[] arr=new Button[20]; public String[] name = {"9","8","7","6","5","4","3","2","1","0","+","-","*","/",".","cos","sin","=","pow"}; public Caldesinger() { for (int i = 0; i < arr.length; i++) { this.arr[i]=new Button(""+name[i]); } } public Panel getP1() { return p1; } public void setP1(Panel p1) { this.p1 = p1; } public Button[] getArr() { return arr; } public void setArr(Button[] arr) { this.arr = arr; } public Object c() { this.p1.setLayout(new GridLayout(4,15)); for (int i = 0; i < arr.length; i++) { arr[i].setBackground(Color.LIGHT_GRAY); arr[i].setForeground(Color.orange); p1.add(arr[i]); } this.p1.setLayout(new GridLayout(4,15)); return this; } } the class desinge the applet this is the main: import java.applet.Applet; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Mainapp extends Applet implements ActionListener { Caldesinger desinge=new Caldesinger (); public void init() { this.setLayout(new BorderLayout()); this.desinge.c(); } public void ActionPerformed(ActionEvent arg0) { for (int i = 0; i <20; i++) { if(arg0.getSource()== this.desinge.arr[i]); } } } way the method c does not work? the method desinge the applet

    Read the article

  • Problems with DNS propagation 10 days after a change was made

    - by runlevel6
    The engineering team I work with has been in the process of moving equipment from one datacenter to another. Ten days ago we moved one of our name servers authoritative for our client's domains (ns1.faithhiway.com) and updated its IP address with its respective DNS provider (register.com) to point to the new datacenter. All tests done show that this name server is correctly running at its new location and when queried, returning the correct response for any domains it is responsible for. The problem is that well after 72 hours had gone by we were still seeing more DNS activity at its old IP address than at the new. The good news is that we kept a name server responding on the old IP address for the time being so we are not seeing any issues with the domains our nameserver is responsible for but the goal is to retire that as soon as possible. As you can see from WhatsMyDNS.net, a decent amount of propagation has occurred over the last 10 days since we made this change, but still there are some locations reporting our original IP. Considering that the TTL is only 3600 with the name servers responsible for this domain, it does not make any sense to myself or the other engineers working with me that we are having this issue. Now if I run a DNS check using one of the Register.com DNS servers (direct nameservers for faithhiway.com), I get the following (correct) result: # dig @dns01.gpn.register.com ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @dns01.gpn.register.com. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43232 ;; flags: qr aa; QUERY: 1, ANSWER: 1, AUTHORITY: 5, ADDITIONAL: 5 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 3601 IN A 206.127.2.71 ;; AUTHORITY SECTION: faithhiway.com. 3600 IN NS dns01.gpn.register.com. faithhiway.com. 3600 IN NS dns02.gpn.register.com. faithhiway.com. 3600 IN NS dns03.gpn.register.com. faithhiway.com. 3600 IN NS dns04.gpn.register.com. faithhiway.com. 3600 IN NS dns05.gpn.register.com. ;; ADDITIONAL SECTION: dns01.gpn.register.com. 3600 IN A 98.124.192.1 dns02.gpn.register.com. 3600 IN A 98.124.197.1 dns03.gpn.register.com. 3600 IN A 98.124.193.1 dns04.gpn.register.com. 3600 IN A 69.64.145.225 dns05.gpn.register.com. 3600 IN A 98.124.196.1 ;; Query time: 50 msec ;; SERVER: 98.124.192.1#53(98.124.192.1) ;; WHEN: Thu Jan 27 15:16:57 2011 ;; MSG SIZE rcvd: 269 Just as a reference, here are the results when the same query is checked against a variety of Public DNS servers: Google: # dig @8.8.8.8 ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @8.8.8.8. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12773 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 997 IN A 206.127.2.71 ;; Query time: 29 msec ;; SERVER: 8.8.8.8#53(8.8.8.8) ;; WHEN: Thu Jan 27 15:17:31 2011 ;; MSG SIZE rcvd: 52 Level 3: # dig @4.2.2.1 ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @4.2.2.1. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 46505 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 2623 IN A 206.127.2.71 ;; Query time: 7 msec ;; SERVER: 4.2.2.1#53(4.2.2.1) ;; WHEN: Thu Jan 27 15:18:35 2011 ;; MSG SIZE rcvd: 52 Verizon: # dig @151.197.0.38 ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @151.197.0.38. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 32658 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 3601 IN A 206.127.2.71 ;; Query time: 81 msec ;; SERVER: 151.197.0.38#53(151.197.0.38) ;; WHEN: Thu Jan 27 15:19:15 2011 ;; MSG SIZE rcvd: 52 Cisco: # dig @64.102.255.44 ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @64.102.255.44. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39689 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 5, ADDITIONAL: 0 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 3601 IN A 206.127.2.71 ;; AUTHORITY SECTION: faithhiway.com. 3600 IN NS dns01.gpn.register.com. faithhiway.com. 3600 IN NS dns04.gpn.register.com. faithhiway.com. 3600 IN NS dns05.gpn.register.com. faithhiway.com. 3600 IN NS dns02.gpn.register.com. faithhiway.com. 3600 IN NS dns03.gpn.register.com. ;; Query time: 105 msec ;; SERVER: 64.102.255.44#53(64.102.255.44) ;; WHEN: Thu Jan 27 15:20:05 2011 ;; MSG SIZE rcvd: 165 OpenDNS: # dig @208.67.222.222 ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @208.67.222.222. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12328 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 169507 IN A 207.200.19.162 ;; Query time: 6 msec ;; SERVER: 208.67.222.222#53(208.67.222.222) ;; WHEN: Thu Jan 27 15:19:29 2011 ;; MSG SIZE rcvd: 52 SpeakEasy: # dig @66.93.87.2 ns1.faithhiway.com A ; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_5.3 <<>> @66.93.87.2. ns1.faithhiway.com A ; (1 server found) ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9342 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;ns1.faithhiway.com. IN A ;; ANSWER SECTION: ns1.faithhiway.com. 169323 IN A 207.200.19.162 ;; Query time: 69 msec ;; SERVER: 66.93.87.2#53(66.93.87.2) ;; WHEN: Thu Jan 27 15:19:51 2011 ;; MSG SIZE rcvd: 52 As you can see above, the majority of queries are returning the correct result. But a few (OpenDNS and SpeakEasy in the examples above) are still showing the old IP address. Considering the length of time that has gone by, it seems obvious to me that either we have made a mistake and not thoroughly handled the DNS changes on our end (likely) or there is a problem with either the DNS provider for this domain (Register) or with some of the DNS servers out in the wild (rather unlikely). Any advice on how I can proceed with this? UPDATE (January 31, 2011): First of all, I apologize for the length of both the original question and this update. I contemplated removing some of the excess from the original post but just in case this problem and its solution are helpful to someone else in the future I'm just going to leave everything as it is. Anyway, I've been doing some more research into this problem, and have discovered the following interesting occurrence. While running a check on the glue records for faithhiway.com always resolve correctly, if I go and check a client domain (where ns1.faithhiway.com is authoritative), I get a strange response. It looks like the root servers are returning nsX.faithhiway.com as their old IP addresses still (under Additional Section). Because we have a server still there responding to DNS queries, the trace finishes and returns the correct IP addresses as the final step (again, under Additional Section). The example below uses one of the domains that we use that uses ns1.faithhiway.com as its authoritative DNS server. # dig +trace +nosearch +all +norecurse ignitemail.com ; <<>> DiG 9.2.4 <<>> +trace +nosearch +all +norecurse ignitemail.com ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 46856 ;; flags: qr ra; QUERY: 1, ANSWER: 13, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;. IN NS ;; ANSWER SECTION: . 7986 IN NS a.root-servers.net. . 7986 IN NS b.root-servers.net. . 7986 IN NS c.root-servers.net. . 7986 IN NS d.root-servers.net. . 7986 IN NS e.root-servers.net. . 7986 IN NS f.root-servers.net. . 7986 IN NS g.root-servers.net. . 7986 IN NS h.root-servers.net. . 7986 IN NS i.root-servers.net. . 7986 IN NS j.root-servers.net. . 7986 IN NS k.root-servers.net. . 7986 IN NS l.root-servers.net. . 7986 IN NS m.root-servers.net. ;; Query time: 39 msec ;; SERVER: 8.8.8.8#53(8.8.8.8) ;; WHEN: Mon Jan 31 09:22:17 2011 ;; MSG SIZE rcvd: 228 ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 16325 ;; flags: qr; QUERY: 1, ANSWER: 0, AUTHORITY: 13, ADDITIONAL: 14 ;; QUESTION SECTION: ;ignitemail.com. IN A ;; AUTHORITY SECTION: com. 172800 IN NS h.gtld-servers.net. com. 172800 IN NS m.gtld-servers.net. com. 172800 IN NS i.gtld-servers.net. com. 172800 IN NS l.gtld-servers.net. com. 172800 IN NS c.gtld-servers.net. com. 172800 IN NS k.gtld-servers.net. com. 172800 IN NS d.gtld-servers.net. com. 172800 IN NS f.gtld-servers.net. com. 172800 IN NS b.gtld-servers.net. com. 172800 IN NS a.gtld-servers.net. com. 172800 IN NS e.gtld-servers.net. com. 172800 IN NS g.gtld-servers.net. com. 172800 IN NS j.gtld-servers.net. ;; ADDITIONAL SECTION: a.gtld-servers.net. 172800 IN A 192.5.6.30 a.gtld-servers.net. 172800 IN AAAA 2001:503:a83e::2:30 b.gtld-servers.net. 172800 IN A 192.33.14.30 b.gtld-servers.net. 172800 IN AAAA 2001:503:231d::2:30 c.gtld-servers.net. 172800 IN A 192.26.92.30 d.gtld-servers.net. 172800 IN A 192.31.80.30 e.gtld-servers.net. 172800 IN A 192.12.94.30 f.gtld-servers.net. 172800 IN A 192.35.51.30 g.gtld-servers.net. 172800 IN A 192.42.93.30 h.gtld-servers.net. 172800 IN A 192.54.112.30 i.gtld-servers.net. 172800 IN A 192.43.172.30 j.gtld-servers.net. 172800 IN A 192.48.79.30 k.gtld-servers.net. 172800 IN A 192.52.178.30 l.gtld-servers.net. 172800 IN A 192.41.162.30 ;; Query time: 64 msec ;; SERVER: 198.41.0.4#53(a.root-servers.net) ;; WHEN: Mon Jan 31 09:22:17 2011 ;; MSG SIZE rcvd: 504 ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12860 ;; flags: qr; QUERY: 1, ANSWER: 0, AUTHORITY: 2, ADDITIONAL: 2 ;; QUESTION SECTION: ;ignitemail.com. IN A ;; AUTHORITY SECTION: ignitemail.com. 172800 IN NS ns1.faithhiway.com. ignitemail.com. 172800 IN NS ns2.faithhiway.com. ;; ADDITIONAL SECTION: ns1.faithhiway.com. 172800 IN A 207.200.19.162 ns2.faithhiway.com. 172800 IN A 207.200.50.142 ;; Query time: 152 msec ;; SERVER: 192.54.112.30#53(h.gtld-servers.net) ;; WHEN: Mon Jan 31 09:22:17 2011 ;; MSG SIZE rcvd: 111 ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43016 ;; flags: qr aa; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 2 ;; QUESTION SECTION: ;ignitemail.com. IN A ;; ANSWER SECTION: ignitemail.com. 3600 IN A 206.127.2.64 ;; AUTHORITY SECTION: ignitemail.com. 3600 IN NS ns1.faithhiway.com. ignitemail.com. 3600 IN NS ns2.faithhiway.com. ;; ADDITIONAL SECTION: ns1.faithhiway.com. 3600 IN A 206.127.2.71 ns2.faithhiway.com. 3600 IN A 206.127.2.72 ;; Query time: 25 msec ;; SERVER: 206.127.2.71#53(ns1.faithhiway.com) ;; WHEN: Mon Jan 31 09:22:18 2011 ;; MSG SIZE rcvd: 127 I really think this is a problem we have somewhere in our setup, but whether it is ignorance of something with DNS on my or my fellow engineer's end or just a dumb mistake we made, I have yet to find it.

    Read the article

  • i see the file but when i open it nothing is in it in c++ i/o stream and dont know why

    - by user320950
    #include<iostream> #include<fstream> #include<cstdlib> #include<iomanip> using namespace std; int main() { ifstream in_stream; // reads ITEMSLIST.txt ofstream out_stream1; // writes in listWititems.txt ifstream in_stream2; // reads PRICELIST.txt ofstream out_stream3;// writes in listWitprices.txt ifstream in_stream4;// read display.txt ofstream out_stream5;// write showitems.txt double p1=0.0,p2=0.0; int wrong=0; int count =0; char next; in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items /*if( in_stream.fail() )// check to see if itemlist.txt is open { wrong++; // counts number of errors cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; } */ out_stream1.open("listWititems.txt", ios::out); // list of avaliable items /* if( out_stream1.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; } */ in_stream2.open("PRICELIST.txt", ios::in); /*if( in_stream2.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; } */ out_stream3.open("listWitdollars.txt", ios::out); /*if( out_stream3.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; } */ in_stream4.open("display.txt", ios::in); /*if( in_stream4.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; } */ out_stream5.open("showitems.txt", ios::out); /*if( out_stream5.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; }*/ in_stream.setf(ios::fixed); while(!in_stream.eof()) // reads to end of file and gets p1 which is itemnum, clears and gets next character { in_stream >> p1; cin.clear(); cin >> next; } out_stream1.setf(ios::fixed); while (!out_stream1.eof()) { out_stream1 << p1; cin.clear(); cin >> next; } in_stream2.setf(ios::fixed); in_stream2.setf(ios::showpoint); in_stream2.precision(2); while(!in_stream2.eof()) // reads file to end of file { in_stream2 >> p1 >> p2 >> count; // gets p1,p2, and count which is current total in_stream2 >> p2; p1 += p2; p2++; cin.clear(); // allows more reading cin >> next; return p1, p2; } out_stream3.setf(ios::fixed); out_stream3.setf(ios::showpoint); out_stream3.precision(2); while(!out_stream3.eof()) // reads file to end of file { out_stream3 << p1 << p2 << count; out_stream3 << p2; p1 += p2; p2++; cin.clear(); // allows more reading cin >> next; return p1, p2; } in_stream4.setf(ios::fixed); in_stream4.setf(ios::showpoint); in_stream4.precision(2); while (!in_stream4.eof()) { in_stream4 >> p1 >> p2 >> count; cin.clear(); cin >> next; } out_stream5.setf(ios::fixed); out_stream5.setf(ios::showpoint); out_stream5.precision(2); out_stream5 <<setw(5)<< " itemnum " <<setw(5)<<" price "<<setw(5)<<" curr_total " <<endl; // sends items and prices to receipt.txt out_stream5 << setw(5) << p1 << setw(5) <<p2 << setw(5)<< count; // sends items and prices to receipt.txt out_stream5 << " You have a total of " << wrong++ << " errors " << endl; in_stream.close(); // closing files. out_stream1.close(); in_stream2.close(); out_stream3.close(); in_stream4.close(); out_stream5.close(); system("pause"); }

    Read the article

  • JavaScript Optimisation

    - by Jayie
    I am using JavaScript to work out all the combinations of badminton doubles matches from a given list of players. Each player teams up with everyone else. EG. If I have the following players a, b, c & d. Their combinations can be: a & b V c & d a & c V b & d a & d V b & c I am using the code below, which I wrote to do the job, but it's a little inefficient. It loops through the PLAYERS array 4 times finding every single combination (including impossible ones). It then sorts the game out into alphabetical order and stores it in the GAMES array if it doesn't already exist. I can then use the first half of the GAMES array to list all game combinations. The trouble is if I have any more than 8 players it runs really slowly because the combination growth is exponential. Does anyone know a better way or algorithm I could use? The more I think about it the more my brain hurts! var PLAYERS = ["a", "b", "c", "d", "e", "f", "g"]; var GAMES = []; var p1, p2, p3, p4, i1, i2, i3, i4, entry, found, i; var pos = 0; var TEAM1 = []; var TEAM2 = []; // loop through players 4 times to get all combinations for (i1 = 0; i1 < PLAYERS.length; i1++) { p1 = PLAYERS[i1]; for (i2 = 0; i2 < PLAYERS.length; i2++) { p2 = PLAYERS[i2]; for (i3 = 0; i3 < PLAYERS.length; i3++) { p3 = PLAYERS[i3]; for (i4 = 0; i4 < PLAYERS.length; i4++) { p4 = PLAYERS[i4]; if ((p1 != p2 && p1 != p3 && p1 != p4) && (p2 != p1 && p2 != p3 && p2 != p4) && (p3 != p1 && p3 != p2 && p3 != p4) && (p4 != p1 && p4 != p2 && p4 != p3)) { // sort teams into alphabetical order (so we can compare them easily later) TEAM1[0] = p1; TEAM1[1] = p2; TEAM2[0] = p3; TEAM2[1] = p4; TEAM1.sort(); TEAM2.sort(); // work out the game and search the array to see if it already exists entry = TEAM1[0] + " & " + TEAM1[1] + " v " + TEAM2[0] + " & " + TEAM2[1]; found = false; for (i=0; i < GAMES.length; i++) { if (entry == GAMES[i]) found = true; } // if the game is unique then store it if (!found) { GAMES[pos] = entry; document.write((pos+1) + ": " + GAMES[pos] + "<br>"); pos++; } } } } } } Thanks in advance. Jason.

    Read the article

  • Help with string manipulation function

    - by MusiGenesis
    I have a set of strings that contain within them one or more question marks delimited by a comma, a comma plus one or more spaces, or potentially both. So these strings are all possible: BOB AND ? BOB AND ?,?,?,?,? BOB AND ?, ?, ? ,? BOB AND ?,? , ?,? ?, ? ,? AND BOB I need to replace the question marks with @P#, so that the above samples would become: BOB AND @P1 BOB AND @P1,@P2,@P3,@P4,@P5 BOB AND @P1,@P2,@P3,@P4 BOB AND @P1,@P2,@P3,@P4 @P1,@P2,@P3 AND BOB What's the best way to do this without regex or Linq?

    Read the article

  • How to rotate a set of points on z = 0 plane in 3-D, preserving pairwise distances?

    - by cagirici
    I have a set of points double n[] on the plane z = 0. And I have another set of points double[] m on the plane ax + by + cz + d = 0. Length of n is equal to length of m. Also, euclidean distance between n[i] and n[j] is equal to euclidean distance between m[i] and m[j]. I want to rotate n[] in 3-D, such that for all i, n[i] = m[i] would be true. In other words, I want to turn a plane into another plane, preserving the pairwise distances. Here's my code in java. But it does not help so much: double[] rotate(double[] point, double[] currentEquation, double[] targetEquation) { double[] currentNormal = new double[]{currentEquation[0], currentEquation[1], currentEquation[2]}; double[] targetNormal = new double[]{targetEquation[0], targetEquation[1], targetEquation[2]}; targetNormal = normalize(targetNormal); double angle = angleBetween(currentNormal, targetNormal); double[] axis = cross(targetNormal, currentNormal); double[][] R = getRotationMatrix(axis, angle); return rotated; } double[][] getRotationMatrix(double[] axis, double angle) { axis = normalize(axis); double cA = (float)Math.cos(angle); double sA = (float)Math.sin(angle); Matrix I = Matrix.identity(3, 3); Matrix a = new Matrix(axis, 3); Matrix aT = a.transpose(); Matrix a2 = a.times(aT); double[][] B = { {0, axis[2], -1*axis[1]}, {-1*axis[2], 0, axis[0]}, {axis[1], -1*axis[0], 0} }; Matrix A = new Matrix(B); Matrix R = I.minus(a2); R = R.times(cA); R = R.plus(a2); R = R.plus(A.times(sA)); return R.getArray(); } This is what I get. The point set on the right side is actually part of a point set on the left side. But they are on another plane. Here's a 2-D representation of what I try to do: There are two lines. The line on the bottom is the line I have. The line on the top is the target line. The distances are preserved (a, b and c). Edit: I have tried both methods written in answers. They both fail (I guess). Method of Martijn Courteaux public static double[][] getRotationMatrix(double[] v0, double[] v1, double[] v2, double[] u0, double[] u1, double[] u2) { RealMatrix M1 = new Array2DRowRealMatrix(new double[][]{ {1,0,0,-1*v0[0]}, {0,1,0,-1*v0[1]}, {0,0,1,0}, {0,0,0,1} }); RealMatrix M2 = new Array2DRowRealMatrix(new double[][]{ {1,0,0,-1*u0[0]}, {0,1,0,-1*u0[1]}, {0,0,1,-1*u0[2]}, {0,0,0,1} }); Vector3D imX = new Vector3D((v0[1] - v1[1])*(u2[0] - u0[0]) - (v0[1] - v2[1])*(u1[0] - u0[0]), (v0[1] - v1[1])*(u2[1] - u0[1]) - (v0[1] - v2[1])*(u1[1] - u0[1]), (v0[1] - v1[1])*(u2[2] - u0[2]) - (v0[1] - v2[1])*(u1[2] - u0[2]) ).scalarMultiply(1/((v0[0]*v1[1])-(v0[0]*v2[1])-(v1[0]*v0[1])+(v1[0]*v2[1])+(v2[0]*v0[1])-(v2[0]*v1[1]))); Vector3D imZ = new Vector3D(findEquation(u0, u1, u2)); Vector3D imY = Vector3D.crossProduct(imZ, imX); double[] imXn = imX.normalize().toArray(); double[] imYn = imY.normalize().toArray(); double[] imZn = imZ.normalize().toArray(); RealMatrix M = new Array2DRowRealMatrix(new double[][]{ {imXn[0], imXn[1], imXn[2], 0}, {imYn[0], imYn[1], imYn[2], 0}, {imZn[0], imZn[1], imZn[2], 0}, {0, 0, 0, 1} }); RealMatrix rotationMatrix = MatrixUtils.inverse(M2).multiply(M).multiply(M1); return rotationMatrix.getData(); } Method of Sam Hocevar static double[][] makeMatrix(double[] p1, double[] p2, double[] p3) { double[] v1 = normalize(difference(p2,p1)); double[] v2 = normalize(cross(difference(p3,p1), difference(p2,p1))); double[] v3 = cross(v1, v2); double[][] M = { { v1[0], v2[0], v3[0], p1[0] }, { v1[1], v2[1], v3[1], p1[1] }, { v1[2], v2[2], v3[2], p1[2] }, { 0.0, 0.0, 0.0, 1.0 } }; return M; } static double[][] createTransform(double[] A, double[] B, double[] C, double[] P, double[] Q, double[] R) { RealMatrix c = new Array2DRowRealMatrix(makeMatrix(A,B,C)); RealMatrix t = new Array2DRowRealMatrix(makeMatrix(P,Q,R)); return MatrixUtils.inverse(c).multiply(t).getData(); } The blue points are the calculated points. The black lines indicate the offset from the real position.

    Read the article

  • Parameters with default value not in PsBoundParameters?

    - by stej
    General code Consider this code: PS> function Test { param($p='default value') $PsBoundParameters } PS> Test 'some value' Key Value --- ----- p some value PS> Test # nothing I would expect that $PsBoundParameters would contain record for $p variable on both cases. Is that correct behaviour? Question I'd like to use splatting for a lot of functions that would work like this: function SomeFuncWithManyRequiredParams { param( [Parameter(Mandatory=$true)][string]$p1, [Parameter(Mandatory=$true)][string]$p2, [Parameter(Mandatory=$true)][string]$p3, ...other parameters ) ... } function SimplifiedFuncWithDefaultValues { param( [Parameter(Mandatory=$false)][string]$p1='default for p1', [Parameter(Mandatory=$false)][string]$p2='default for p2', [Parameter(Mandatory=$false)][string]$p3='default for p3', ...other parameters ) SomeFuncWithManyRequiredParams @PsBoundParameters } I have more functions like this and I don't want to call SomeFuncWithManyRequiredParams with all the params enumerated: SomeFuncWithManyRequiredParams -p1 $p1 -p2 $p2 -p3 $p3 ... Is it possible?

    Read the article

  • Ruby - Call method passing values of array as each parameter

    - by Markus Orreilly
    I'm currently stuck on this problem. I've hooked into the method_missing function in a class I've made. When a function is called that doesn't exist, I want to call another function I know exists, passing the args array as all of the parameters to the second function. Does anyone know a way to do this? For example, I'd like to do something like this: class Blah def valid_method(p1, p2, p3, opt=false) puts "p1: #{p1}, p2: #{p2}, p3: #{p3}, opt: #{opt.inspect}" end def method_missing(methodname, *args) if methodname.to_s =~ /_with_opt$/ real_method = methodname.to_s.gsub(/_with_opt$/, '') send(real_method, args) # <-- this is the problem end end end b = Blah.new b.valid_method(1,2,3) # output: p1: 1, p2: 2, p3: 3, opt: false b.valid_method_with_opt(2,3,4) # output: p1: 2, p2: 3, p3: 4, opt: true (Oh, and btw, the above example doesn't work for me)

    Read the article

  • Help understanding some OpenGL stuff

    - by shinjuo
    I am working with some code to create a triangle that moves with arrow keys. I want to create a second object that moves independently. This is where I am having trouble, I have created the second actor, but cannot get it to move. There is too much code to post it all so I will just post a little and see if anyone can help at all. ogl_test.cpp #include "platform.h" #include "srt/scheduler.h" #include "model.h" #include "controller.h" #include "model_module.h" #include "graphics_module.h" class blob : public actor { public: blob(float x, float y) : actor(math::vector2f(x, y)) { } void render() { transform(); glBegin(GL_TRIANGLES); glVertex3f(0.25f, 0.0f, -5.0f); glVertex3f(-.5f, 0.25f, -5.0f); glVertex3f(-.5f, -0.25f, -5.0f); glEnd(); end_transform(); } void update(controller& c, float dt) { if (c.left_key) { rho += pi / 9.0f * dt; c.left_key = false; } if (c.right_key) { rho -= pi / 9.0f * dt; c.right_key = false; } if (c.up_key) { v += .1f * dt; c.up_key = false; } if (c.down_key) { v -= .1f * dt; if (v < 0.0) { v = 0.0; } c.down_key = false; } actor::update(c, dt); } }; class enemyOne : public actor { public: enemyOne(float x, float y) : actor(math::vector2f(x, y)) { } void render() { transform(); glBegin(GL_TRIANGLES); glVertex3f(0.25f, 0.0f, -5.0f); glVertex3f(-.5f, 0.25f, -5.0f); glVertex3f(-.5f, -0.25f, -5.0f); glEnd(); end_transform(); } void update(controller& c, float dt) { if (c.left_key) { rho += pi / 9.0f * dt; c.left_key = false; } if (c.right_key) { rho -= pi / 9.0f * dt; c.right_key = false; } if (c.up_key) { v += .1f * dt; c.up_key = false; } if (c.down_key) { v -= .1f * dt; if (v < 0.0) { v = 0.0; } c.down_key = false; } actor::update(c, dt); } }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, char* lpCmdLine, int nCmdShow ) { model m; controller control(m); srt::scheduler scheduler(33); srt::frame* model_frame = new srt::frame(scheduler.timer(), 0, 1, 2); srt::frame* render_frame = new srt::frame(scheduler.timer(), 1, 1, 2); model_frame->add(new model_module(m, control)); render_frame->add(new graphics_module(m)); scheduler.add(model_frame); scheduler.add(render_frame); blob* prime = new blob(0.0f, 0.0f); m.add(prime); m.set_prime(prime); enemyOne* primeTwo = new enemyOne(2.0f, 0.0f); m.add(primeTwo); m.set_prime(primeTwo); scheduler.start(); control.start(); return 0; } model.h #include <vector> #include "vec.h" const double pi = 3.14159265358979323; class controller; using math::vector2f; class actor { public: vector2f P; float theta; float v; float rho; actor(const vector2f& init_location) : P(init_location), rho(0.0), v(0.0), theta(0.0) { } virtual void render() = 0; virtual void update(controller&, float dt) { float v1 = v; float theta1 = theta + rho * dt; vector2f P1 = P + v1 * vector2f(cos(theta1), sin(theta1)); if (P1.x < -4.5f || P1.x > 4.5f) { P1.x = -P1.x; } if (P1.y < -4.5f || P1.y > 4.5f) { P1.y = -P1.y; } v = v1; theta = theta1; P = P1; } protected: void transform() { glPushMatrix(); glTranslatef(P.x, P.y, 0.0f); glRotatef(theta * 180.0f / pi, 0.0f, 0.0f, 1.0f); //Rotate about the z-axis } void end_transform() { glPopMatrix(); } }; class model { private: typedef std::vector<actor*> actor_vector; actor_vector actors; public: actor* _prime; model() { } void add(actor* a) { actors.push_back(a); } void set_prime(actor* a) { _prime = a; } void update(controller& control, float dt) { for (actor_vector::iterator i = actors.begin(); i != actors.end(); ++i) { (*i)->update(control, dt); } } void render() { for (actor_vector::iterator i = actors.begin(); i != actors.end(); ++i) { (*i)->render(); } } };

    Read the article

  • How do you control what your C compiler Optimizes?

    - by Jordan S
    I am writing the firmware for an embedded device in C using the Silicon Labs IDE and the SDCC compiler. The device architecture is based on the 8051 family. The function in question is shown below. The function is used to set the ports on my MCU to drive a stepper motor. It gets called in by an interrupt handler. The big switch statement just sets the ports to the proper value for the next motor step. The bottom part of the function looks at an input from a hall effect sensor and a number of steps moved in order to detect if the motor has stalled. The problem is, for some reason the second IF statement that looks like this if (StallDetector > (GapSize + 20)) { HandleStallEvent(); } always seems to get optimized out. If I try to put a breakpoint at the HandleStallEvent() call the IDE gives me a message saying "No Address Correlation to this line number". I am not really good enough at reading assembly to tell what it is doing but I have pasted a snippet from the asm output below. Any help would be much appreciated. void OperateStepper(void) { //static bit LastHomeMagState = HomeSensor; static bit LastPosMagState = PosSensor; if(PulseMotor) { if(MoveDirection == 1) // Go clockwise { switch(STEPPER_POSITION) { case 'A': STEPPER_POSITION = 'B'; P1 = 0xFD; break; case 'B': STEPPER_POSITION = 'C'; P1 = 0xFF; break; case 'C': STEPPER_POSITION = 'D'; P1 = 0xFE; break; case 'D': STEPPER_POSITION = 'A'; P1 = 0xFC; break; default: STEPPER_POSITION = 'A'; P1 = 0xFC; } //end switch } else // Go CounterClockwise { switch(STEPPER_POSITION) { case 'A': STEPPER_POSITION = 'D'; P1 = 0xFE; break; case 'B': STEPPER_POSITION = 'A'; P1 = 0xFC; break; case 'C': STEPPER_POSITION = 'B'; P1 = 0xFD; break; case 'D': STEPPER_POSITION = 'C'; P1 = 0xFF; break; default: STEPPER_POSITION = 'A'; P1 = 0xFE; } //end switch } //end else MotorSteps++; StallDetector++; if(PosSensor != LastPosMagState) { StallDetector = 0; LastPosMagState = PosSensor; } else { if (PosSensor == ON) { if (StallDetector > (MagnetSize + 20)) { HandleStallEvent(); } } else if (PosSensor == OFF) { if (StallDetector > (GapSize + 20)) { HandleStallEvent(); } } } } //end if PulseMotor } ... and the asm output for the the bottom part of this function... ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:653: if(PosSensor != LastPosMagState) mov c,_P1_4 jb _OperateStepper_LastPosMagState_1_1,00158$ cpl c 00158$: jc 00126$ C$MotionControl.c$655$3$7 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:655: StallDetector = 0; clr a mov _StallDetector,a mov (_StallDetector + 1),a C$MotionControl.c$657$3$7 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:657: LastPosMagState = PosSensor; mov c,_P1_4 mov _OperateStepper_LastPosMagState_1_1,c ret 00126$: C$MotionControl.c$661$2$8 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:661: if (PosSensor == ON) jb _P1_4,00123$ C$MotionControl.c$663$4$9 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:663: if (StallDetector > (MagnetSize + 20)) mov a,_MagnetSize mov r2,a rlc a subb a,acc mov r3,a mov a,#0x14 add a,r2 mov r2,a clr a addc a,r3 mov r3,a clr c mov a,r2 subb a,_StallDetector mov a,r3 subb a,(_StallDetector + 1) jnc 00130$ C$MotionControl.c$665$5$10 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:665: HandleStallEvent(); ljmp _HandleStallEvent 00123$: C$MotionControl.c$668$2$8 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:668: else if (PosSensor == OFF) jnb _P1_4,00130$ C$MotionControl.c$670$4$11 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:670: if (StallDetector > (GapSize + 20)) mov a,#0x14 add a,_GapSize mov r2,a clr a addc a,(_GapSize + 1) mov r3,a clr c mov a,r2 subb a,_StallDetector mov a,r3 subb a,(_StallDetector + 1) jnc 00130$ C$MotionControl.c$672$5$12 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:672: HandleStallEvent(); C$MotionControl.c$678$2$1 ==. XG$OperateStepper$0$0 ==. ljmp _HandleStallEvent 00130$: ret It looks to me like the compiler is NOT optimizing out this second if statement from the looks of the asm but if that is the case why does the IDE not allow me so set a breakpoint there? Maybe it's just a dumb IDE!

    Read the article

  • Is there a way to rewrite the SQL query efficiently

    - by user320587
    hi, I have two tables with following definition TableA TableB ID1 ID2 ID3 Value1 Value ID1 Value1 C1 P1 S1 S1 C1 P1 S2 S2 C1 P1 S3 S3 C1 P1 S5 S4 S5 The values are just examples in the table. TableA has a clustered primary key ID1, ID2 & ID3 and TableB has p.k. ID1 I need to create a table that has the missing records in TableA based on TableB The select query I am trying to create should give the following output C1 P1 S4 To do this, I have the following SQL query SELECT DISTINCT TableA.ID1, TableA.ID2, TableB.ID1 FROM TableA a, TableB b WHERE TableB.ID1 NOT IN ( SELECT DISTINCT [ID3] FROM TableA aa WHERE a.ID1 == aa.ID1 AND a.ID2 == aa.ID2 ) Though this query works, it performs poorly and my final TableA may have upto 1M records. is there a way to rewrite this more efficiently. Thanks for any help, Javid

    Read the article

  • How to structure (normalize?) a database of physical parameters?

    - by Arrieta
    Hello: I have a collection of physical parameters associated with different items. For example: Item, p1, p2, p3 a, 1, 2, 3 b, 4, 5, 6 [...] where px stands for parameter x. I could go ahead and store the database exactly as presented; the schema would be CREATE TABLE t1 (item TEXT PRIMARY KEY, p1 FLOAT, p2 FLOAT, p3 FLOAT); I could retrieve the parameter p1 for all the items with the statement: SELECT p1 FROM t1; A second alternative is to have an schema like: CREATE TABLE t1 (id INT PRIMARY KEY, item TEXT, par TEXT, val FLOAT) This seems much simpler if you have many parameters (as I do). However, the parameter retrieval seems very awkward: SELECT val FROM t1 WHERE par == 'p1' What do you advice? Should go for the "pivoted" (first) version or the id, par, val (second) version? Many thanks.

    Read the article

  • MySQL Inserting into locked aliased table

    - by Whitey
    I am trying to insert data into a InnoDB MySQL table which is locked using an alias and I cannot for the life of me get it to work! The following works: LOCK TABLES Problems p1 WRITE, Problems p2 WRITE, Server READ; SELECT * FROM Problems p1; UNLOCK TABLES; But try and do an insert and it doesn't work (it claims there is a syntax error round the 'p1' in my INSERT): LOCK TABLES Problems p1 WRITE, Problems p2 WRITE, Server READ; INSERT INTO Problems p1 (SomeCol) VALUES(43534); UNLOCK TABLES; Help please!

    Read the article

  • Algorithm for redirecting the traffic

    - by TechGeeky
    I was going through the interview questions and found out the below question which I am not able to answer it. Can anyone provide some sort of algorithm for this problem how can I solve it? There are a cluster of stateless servers all serving the same pages. The servers are hosting 5 web pages- p1.html, p2.html, p3.html, p4.html and p5.html p1.html just redirects users to the other 4 pages Requests to p1.html should result in 10% of users being redirected to p2.html, 5% of users redirected to p3.html, 20% of users redirected to p4.html, and 65% of users redirected to p5.html. Users do not need to stick to the page they are first redirected to. They could end up on a different page with every request to p1.html Write a function/pseudocode that would be invoked with every request to p1.html and redirect the correct percentage of users to the correct page. Any suggestions will be of great help.

    Read the article

  • Is it a good practice to pass struct object as parameter to a function in c++?

    - by tsubasa
    I tried an example live below: typedef struct point { int x; int y; } point; void cp(point p) { cout<<p.x<<endl; cout<<p.y<<endl; } int main() { point p1; p1.x=1; p1.y=2; cp(p1); } The result thats printed out is: 1 2 which is what I expected. My question is: Does parameter p get the full copy of object p1? If so, I wonder if this is a good practice? (I assumed when the struct gets big in size, this will create a lot of copy overhead).

    Read the article

  • Improve SQL query performance

    - by Anax
    I have three tables where I store actual person data (person), teams (team) and entries (athlete). The schema of the three tables is: In each team there might be two or more athletes. I'm trying to create a query to produce the most frequent pairs, meaning people who play in teams of two. I came up with the following query: SELECT p1.surname, p1.name, p2.surname, p2.name, COUNT(*) AS freq FROM person p1, athlete a1, person p2, athlete a2 WHERE p1.id = a1.person_id AND p2.id = a2.person_id AND a1.team_id = a2.team_id AND a1.team_id IN ( SELECT id FROM team, athlete WHERE team.id = athlete.team_id GROUP BY team.id HAVING COUNT(*) = 2 ) GROUP BY p1.id ORDER BY freq DESC Obviously this is a resource consuming query. Is there a way to improve it?

    Read the article

  • Algorithm for querying linearly through a non-linear list of questions

    - by JoshLeaves
    For a multiplayers trivia game, I need to supply my users with a new quizz in a desired subject (Science, Maths, Litt. and such) at the start of every game. I've generated about 5K quizzes for each subject and filled my database with them. So my 'Quizzes' database looks like this: |ID |Subject |Question +-----+------------+---------------------------------- | 23 |Science | What's water? | 42 |Maths | What's 2+2? | 99 |Litt. | Who wrote "Pride and Prejudice"? | 123 |Litt. | Who wrote "On The Road"? | 146 |Maths | What's 2*2? | 599 |Science | You know what's cool? |1042 |Maths | What's the Fibonacci Sequence? |1056 |Maths | What's 42? And so on... (Much more detailed/complex but I'll keep the exemple simple) As you can see, due to technical constraints (MongoDB), my IDs are not linear but I can use them as an increasing suite. So far, my algorithm to ensure two users get a new quizz when they play together is the following: // Take the last played quizzes by P1 and P2 var q_one = player_one.getLastPlayedQuizz('Maths'); var q_two = player_two.getLastPlayedQuizz('Maths'); // If both of them never played in the subject, return first quizz in the list if ((q_one == NULL) && (q_two == NULL)) return QuizzDB.findOne({subject: 'Maths'}); // If one of them never played, play the next quizz for the other player // This quizz is found by asking for the first quizz in the desired subject where // the ID is greater than the last played quizz's ID (if the last played quizz ID // is 42, this will return 146 following the above example database) if (q_one == NULL) return QuizzDB.findOne({subject: 'Maths', ID > q_two}); if (q_two == NULL) return QuizzDB.findOne({subject: 'Maths', ID > q_one}); // And if both of them have a lastPlayedQuizz, we return the next quizz for the // player whose lastPlayedQuizz got the higher ID if (q_one > q_two) return QuizzDB.findOne({subject: 'Maths', ID > q_one}); else return QuizzDB.findOne({subject: 'Maths', ID > q_two}); Now here comes the real problem: Once I get to the end of my database (let's say, P1's last played quizz in 'Maths' is 1056, P2's is 146 and P3 is 1042), following my algorithm, P1's ID is the highest so I ask for the next question in 'Maths' where ID is superior to 1056. There is nothing, so I roll back to the beginning of my quizz list (with a random skipper to avoid having the first question always show up). P1 and P2's last played will then be 42 and they will start fresh from the beginning of the list. However, if P1 (42) plays against P3 (1042), the resulting ID will be 1056...which P1 already played two games ago. Basically, players who just "rolled back" to the beginning of the list will be brought back to the end of the list by players who still haven't rolled back. The rollback WILL happen in the end, but it'll take time and there'll be a "bottleneck" at the beginning and at the end. Thus my question: What would be the best algorith to avoid this bottleneck and ensure players don't get stuck endlessly on the same quizzes? Also bear in mind that I've got some technical constraints: I can't get a random question in a subject (ie: no "QuizzDB.findOne({subject: 'Maths'}).skip(random());"). It's cool to skip on one to twenty records, but the MongoDB documentation warns against skipping too many documents. I would like to avoid building an array of every quizz played by each player and find the next non-played in the database with a $nin. Thanks for your help

    Read the article

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