Daily Archives

Articles indexed Wednesday June 6 2012

Page 12/17 | < Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Numpy: Sorting a multidimensional array by a multidimensional array

    - by JD Long
    Forgive me if this is redundant or super basic. I'm coming to Python/Numpy from R and having a hard time flipping things around in my head. I have a n dimensional array which I want to sort using another n dimensional array of index values. I know I could wrap this in a loop but it seems like there should be a really concise Numpyonic way of beating this into submission. Here's my example code to set up the problem where n=2: a1 = random.standard_normal(size=[2,5]) index = array([[0,1,2,4,3] , [0,1,2,3,4] ]) so now I have a 2 x 5 array of random numbers and a 2 x 5 index. I've read the help for take() about 10 times now but my brain is not groking it, obviously. I thought this might get me there: take(a1, index) array([[ 0.29589188, -0.71279375, -0.18154864, -1.12184984, 0.25698875], [ 0.29589188, -0.71279375, -0.18154864, 0.25698875, -1.12184984]]) but that's clearly reordering only the first element (I presume because of flattening). Any tips on how I get from where I am to a solution that sorts element 0 of a1 by element 0 of the index ... element n?

    Read the article

  • What to do with missing fields in sunspot-rails?

    - by chrismealy
    I'm using sunspot/rails version 2. It's working great, but I can't figure out how to handle missing fields. If I don't have latitude and longitude this code will map it to 0,0 (near Africa): searchable do text :resume, :stored => true text :city, :boost => 5 latlon(:geo) { Sunspot::Util::Coordinates.new(latitude, longitude) } end I tried using two search blocks, each with a different conditional, but sunspot just uses the first searchable block. What I want to happen is for things missing locations to still be searchable, just not by location.

    Read the article

  • Disable iOS keyboard (don't show it at all) in phonegap

    - by lashleigh
    If I were writing a native app I would try the solution given here which says: Try to implement the following method in text view's delegate: - (BOOL)textViewShouldBeginEditing:(UITextView *)textView{ return NO; } Unfortunately I need to use phonegap, so I don't have a text view to manipulate. It would be great if I could permanently suppress the keyboard in this app. We've got some custom on screen keyboard that people are supposed to use instead. So, any idea how to disable the popup keyboard completely?

    Read the article

  • Javascript errors on internet explorer with jQuery but working fine on Firefox

    - by user994319
    A quick question I'm hoping someone can help me out with. On firefox our jQuery slider is working perfectly, however on viewing with internet explorer there are some javascript errors occurring. The website is http://foscam-uk.com/index.php Hoping there is a possible solution to this. Kind Regards and Thank You! Errors: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3) Timestamp: Wed, 6 Jun 2012 22:36:43 UTC Message: Object doesn't support this property or method Line: 5653 Char: 9 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 5988 Char: 5 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 2 Char: 5 Code: 0 URI: http://foscam-uk.com/skin/frontend/default/theme316/js/scripts.js Message: Object doesn't support this property or method Line: 5736 Char: 7 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 5988 Char: 5 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 73 Char: 11 Code: 0 URI: http://foscam-uk.com/index.php

    Read the article

  • What is the equivalent of Java's .length for arrays in C#?

    - by Michael Loftus
    I'm new to C#, and I'm trying to convert this code from java into C#. static public double euclidean_2(double[] x, double[] y) { if (x.length != y.length) throw new RuntimeException("Arguments must have same number of dimensions."); double cumssq = 0.0; for (int i = 0; i < x.length; i++) cumssq += (x[i] - y[i]) * (x[i] - y[i]); return cumssq; } I know java uses .length but what is the equivalent in C# since I keep getting an error Thanks

    Read the article

  • JDBC going to the wrong address

    - by DCSoft
    When I try and connect it my mysql database with JDBC in java, it doesn't go to my web server. Here is the code String dbtime; String dbUrl = "jdbc:mysql://184.172.176.18:3306/dcsoft_dcsoft_balloon"; String dbUser = "myuser"; String dcPass = "mypass"; String dbClass = "com.mysql.jdbc.Driver"; String query = "Select * FROM users"; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(dbUrl, dbUser, dcPass); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { dbtime = rs.getString(1); System.out.println(dbtime); } //end while con.close(); } //end try catch(ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } This code is supposed to go to my web server but it gives this error java.sql.SQLException: Access denied for user 'dcsoft_dcsoft_java'@'jamesposse.force9.co.uk' (using password: YES) jamesposse.force9.co.uk is the not the address im trying to connect to I'm trying to connect to 184.172.176.18:3306. Thanks.

    Read the article

  • poplib and email module will not reloop through a message if it has alread read it

    - by user1440925
    I'm currently trying to write a script that gets messages from my gmail account but I'm noticing a problem. If poplib loops through a message in my inbox it will never loop through it again. Here is my code import poplib, string, email user = "[email protected]" password = "p0ckystyx" message = "" mail = poplib.POP3_SSL('pop.gmail.com') mail.user(user) mail.pass_(password) iMessageCount = len(mail.list()[1]) message = "" msg = mail.retr(iMessageCount) str = string.join(msg[1], "\n") frmMail = email.message_from_string(str) for part in frmMail.walk(): if part.get_content_type() == "text/plain": print part.get_payload() mail.quit() Every time I run this script it goes to the next newest email and just skips over the email that was shown last time it was run.

    Read the article

  • When can I find out the width/height of my view

    - by michael
    When is the earliest I can find out the actual (after layout) width/height of my view? I tried to do that @Override protected void onFinishInflate() { super.onFinishInflate(); w = getWidth(); h = getHeight(); } But it gives me 0. I have cases in which the view is invisible in the beginning and that programmically become visible. I think I can do that in onDraw(), but i dont' want to do that in everything I draw() something.

    Read the article

  • DependencyProperty binding not happening on initial load

    - by Ari Roth
    I'm trying to do something simple -- make a DependencyProperty and then bind to it. However, the getter doesn't appear to fire when I start up the app. (I'm guessing the solution will make me smack my head and go "Doh!", but still. :) ) Any ideas? Code-behind code: public static readonly DependencyProperty PriorityProperty = DependencyProperty.Register("Priority", typeof (Priority), typeof (PriorityControl), null); public Priority Priority { get { return (Priority)GetValue(PriorityProperty); } set { SetValue(PriorityProperty, value); } } Control XAML: <ListBox Background="Transparent" BorderThickness="0" ItemsSource="{Binding Path=Priorities}" Name="PriorityList" SelectedItem="{Binding Path=Priority, Mode=TwoWay}"> <ListBox.ItemTemplate> <DataTemplate> <Grid Height="16" Width="16"> <Border BorderBrush="Black" BorderThickness="2" CornerRadius="3" Visibility="{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected, Converter={StaticResource boolToVisibilityConverter}}" /> <Border CornerRadius="3" Height="12" Width="12"> <Border.Background> <SolidColorBrush Color="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=Content, Converter={StaticResource priorityToColorConverter}}" /> </Border.Background> </Border> </Grid> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> Binding statement: <UI:PriorityControl Grid.Column="8" Priority="{Binding Path=Priority}" VerticalAlignment="Center"/> Some other notes: Binding is in a UserControl UserControl contains the PriorityControl PriorityControl contains the DependencyProperty I've checked that the data the UserControl is getting the appropriate data -- every other binding works. If I change the selection on the PriorityControl via the mouse, everything fires as appropriate. It's just that initial setting of the value that isn't working. Priority is an enum.

    Read the article

  • How do I build a class that shares a table with multiple columns in MVC3?

    - by Barrett Kuethen
    I have a Job table public class Job { public int JobId { get; set; } public int SalesManagerId { get; set; } public int SalesRepId { get; set; } } and a Person table public class Person { public int PersonId { get; set; } public int FirstName { get; set; } public int LastName { get; set; } } My question is, how do I link the SalesManagerId to the Person (or PersonId) as well as the SalesRepId to the Person (PersonId)? The Sales Manager and Sales Rep are independent of each other. I just don't want to make 2 different lists to support the Sales Manager and Sales Rep roles. I'm new to MVC3, but it seems public virtual Person Person {get; set; } would be the way to go, but that doesn't work. Any help would be appreciated! Thanks!

    Read the article

  • Mongodb, linq driver. How to construct Contains with variable or statements

    - by Syska
    I'm using the LINQ Driver for C#, works great. Sorting a lot of properties but heres a problem I can't solve, its probebly simple. var identifierList = new []{"10", "20", "30"}; var newList = list.Where(x => identifierList.Contains(x.Identifier)); This is NOT supported ... So I could do something like: var newList = list.Where(x => x.Identifier == "10" || x.Identifier == "20" || x.Identifier == "30"); But since the list is variable ... how do I construct the above? Or are there even better alternatives? The list is of type IQueryable<MyCustomClass> For information ... this is used as a filter of alot of properties. In SQL I could have a parent - child relationship. But as I can't as the parent for the main ID I need to take all the ID's out and then construct it like this. Hopes this makes sense. If needed I will explain more.

    Read the article

  • C#/XNA Giant Memory Leak

    - by user1440926
    this is my first post here. I'm making a game in Visual Studio 2010 using XNA, and i've hit a giant memory leak. My game starts out using 17k ram and then after ten minutes it's upto 65k. I ran some memory profilers, and they all say that new instances of the String object are being created, but they aren't live. The amount of live instances of String hasn't changed at all. It's also creating instances of Char[] (which i'd expect from it), Object[], and StringBuilder. My game is pretty new but there's too much code to post here. I have no idea how to get rid of instances that aren't live, please help!

    Read the article

  • If setUpBeforeClass() fails, test failures are hidden in PHPUnit's JUnit XML output

    - by Adam Monsen
    If setUpBeforeClass() throws an exception, no failures or errors are reported in the PHPUnit's JUnit XML output. Why? Example test class: <?php class Test extends PHPUnit_Framework_TestCase { public static function setUpBeforeClass() { throw new \Exception('masks all failures in xml output'); } public function testFoo() { $this->fail('failing'); } } Command line: phpunit --verbose --log-junit out.xml Test.php Console output: PHPUnit 3.6.10 by Sebastian Bergmann. E Time: 0 seconds, Memory: 3.25Mb There was 1 error: 1) Test Exception: masks all failures in xml output /tmp/pu/Test.php:6 FAILURES! Tests: 0, Assertions: 0, Errors: 1. JUnit XML output: <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="Test" file="/tmp/phpunit-broken/Test.php"/> </testsuites> More info: $ php --version PHP 5.3.10-1ubuntu3.1 with Suhosin-Patch (cli) (built: May 4 2012 02:21:57) Copyright (c) 1997-2012 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans

    Read the article

  • MYSQL Event Scheduler DELIMITER using PHP

    - by user1440918
    I'm having an issue with my PHP code trying to create events within MySQL. I begin with creating a string like this: $sql="DELIMITER $$ CREATE EVENT `$test_name` ON SCHEDULE EVERY $time1 $sched2 STARTS '$start_date $start_time' DO BEGIN "; $sql .="INSERT INTO blah (foo,bar); "; $sql .="END$$ DELIMITER ;" mysql_query($sql,$dbh); But I keep getting Syntax Errors starting with DELIMITER $$ CREATE EVENT. Without the semicolon behind (foo,bar); the event triggers with a unexecuted payload. Any ideas on where I'm going wrong? Thanks!

    Read the article

  • Finding the index of a list item in jQuery

    - by Tim Piele
    I have an unordered list of eight items. On page load the first five <li> have default thumbnail images in them and the 6th one has a 1px by 1px placeholder image with the ID of $('#last'). When a user inserts a new image it replaces the 'src' of $('#last') with their new image. It's not the most efficient way but it works. <ul> <li><img src="img1.png" /></li> <li><img src="img2.png" /></li> <li><img src="img3.png" /></li> <li><img src="img4.png" /></li> <li><img src="img5.png" /></li> <li><img src="1px.png" id="last"/></li> <li></li> <li></li> </ul> When the user adds a new image the ID of $('#last') is removed and I use each() to find the next empty <li> and insert the 1px by 1px image in it, with an ID of $('#last') so it is ready for the next image upload. At this point I need to get the index() of the <li> that now has the 1px by 1px image in it, whose ID is $('#last'), so that I can store the index in the session, so when a user comes back to the page the $('#last') ID is still set and ready to accept another image. How do I get the index of the <li> with that image in it, since it was set after page load? Is there a way to use delegate() or on() to get it? i.e. how do I get the index of an element that was set after page load?

    Read the article

  • login not working when changing from mysql to mysqli

    - by user1438647
    I have a code below where it logs a teacher in by matching it's username and password in the database, if correct, then log in, if incorrect, then display a message. <?php session_start(); $username="xxx"; $password="xxx"; $database="mobile_app"; $link = mysqli_connect('localhost',$username,$password); mysqli_select_db($link, $database) or die( "Unable to select database"); foreach (array('teacherusername','teacherpassword') as $varname) { $$varname = (isset($_POST[$varname])) ? $_POST[$varname] : ''; } ?> <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" id="teachLoginForm"> <p>Username</p><p><input type="text" name="teacherusername" /></p> <!-- Enter Teacher Username--> <p>Password</p><p><input type="password" name="teacherpassword" /></p> <!-- Enter Teacher Password--> <p><input id="loginSubmit" type="submit" value="Login" name="submit" /></p> </form> <?php if (isset($_POST['submit'])) { $query = " SELECT * FROM Teacher t WHERE (t.TeacherUsername = '".mysqli_real_escape_string($teacherusername)."') AND (t.TeacherPassword = '".mysqli_real_escape_string($teacherpassword)."') "; $result = mysqli_query($link, $query); $num = mysqli_num_rows($result); $loged = false; while($row = mysqli_fetch_array($result)) { if ($_POST['teacherusername'] == ($row['TeacherUsername']) && $_POST['teacherpassword'] == ($row['TeacherPassword'])) { $loged = true; } $_SESSION['teacherforename'] = $row['TeacherForename']; $_SESSION['teachersurname'] = $row['TeacherSurname']; $_SESSION['teacherusername'] = $row['TeacherUsername']; } if ($loged == true){ header( 'Location: menu.php' ) ; }else{ echo "The Username or Password that you Entered is not Valid. Try Entering it Again."; } mysqli_close($link); } ?> Now the problem is that even if the teacher has entered in the correct username and password, it still doesn't let the teacher log in. When the code above was the old mysql() code, it worked fine as teacher was able to login when username and password match, but when trying to change the code into mysqli then it causes login to not work even though username and password match. What am I doing wrong?

    Read the article

  • Multi-Column Join in Hibernate/JPA Annotations

    - by bowsie
    I have two entities which I would like to join through multiple columns. These columns are shared by an @Embeddable object that is shared by both entities. In the example below, Foo can have only one Bar but Bar can have multiple Foos (where AnEmbeddableObject is a unique key for Bar). Here is an example: @Entity @Table(name = "foo") public class Foo { @Id @Column(name = "id") @GeneratedValue(generator = "seqGen") @SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1) private Long id; @Embedded private AnEmbeddableObject anEmbeddableObject; @ManyToOne(targetEntity = Bar.class, fetch = FetchType.LAZY) @JoinColumns( { @JoinColumn(name = "column_1", referencedColumnName = "column_1"), @JoinColumn(name = "column_2", referencedColumnName = "column_2"), @JoinColumn(name = "column_3", referencedColumnName = "column_3"), @JoinColumn(name = "column_4", referencedColumnName = "column_4") }) private Bar bar; // ... rest of class } And the Bar class: @Entity @Table(name = "bar") public class Bar { @Id @Column(name = "id") @GeneratedValue(generator = "seqGen") @SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1) private Long id; @Embedded private AnEmbeddableObject anEmbeddableObject; // ... rest of class } Finally the AnEmbeddedObject class: @Embeddable public class AnEmbeddedObject { @Column(name = "column_1") private Long column1; @Column(name = "column_2") private Long column2; @Column(name = "column_3") private Long column3; @Column(name = "column_4") private Long column4; // ... rest of class } Obviously the schema is poorly normalised, it is a restriction that AnEmbeddedObject's fields are repeated in each table. The problem I have is that I receive this error when I try to start up Hibernate: org.hibernate.AnnotationException: referencedColumnNames(column_1, column_2, column_3, column_4) of Foo.bar referencing Bar not mapped to a single property I have tried marking the JoinColumns are not insertable and updatable, but with no luck. Is there a way to express this with Hibernate/JPA annotations? Thank you.

    Read the article

  • Android ndk-build command does nothing

    - by James
    I have a similar question to that posted here: Android NDK: why ndk-build doesn't generate .so file and a new libs folder in Eclipse? ...though I am running Windows 7, not Mac os. Essentially the ndk-build command is run, gives no error but doesn't create an .so file (also, since I'm on windows this should create a .dll and not an .so?). I tried running the command from the root, jni, src folders etc. but got the same result; cmd just returns to the prompter after a few seconds. I ran it again from the jni folder with NDK_LOG=1 parameter to see what was happening. Here is a portion of the transcript of the log results after running ndk-build in the jni folder (after it successfully identified the platform, etc.)... Android NDK: Looking for jni/Android.mk in /workspace/NdkFooActivity/jni Android NDK: Looking for jni/Android.mk in /workspace/NdkFooActivity Android NDK: Found it ! Android NDK: Found project path: /workspace/NdkFooActivity Android NDK: Ouput path: /workspace/NdkFooActivity/obj Android NDK: Parsing /cygdrive/c/android-ndk-r8/build/core/default-application.mk Android NDK: Found APP_PLATFORM=android-15 in /workspace/NdkFooActivity/project.properties Android NDK: Application local targets unknown platform 'android-15' Android NDK: Switching to android-14 Android NDK: Using build script /workspace/NdkFooActivity/jni/Android.mk Android NDK: Application 'local' is not debuggable Android NDK: Selecting release optimization mode (app is not debuggable) Android NDK: Adding import directory: /cygdrive/c/android-ndk-r8/sources Android NDK: Building application 'local' for ABI 'armeabi' Android NDK: Using target toolchain 'arm-linux-androideabi-4.4.3' for 'armeabi' ABI Android NDK: Looking for imported module with tag 'cxx-stl/system' Android NDK: Probing /cygdrive/c/android-ndk-r8/sources/cxx-stl/system/Android.mk Android NDK: Found in /cygdrive/c/android-ndk-r8/sources/cxx-stl/system Android NDK: Cygwin dependency file conversion script: ...after which point it just runs the script mentioned in the last line, then terminates. Any ideas? Thanks!

    Read the article

  • android error NoSuchElementException

    - by Alexander
    I have returned a cursor string but it contains a delimiter. The delimiter is . I have the string quest.setText(String.valueOf(c.getString(1)));I want to turn the into a new line. What is the best method to achieve this task in android. I understand there is a way to get the delimeter. I want this to achieved for each record. I can itterate through record like so. Cursor c = db.getContact(2); I tried using a string tokenizer but it doesnt seem to work. Here is the code for the tokenizer. I tested it in just plain java and it works without errors. String question = c.getString(1); // quest.setText(String.valueOf(c.getString(1))); //quest.setText(String.valueOf(question)); StringTokenizer st = new StringTokenizer(question,"<ENTER>"); //DisplayContact(c); // StringTokenizer st = new StringTokenizer(question, "=<ENTER>"); while(st.hasMoreTokens()) { String key = st.nextToken(); String val = st.nextToken(); System.out.println(key + "\n" + val); } I then tried running it in android. Here is the error log 06-06 22:31:55.251: E/AndroidRuntime(537): FATAL EXCEPTION: main 06-06 22:31:55.251: E/AndroidRuntime(537): java.util.NoSuchElementException 06-06 22:31:55.251: E/AndroidRuntime(537): at java.util.StringTokenizer.nextToken(StringTokenizer.java:208) 06-06 22:31:55.251: E/AndroidRuntime(537): at alex.android.test.database.quiz.TestdatabasequizActivity$1.onClick(TestdatabasequizActivity.java:95) 06-06 22:31:55.251: E/AndroidRuntime(537): at android.view.View.performClick(View.java:3511) 06-06 22:31:55.251: E/AndroidRuntime(537): at android.view.View$PerformClick.run(View.java:14105) 06-06 22:31:55.251: E/AndroidRuntime(537): at android.os.Handler.handleCallback(Handler.java:605) 06-06 22:31:55.251: E/AndroidRuntime(537): at android.os.Handler.dispatchMessage(Handler.java:92) 06-06 22:31:55.251: E/AndroidRuntime(537): at android.os.Looper.loop(Looper.java:137) 06-06 22:31:55.251: E/AndroidRuntime(537): at android.app.ActivityThread.main(ActivityThread.java:4424) 06-06 22:31:55.251: E/AndroidRuntime(537): at java.lang.reflect.Method.invokeNative(Native Method) 06-06 22:31:55.251: E/AndroidRuntime(537): at java.lang.reflect.Method.invoke(Method.java:511) 06-06 22:31:55.251: E/AndroidRuntime(537): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 06-06 22:31:55.251: E/AndroidRuntime(537): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 06-06 22:31:55.251: E/AndroidRuntime(537): at dalvik.system.NativeStart.main(Native Method) This is the database query public Cursor getContact(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, question, possibleAnsOne,possibleAnsTwo, possibleAnsThree,realQuestion,UR}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); }

    Read the article

  • Finding open contiguous blocks of time for every day of a month, fast

    - by Chris
    I am working on a booking availability system for a group of several venues, and am having a hard time generating the availability of time blocks for days in a given month. This is happening server-side in PHP, but the concept itself is language agnostic -- I could be doing this in JS or anything else. Given a venue_id, month, and year (6/2012 for example), I have a list of all events occurring in that range at that venue, represented as unix timestamps start and end. This data comes from the database. I need to establish what, if any, contiguous block of time of a minimum length (different per venue) exist on each day. For example, on 6/1 I have an event between 2:00pm and 7:00pm. The minimum time is 5 hours, so there's a block open there from 9am - 2pm and another between 7pm and 12pm. This would continue for the 2nd, 3rd, etc... every day of June. Some (most) of the days have nothing happening at all, some have 1 - 3 events. The solution I came up with works, but it also takes waaaay too long to generate the data. Basically, I loop every day of the month and create an array of timestamps for each 15 minutes of that day. Then, I loop the time spans of events from that day by 15 minutes, marking any "taken" timeslot as false. Remaining, I have an array that contains timestamp of free time vs. taken time: //one day's array after processing through loops (not real timestamps) array( 12345678=>12345678, // <--- avail 12345878=>12345878, 12346078=>12346078, 12346278=>false, // <--- not avail 12346478=>false, 12346678=>false, 12346878=>false, 12347078=>12347078, // <--- avail 12347278=>12347278 ) Now I would need to loop THIS array to find continuous time blocks, then check to see if they are long enough (each venue has a minimum), and if so then establish the descriptive text for their start and end (i.e. 9am - 2pm). WHEW! By the time all this looping is done, the user has grown bored and wandered off to Youtube to watch videos of puppies; it takes ages to so examine 30 or so days. Is there a faster way to solve this issue? To summarize the problem, given time ranges t1 and t2 on day d, how can I determine the remaining time left in d that is longer than the minimum time block m. This data is assembled on demand via AJAX as the user moves between calendar months. Results are cached per-page-load, so if the user goes to July a second time, the data that was generated the first time would be reused. Any other details that would help, let me know. Edit Per request, the database structure (or the part that is relevant here) *events* id (bigint) title (varchar) *event_times* id (bigint) event_id (bigint) venue_id (bigint) start (bigint) end (bigint) *venues* id (bigint) name (varchar) min_block (int) min_start (varchar) max_start (varchar)

    Read the article

  • Calculate new position of player

    - by user1439111
    Edit: I will summerize my question since it is very long (Thanks Len for pointing it out) What I'm trying to find out is to get a new position of a player after an X amount of time. The following variables are known: - Speed - Length between the 2 points - Source position (X, Y) - Destination position (X, Y) How can I calculate a position between the source and destion with these variables given? For example: source: 0, 0 destination: 10, 0 speed: 1 so after 1 second the players position would be 1, 0 The code below works but it's quite long so I'm looking for something shorter/more logical ====================================================================== I'm having a hard time figuring out how to calculate a new position of a player ingame. This code is server sided used to track a player(It's a emulator so I don't have access to the clients code). The collision detection of the server works fine I'm using bresenham's line algorithm and a raycast to determine at which point a collision happens. Once I deteremined the collision I calculate the length of the path the player is about to walk and also the total time. I would like to know the new position of a player each second. This is the code I'm currently using. It's in C++ but I am porting the server to C# and I haven't written the code in C# yet. // Difference between the source X - destination X //and source y - destionation Y float xDiff, yDiff; xDiff = xDes - xSrc; yDiff = yDes - ySrc; float walkingLength = 0.00F; float NewX = xDiff * xDiff; float NewY = yDiff * yDiff; walkingLength = NewX + NewY; walkingLength = sqrt(walkingLength); const float PI = 3.14159265F; float Angle = 0.00F; if(xDes >= xSrc && yDes >= ySrc) { Angle = atanf((yDiff / xDiff)); Angle = Angle * 180 / PI; } else if(xDes < xSrc && yDes >= ySrc) { Angle = atanf((-xDiff / yDiff)); Angle = Angle * 180 / PI; Angle += 90.00F; } else if(xDes < xSrc && yDes < ySrc) { Angle = atanf((yDiff / xDiff)); Angle = Angle * 180 / PI; Angle += 180.00F; } else if(xDes >= xSrc && yDes < ySrc) { Angle = atanf((xDiff / -yDiff)); Angle = Angle * 180 / PI; Angle += 270.00F; } float WalkingTime = (float)walkingLength / (float)speed; bool Done = false; float i = 0; while(i < walkingLength) { if(Done == true) { break; } if(WalkingTime >= 1000) { Sleep(1000); i += speed; WalkTime -= 1000; } else { Sleep(WalkTime); i += speed * WalkTime; WalkTime -= 1000; Done = true; } if(Angle >= 0 && Angle < 90) { float xNew = cosf(Angle * PI / 180) * i; float yNew = sinf(Angle * PI / 180) * i; float NewCharacterX = xSrc + xNew; float NewCharacterY = ySrc + yNew; } I have cut the last part of the loop since it's just 3 other else if statements with 3 other angle conditions and the only change is the sin and cos. The given speed parameter is the speed/second. The code above works but as you can see it's quite long so I'm looking for a new way to calculate this. btw, don't mind the while loop to calculate each new position I'm going to use a timer in C# Thank you very much

    Read the article

  • How to know file type without extension

    - by Ayusman
    While trying to come-up with a servlet based application to read files and manipulate them (image type conversion) here is a question that came up to me: Is it possible to inspect a file content and know the filetype? Is there a standard that specifies that each file MUST provide some type of marker in their content so that the application will not have to rely on the file extension constraints? Consider an application scenario: I am creating an application that will be able to convert different file formats to a set of output formats. Say user uploads an PDF, my application can suggest that the possible conversion formats are microsoft word or TIFF or JPEG etc. As my application will gradually support different file formats (over a period of time), I want my application to inspect the input file instead of having the user to specify the format. And suggest to user the possible formats of output. I understand this is an open ended, broad question. Please let me know if it needs to be modified. Thanks, Ayusman

    Read the article

  • Is Innovation Dead?

    - by wulfers
    My question is has innovation died?  For large businesses that do not have a vibrant, and fearless leadership (see Apple under Steve jobs), I think is has.  If you look at the organizational charts for many of the large corporate megaliths you will see a plethora of middle managers who are so risk averse that innovation (any change involves risk) is choked off since there are no innovation champions in the middle layers.  And innovation driven top down can only happen when you have a visionary in the top ranks, and that is also very rare.So where is actual innovation happening, at the bottom layer, the people who live in the trenches…   The people who live for a challenge. So how can big business leverage this innovation layer?  Remove the middle management layer.   Provide an innovation champion who has an R&D budget and is tasked with working with the bottom layer of a company, the engineers, developers  and business analysts that live on the edge (Where the corporate tires meet the road). Here are two innovation failures I will tell you about, and both have been impacted by a company so risk averse it is starting to fail in its primary business ventures: This company initiated an innovation process several years ago.  The process was driven companywide with team managers being the central points of collection of innovative ideas.  These managers were given no budget to do anything with these ideas.  There was no process or incentive for these managers to drive it about their team.  This lasted close to a year and the innovation program slowly slipped into oblivion…. A second example:  This same company failed an attempt to market a consumer product in a line where there was already a major market leader.  This product was under development for several years and needed to provide some major device differentiation form the current market leader.  This same company had a large Lead Technologist community made up of real innovators in all areas of technology.  Did this same company leverage the skills and experience of this internal community,   NO!!! So to wrap this up, if large companies really want to survive, then they need to start acting like a small company.  Support those innovators and risk takers!  Reward them by implementing their innovative ideas.  Champion (from the top down) innovation (found at the bottom) in your companies.  Remember if you stand still you are really falling behind.Do it now!  Take a risk!

    Read the article

  • Getting 502 instead of 503 when all backend servers are down running HAProxy behind Apache

    - by scarba05
    I'm testing running HAProxy as a dedicated load balancer behind Apache 2.2, replacing our current configuration where we use Apache's load balancer. In our current, Apache only, set-up if all the backend (origin) servers are down Apache will serve a 503 service unavailable message. With HAProxy I get a 502 bad gateway response. I'm using a simple reverse proxy rewrite rule in Apache RewriteRule ^/(.*) http://127.0.0.1:8000/$1 [last,proxy] In HAProxy I have the following (running in default tcp mode) defaults log global option tcp-smart-accept timeout connect 7s timeout client 60s timeout queue 120s timeout server 60s listen my_server 127.0.0.1:8000 balance leastconn server backend1 127.0.0.1:8001 check observe layer4 maxconn 2 server backend1 127.0.0.1:8001 check observe layer4 maxconn 2 Testing connecting directly to the load balancer when the backend servers are down: [root@dev ~]# wget http://127.0.0.1:8000/ test.html --2012-05-28 11:45:28-- http://127.0.0.1:8000/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... No data received. So presumably this is down to the fact that HAProxy accepts the connection and then closes it.

    Read the article

  • Setting up a localhost mail server on Mac OSX

    - by Thom
    I asked this over on stackoverflow. They pointed me here. I would love to be able to test php webapps that require emailing registration info etc. on my mac. I downloaded a version of CommuniGate Pro. I need to mail either to an account inside or outside (whichever is best) of the localhost. Again this would be used for testing purposes to verify and debug my code prior to uploading to a hosting service. Any ideas, help and/or examples would be very much appreciated. If it would be easier I could go over to Windows XP. That would just mean setting up wamp and transfering my files over from the mac side via dropbox. I got the local mailserver to work so I can send emails between accounts. However, I cannot seem to get the php code to work. I know that I am missing something. I see where this has been asked before. I want to add that I am using xampp. In Mac OS 10.6.8. I tried changing the php.ini SMTP command to macintosh-3.local. <?php function email($to, $subject, $body, $headers) { $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'From: <[email protected]>' . "\r\n"; mail($to, $subject, $body, $headers); } ?>

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >