text
stringlengths
8
267k
meta
dict
Q: takePicture callback data is null Is the Camera.takePicture callback for raw data null when running in emulator environment? I got the CameraSurface method out of the WWW, so it should be correct. A: Before calling takePicture you have to provide a buffer large enough to hold the raw image data. (detailed here). For setting the buffer, use the addCallbackBuffer method. A: This issue seems to be related to the raw-data callback only. Using the picture callback which retrieves a jpeg solves the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Issue with HTC Desire android app So I have an object called ExtendedCanvas that contains this following field: private static final Status status = new Status(); This object contains a method named advance() that is called from a thread started in a surfaceCreated() method (don't know if this info is of any meaning but I try to be specific). And in this method the first thing is if (status.FirstTime == false) { And this throws a NullPointerException no matter what I do (FirstTime is a boolean, status is null), but this only on HTC Desire (so far at least, in emulator works ok always). I have no idea how something static final that has been initialized can be null... Status is accesed previously from the surfaceCreated thread and there it works. But after creating another thread and accessing status it says it's null. Has anyone ever encountered something like this? Could it be an optimization problem when the dalvik bytecode gets compiled down to native in HTC Desire?
{ "language": "en", "url": "https://stackoverflow.com/questions/7562526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Insert a whole element into another element, not just its inner HTML I'm trying to figure out how to use jQuery to construct HTML as sanely as possible. As far as I can tell, this should produce <div><span>Alice</span></div>, but instead produces <div>[object Object]</div>: post = $("<div>"); username = $("<span>").html("Alice"); post.append(username); I've found that replacing the last line with post.append(username.html()) gets me closer to my goal, but it omits the <span> tags if I do it that way. How do I insert a child element with the surrounding tags, and without writing out "<span>" + username + "</span>", which seems like a novice approach to the task? EDIT: Stupid mistake. The snippet I posted above was excessively simplified; I was really trying to do post.append(username + another_span_element) in my code. Obviously I can't append objects like that. I've changed it to post.append(username); post.append(another_span_element); and now it works fine. Durr! A: Works for me: $("<div>").append($("<span>").html("Alice"))[0].outerHTML == "<div><span>Alice</span></div>" A: Is there a reason for not doing: $('<div><span>Alice</span></div>').appendTo('body'); or var username = "Alice"; $('<div><span id="user"></span></div>').appendTo('body'); $(username).appendTo('#user'); or var username = "Alice"; $('<div><span id="user"></span></div>').appendTo('body'); $('#user').html(username); or var username = "Alice"; $('<div><span id="user"></span></div>').appendTo('body'); $('#user').text(username); or any of the other 200 options? A: What you're aiming for is done with the text() method: post = $("<div>"); username = $("<span>").text("Alice"); post.append(username); Example here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL: VBO functions are not defined I'm trying to use OpenGL VBO's, but the functions associated with their use, glGenBuffersARB() for instance, are all undefined. Immediate mode functions are fine of course, it's only these. I'm using VS2010, with the SFML library. One of the include headers in that library includes both <GL/gl.h> and <GL/glu.h>, and the executable is linked against glu32.lib and opengl32.lib Why are only these functions missing, and how would I be able to include their use? A: GLEW will define them, as will other GL extension libraries. Information can be found here: http://www.opengl.org/resources/features/OGLextensions/ Using an extension that includes new function call entry-points is harder in Win32 because you must first request the function pointer from the OpenGL ICD driver before you can call the OpenGL function. GLEW does this for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What problems could warning C4407 cause? I got some warnings by using pure virtual interfaces on some MFC CWnd derived objects through multiple inheritance. I believe it's caused by defining the methods which need to be implemented for the message map. warning C4407: cast between different pointer to member representations, compiler may generate incorrect code That sounds like a bit more than a warning, more like something that might cause heap corruption. So is there another way to do something similar to below that won't cause the MFC dynamic downcast macros to choke anymore than usual? class ISomeInterface { public: virtual LRESULT OnSomeRegisteredMessage(WPARAM wp, LPARAM lp) = 0; }; class CSomeCoolWnd : public CWnd, public ISomeInterface { public: LRESULT OnSomeRegisteredMessage(WPARAM wp, LPARAM lp); }; BEGIN_MESSAGE_MAP(CSomeCoolWnd , CWnd) ON_REGISTERED_MESSAGE(WM_USER_DEFINED, &CSomeCoolWnd::OnSomeRegisteredMessage) END_MESSAGE_MAP() The only thing I've come up with is commenting out the message handlers from the interfaces and leaving comments telling the consumer that they should implement them. However it would be nice to enforce that through a compiler error rather than letting them use an interface and get unexpected results at runtime from things being missing. A: An excellent description of the different representations of pointer-to-member values can be found at the article Member Function Pointers and the Fastest Possible C++ Delegates. Essentially, all the different inheritance types can require the use of different member function pointer representations. This is compiler-specific and the article talks about a number of different compilers (up to 2005 when the article was written). Evidently your use of multiple inheritance with virtual functions may require a different representation than a simple pointer-to-member function. There's probably a cast somewhere in ON_REGISTERED_MESSAGE() that isn't visible in the code you posted. A: Try to use something like this: class ISomeInterface { public: virtual LRESULT OnSomeRegisteredMessage(WPARAM wp, LPARAM lp) = 0; }; class CSomeCoolWnd : public CWnd, public ISomeInterface { public: LRESULT OnSomeRegisteredMessage(WPARAM wp, LPARAM lp); }; typedef void (CSomeCoolWnd::*FNMETHOD) (WPARAM, LPARAM); FNMETHOD method = &CSomeCoolWnd::OnSomeRegisteredMessage; BEGIN_MESSAGE_MAP(CSomeCoolWnd, CWnd) ON_REGISTERED_MESSAGE(WM_USER_DEFINED, method) END_MESSAGE_MAP()
{ "language": "en", "url": "https://stackoverflow.com/questions/7562534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: RTOS: windows ce: can I perform all my calculations in kernel mode for a PID control loop? In Windows CE, can I do all my calucation for a PID(Proportional-Integral-Derivative) control loop in "kernel mode" and avoid using "user mode"? I will transfering data over TCP=IP to another machine for the end result to keep the system in "kernel mode". My understanding is that switching from "kernel mode" to "user mode" and vice versa costs time..ie 40us round trip. A: I think you can do that, you should call SetKMode function to put your thread out or in of kernel mode. More details in these two blog posts from CE team: What is Kernel Mode? and Inside Windows CE API Calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CLLocationManager "turn on location services..." alertview customization ios I know that I can't change the title or the buttons for this alertview, but i've seen numerous apps that changed the message of the alert view Something like this Also, I have the Bump API in my app so everytime the popup shows, it says "Bump uses your location to help determine whom you are bumping." and I don't want that displayed when they first use my app. Does anybody know how I can change the message or change bump's message? Thanks A: To change the message of the alert, use the "purpose" property of CLLocationManager. Check the docs: http://developer.apple.com/library/IOs/#documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html A: I'm not sure how the Bump API works, but if you are just importing all the classes you need, you should be able to edit the location services message. Otherwise, one option would be to request location access before calling the Bump API's to get permission for your app. Once Bump checks, it will already have permission and skip presenting its own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework Code First MySql Pluralizing Tables I am using the Microsoft Entity Framework with code first to manage my data (with MySQL). I have defined a POCO object, however, when I try to add data it says table Users doesn't exist. I looked in the DB and it created table User not Users. How can I remedy this? It is driving me nuts! Thanks! public class User { [Key,Required] public int UserId { get; set; } [StringLength(20), Required] public string UserName { get; set; } [StringLength(30), Required] public string Password { get; set; } [StringLength(100), Required] public string EmailAddress { get; set; } [Required] public DateTime CreateDate { get; set; } [Required] public bool IsActive { get; set; } } A: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace YourNamespace { public class DataContext : DbContext { protected override void OnModelCreating(DbModelBuilder dbModelBuilder) { dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } public DbSet<User> User { get; set; } } } A: I have not used MySQL with EF yet but regardless I think the solution is unbias. You need to turn off Pluralize Table Convention. using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db; public class MyDbContext: DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } Now EF will look for the literal of your object name to the table name. Some great video tutorials are at http://msdn.microsoft.com/en-us/data/aa937723 under the Continue Learning Entity Framework. For additional learning experience, you can not specify the above but rather explicitly map the object 'user' to the table 'user'. Additional References: http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx A: You can put an attribute on the class telling the name of the table: [Table("Users")] public class User { //... } ...or you could use the fluent API. To do this you will override the OnModelCreating method in your DbContext class. public class MyDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<User>().Map(t => t.ToTable("Users")); } } In future versions of EF, we've been promised the ability to write our own conventions. Thats not in there yet as of version 4.1... (Haven't tried it with MySQL...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: JSON filtering attributes What is the best way to filter JSON nested keys and delete them? For example: { "id" : "1", "key1" : "val1", "key2" : "val2", "name" : "someone", "age" : 39, "data" : [ { "id" : "1234", "key1" : "val1", "key2" : "val2", "name" : "someone", "age" : 39 }, { "id" : "1234", "key1" : "val1", "key2" : "val2", "name" : "someone", "age" : 39 } ] } To get the following JSON by deleting all key1 and key2 items recursively: { "id" : "1", "name" : "someone", "age" : 39, "data" : [ { "id" : "1234", "name" : "someone", "age" : 39 }, { "id" : "1234", "name" : "someone", "age" : 39 } ] } Thanks. A: Something like this should work: function deleteRecursive(data, key) { for(var property in data) { if(data.hasOwnProperty(property)) { if(property == key) { delete data[key]; } else { if(typeof data[property] === "object") { deleteRecursive(data[property], key); } } } } } Fiddle here A: Assuming this is the JSON for an object called, say, people, something like this should work: function objWithoutPropsIDontLike(obj, propsIDontLike) { // check to make sure the given parameter is an object if(typeof obj == "object" && obj !== null) { // typeof null gives "object" ಠ_ಠ // for every property name... (see note on Object.keys() and // Array.forEach() below) obj.keys().forEach(function(prop) { // Test if the property name is one of the ones you don't like // (Array.indexOf() returns -1 if the item isn't found in the array). if(propsIDontLike.indexOf(prop) >= 0) { // if it is, nuke it delete obj[prop]; } else if(obj[prop]) { // if it isn't, recursively filter it obj[prop] = filterPropsIDontLike(obj[prop], propsIDontLike); } }); } // There is no else { ... }; if the thing given for "obj" isn't an object // just return it as-is. return obj; } var propsIDontLike = [ 'key1', 'key2' ]; people = objWithoutPropsIDontLike(people, propsIDontLike); Note: Object.keys() and Array.forEach() aren't available in Internet Explorer < 9. Happily MDC provides working polyfills for both: Object.keys(), Array.forEach(). A: Your question contains your answer: recursively! Your base cases are the "primitive" JSON types: strings and numbers. These remain unchanged. For arrays, you apply the operation to each element of the array, returning a new array. The interesting case is objects. Here, for each key-value pair, you apply the operation to each value (but ignore those whose key is one you would like to "delete") and write them into a new object. As an (off the cuff) example, using jQuery: var removeKey(object, key){ if(typeof(object)==='number' || typeof(object)==='string'){ return object; } else if(typeof(object)==='object'){ var newObject = {}; $.each(object, function(k, value) { if(k!==key){ newObject[k] = removeKey(value, key); } }); return newObject; } else { // Oh dear, that wasn't really JSON! } }; If you want to remove more than one key, adjust the second parameter and condition in the recursive case as you see fit. NOTE This is a non-destructive, which may or may not be what you need; the other answer (by Vivin Paliath) has a destructive version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting Privacy Settings using the Facebook API I am working with the Facebook API for C#. I am unable to find any reference to changing privacy settings using the API. I've looked at a lot of different places, with no success. Could anyone guide me in the right direction? Thanks! A: You can't. Only through the official channels can users change their privacy settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Setting the Item property of a Collection in VBA I'm surprised at how hard this has been to do but I imagine it's a quick fix so I will ask here (searched google and documentation but neither helped). I have some code that adds items to a collection using keys. When I come across a key that already exists in the collection, I simply want to set it by adding a number to the current value. Here is the code: If CollectionItemExists(aKey, aColl) Then 'If key already has a value 'add value to existing item aColl(aKey).Item = aColl(aKey) + someValue Else 'add a new item to the collection (aka a new key/value pair) mwTable_ISO_DA.Add someValue, aKey End If The first time I add the key/value pair into the collection, I am adding an integer as the value. When I come across the key again, I try to add another integer to the value, but this doesn't work. I don't think the problem lies in any kind of object mis-match or something similar. The error message I currently get is Runtime Error 424: Object Required A: Dictionaries are more versatile and more time efficient than Collections. If you went this route you could run an simple Exists test on the Dictionary directly below, and then update the key value Patrick Matthews has written an excellent article on dictionaries v collections Sub Test() Dim MyDict Set MyDict = CreateObject("scripting.dictionary") MyDict.Add "apples", 10 If MyDict.exists("apples") Then MyDict.Item("apples") = MyDict.Item("apples") + 20 MsgBox MyDict.Item("apples") End Sub A: You can't edit values once they've been added to a collection. So this is not possible: aColl.Item(aKey) = aColl.Item(aKey) + someValue Instead, you can take the object out of the collection, edit its value, and add it back. temp = aColl.Item(aKey) aColl.Remove aKey aColl.Add temp + someValue, aKey This is a bit tedious, but place these three lines in a Sub and you're all set. Collections are more friendly when they are used as containers for objects (as opposed to containers for "primitive" variables like integer, double, etc.). You can't change the object reference contained in the collection, but you can manipulate the object attached to that reference. On a side note, I think you've misunderstood the syntax related to Item. You can't say: aColl(aKey).Item. The right syntax is aColl.Item(aKey), or, for short, aColl(aKey) since Item is the default method of the Collection object. However, I prefer to use the full, explicit form... A: I think you need to remove the existing key-value pair and then add the key to the collection again but with the new value
{ "language": "en", "url": "https://stackoverflow.com/questions/7562546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: string array from c# to javascript example not working i'm using asp.net web form fx3.5 and i'm trying to get my server-side string array into my javascript. i found a simple example that claims to work but it doesn't for me. temp variable is not recognized in ().Serialize(temp); Here's the reference article <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ShelterExpress.UserInterface.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server" language="c#"> string[] temp; int lengthOfTemp; public string tempJSON = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(temp); </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> A: <script runat="server" language="c#"> string[] temp; int lengthOfTemp; public string tempJSON; protected override void OnLoad(EventArgs e)//you have to initialize your temp and tempJSON in a method { base.OnLoad(e); temp = new string[] { "Hi", ",", "ojlovecd" };//Initialize your temp here tempJSON = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(temp); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7562558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android-adding tabs in view flipper I am developing an android application in which I have creted a TabActivity. For each tab I am using a separate activity and a separate layout file. Actually this activity is a details screen which shows customer information. The user can click on an item in a listview activity in order to see customer's detailed info in the tab acticity. There he can use navigation buttons to navigate through the customers In a few words, if the listview displays 10 records and the user clicks on the first item the customer details.tabactivity opens and displays detailed info. Using the navigation butons the user can see the next or previous record. Now, I would like to use a viewflipper in the details screen in order to use animations while navigating through the records and in the end. to use fling gestures instead of buttons. Nevertheless I haven't found a proper example of how to add a tabhost/tabactivity in the flipper. I also thought to create the tabs using one layout in order to add it to the viewflipper but then I have no way to create the tabs inside the activity that hosts the viewfliper. Any help would be apreciated. Thank you in advance. ps. I will create a basic app of what I am talking and upload if that would be helpful A: The ViewPager may be more appropriate for what you are trying to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determine if a file is script or not I am wondering that how can I Use the file command and determine if a file is a script or not.for example in usr bin I want to know which file is script or not. actually i don't want write any script just i need a command for determine that. A: This should work (assuming that you're using BASH): for f in `ls`; do file $f|grep "executable"; done Update- I just validated that this works for C shell scripts, BASH, Perl, and Ruby. It also ignores file permissions (meaning that even if a file doesn't have the executable bit set, it still works). This seems to be do to the file command looking for a command interpreter (bash, perl, etc…) A: file can't guarantee to tell you anything about a text file, if it doesn't know how to interpret it. You may need to do a combination of things. jschorr's answer should probably work for the stuff in /bin, but another way to test a file might be to check whether a text file is executable. stat -c "%A" myfilename | grep x If that returns anything, then your file has execute permissions on it. So if file gets you a description that tells you it's plain text (like "ASCII text"), and there are execute permissions on the file, then it's a pretty good bet that it's a script file. Not perfect, but I don't think anything will be. A: You can certainly trust file to find any script in the directory you specify: file /usr/bin/* | grep script Or, if you prefer to do it yourself and you are using bash you can do: for f in /usr/bin/*; do r=$(head -1 $f | grep '^#! */') && echo "$f: $r"; done which uses the shebang to determine the interpreter and thus the script entity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Mercurial clone cleanup to match upstream I have a hg clone of a repository into which I have done numerous changes locally over a few months and pushed them to my clone at google code. Unfortunately as a noob I committed a whole bunch of changes on the default branch. Now I would like to make sure my current default is EXACTLY as upstream and then I can do proper branching off default and only working on the branches.. However how do I do that cleanup though? For reference my clone is http://code.google.com/r/mosabua-roboguice/source/browse PS: I got my self into the same problem with git and got that cleaned up: Cleanup git master branch and move some commit to new branch? A: First, there's nothing wrong with committing on the default branch. You generally don't want to create a separate named branch for every task in Mercurial, because named branches are forever. You might want to look at the bookmark feature for something closer to git branches ("hg help bookmarks"). So if the only thing wrong with your existing changesets is that they are on the default branch, then there really is nothing wrong with them. Don't worry about it. However, if you really want to start afresh, the obvious, straightforward thing to do is reclone from upstream. You can keep your messy changesets by moving the existing repo and recloning. Then transplant the changesets from the old repo into the new one on a branch of your choosing. If you don't want to spend the time/bandwidth for a new clone, you can use the (advanced, dangerous, not for beginners) strip command. First, you have to enable the mq extension (google it or see the manual -- I'm deliberately not explaining it here because it's dangerous). Then run hg strip 'outgoing("http://upstream/path/to/repo")' Note that I'm using the revsets feature added in Mercurial 1.7 here. If you're using an older version, there's no easy way to do this. A: Preface - all history changes have sense only for non-published repos. You'll have to push to GoogleCode's repo from scratch after editing local history (delete repo on GC, create empty, push) - otherwise you'll gust get one more HEAD in default branch Manfred Easy (but not short) way - default only+MQ * *as Greg mentioned, install MQ *move all your commits into MQ-patches on top of upstream code *leave your changes as pathes forever *check, edit if nesessary and re-integrate patches after each upstream pull (this way your own CG-repo without MQ-patches will become identical to upstream) More complex - MQ in the middle + separate branches * *above *above *create named branch, switch to it *"Finish" patches *Pull upstream, merge with your branch changes (from defaut to yourbranch) *Commit your changes only into yourbranch Rebasing * *Enable rebase extension *Create named branch (with changeset in it? TBT) *Rebase your changesets to the new ancestor, test results *See 5-6 from "More complex" chapter A: The best way to do this is with two clones. When working with a remote repo I don't control I always keep a local clone called 'virgin' to which I make no changes. For example: hg clone -U https://code.google.com/r/mosabua-roboguice-clean/ mosabua-roboguice-clean-virgin hg clone mosabua-roboguice-clean-virgin mosabua-roboguice-clean-working Note that because Mercurial uses hard links for local clones and because that first clone was a clone with -U (no working directory (bare repo in git terms)) this takes up no additional disk space. Work all you want in robo-guice working and pull in robo-guice virgin to see what's going on upstream, and pull again in roboguice-working to get upstream changes. You can do something like this after the fact by creating a new clone of the remote repo and if diskspace is precious use the relink extension to associate them. A: Perhaps you could try the Convert extension. It can bring a repository in a better shape, while preserving history. Of course, after the modifications have been done, you will have to delete the old repo and upload the converted one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get javax.comm API? I'd recently downloaded a project on SMS sending, but when I tries to compile the code it gives error on line import javax.comm.*;. Can anybody tell me where to find javax.comm and where to place so that there will be no compilation error. A: Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation). A: Use RXTX. On Debian install librxtx-java by typing: sudo apt-get install librxtx-java On Fedora or Enterprise Linux install rxtx by typing: sudo yum install rxtx A: you can find Java Communications API 2.0 in below link http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm A: Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done. if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip A: On ubuntu sudo apt-get install librxtx-java then add RXTX jars to the project which are in usr/share/java
{ "language": "en", "url": "https://stackoverflow.com/questions/7562565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: TaskCompletionSource for Silverlight? just searching for a way to use the TaskCompletionSource class in Silverlight. So first off, will it be available in Silverlight ver 5? Second, are Reactive Extensions a good way to go? Third, I came across PowerThreading from Jeffery Richter. Is this still a good way to go with Silverlight? http://www.wintellect.com/CS/blogs/jeffreyr/archive/2008/11/05/new-version-of-power-threading-library-dated-october-30-2008.aspx there's a port here (which I'm trying... assuming that pushing Silverlight 5 RC to a client even for testing is probably a bad thing) http://www.damonpayne.com/post/2011/02/13/Binary-Drop-For-the-Task-Parallel-Library-for-Silverlight.aspx http://www.perreira.net/matthieu/?page_id=172 (in French) A: Yes, TaskCompletionSource<T>, as well as the whole Task Parallel Library, is available in Silverlight 5. Reactive Extensions are great, really a higher level way of thinking about events and async operations. Definitely recommended for use in .NET, Silverlight, and JavaScript projects. I don't recommend Richter's PowerThreading library now; with the TPL making its way into SL 5, there's little use for his library, IMO.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "Error reading POM" when selecting a archetype in Maven setup I downloaded maven 3.0.3, set-up my environment variables as instructed and verified with mvn --version that everything looks ok. So far so good So, time to RTFM.. about 1 minute into the manual, weirdness occurs. mvn archetype:generate \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DgroupId=com.mycompany.app \ -DartifactId=my-app It asked me to select a archetype from this long list, I took the quickstart one 135. However, this doesn't work.. it spits out the following error: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.1:generate (default-cli) on project standalone-pom: Error reading POM -> [Help 1] What am I doing wrong? A: Up-to-date documentation: the free book by Sonatype. I learned some stuff from there even after using Maven for over 3 years.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get Django forms to show the html required attribute? I have this form field: email = forms.EmailField( required=True, max_length=100, ) It has the required attribute, but in the html it is not adding the html attribute required. In fact it's not even using email as the field type, it's using text... though it appears to get max_length just fine. Actual: <input id="id_email" type="text" name="email" maxlength="100"> Expected: <input id="id_email" type="email" name="email" maxlength="100" required="true"> How can I get Django to use the correct attributes in html forms? A: Since Django 1.10, this is built-in. From the release notes: Required form fields now have the required HTML attribute. Set the new Form.use_required_attribute attribute to False to disable it. A: Monkeypatching Widget is your best bet: from django.forms.widgets import Widget from django.contrib.admin.widgets import AdminFileWidget from django.forms import HiddenInput, FileInput old_build_attrs = Widget.build_attrs def build_attrs(self, extra_attrs=None, **kwargs): attrs = old_build_attrs(self, extra_attrs, **kwargs) # if required, and it's not a file widget since those can have files # attached without seeming filled-in to the browser, and skip hidden "mock" # fileds created for StackedInline and TabbedInline admin stuff if (self.is_required and type(self) not in (AdminFileWidget, HiddenInput, FileInput) and "__prefix__" not in attrs.get("name", "")): attrs['required'] = 'required' return attrs Widget.build_attrs = build_attrs A: There's also the template-only solution using a filter. I recommend django-widget-tweaks: {% load widget_tweaks %} {{ form.email|attr:'required:true' }} That was easy. A: As you've realized, setting your Field required attribute to True is only for backend validation, as explained in the Django documentation. What you really want is to add a required attribute to the Widget of the field: email.widget.attrs["required"] = "required" But if you really want to write elegant, DRY code, you should make a base form class that dynamically looks for all your required fields and modifies their widget required attribute for you (you can name it whatever you wish, but "BaseForm" seems apt): from django.forms import ModelForm class BaseForm(ModelForm): def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) for bound_field in self: if hasattr(bound_field, "field") and bound_field.field.required: bound_field.field.widget.attrs["required"] = "required" And then have all your Form objects descend from it: class UserForm(BaseForm): class Meta: model = User fields = [] first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = forms.EmailField(required=True, max_length=100) A: Django form elements are written against <input /> as it exists in HTML 4, where type="text" was the correct option for e-mail addresses. There was also no required="true". If you want custom HTML attributes, you need the attrs keyword argument to the widget. It would look something like this: email = forms.EmailField( max_length=100, required=True, widget=forms.TextInput(attrs={ 'required': 'true' }), ) You can check out more documentation about widgets here. Discussion of attrs is near the bottom of that page. Regarding type="email", you might be able to send that to your attrs dictionary and Django will intelligently override its default. If that isn't the result you get, then your route is to subclass forms.TextInput and then pass it to the widget keyword argument. A: Combining Daniel and Daniel answers, I usually use this mixin for my forms: from django.contrib.admin.widgets import AdminFileWidget from django.forms.widgets import HiddenInput, FileInput class HTML5RequiredMixin(object): def __init__(self, *args, **kwargs): super(HTML5RequiredMixin, self).__init__(*args, **kwargs) for field in self.fields: if (self.fields[field].required and type(self.fields[field].widget) not in (AdminFileWidget, HiddenInput, FileInput) and '__prefix__' not in self.fields[field].widget.attrs): self.fields[field].widget.attrs['required'] = 'required' if self.fields[field].label: self.fields[field].label += ' *' So when i have to create a new form or modelform i just use: class NewForm(HTML5RequiredMixin, forms.Form): ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7562573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Javascript apply methods from one object to another I have been at this for hours and just can't get it quite right. I have an object with methods that works fine. I need to save it as a string using JSON.stringify and then bring it back as an object and still use the same methods. function Workflow(){ this.setTitle = function(newtitle){this.title = newtitle; return this;}; this.getTitle = function(){return this.title;}; } function testIn(){ var workflow = new Workflow().setTitle('Workflow Test'); Logger.log(workflow);//{title=Workflow Test} Logger.log(workflow.getTitle()); //Workflow Test var stringy = JSON.stringify(workflow); var newWorkflow = Utilities.jsonParse(stringy); Logger.log(newWorkflow); //{title=Workflow Test} //Looks like the same properties as above Logger.log(newWorkflow.getTitle());//Error can't find getTitle } I think I should prototype the new object but nothing seems to work. Please help I have very little hair left. A: You need to copy the method to the new object: newWorkflow.getTitle = workflow.getTitle; A: you are losing your functions when you stringify and parse. if you have access to jquery, the $.extend is handy (if not, just copy&paste form jquery source) here's a demo: http://jsfiddle.net/VPfLc/ A: Serializing to JSON won't store executable code. It's being removed from your object when calling JSON.stringify. Your best bet is to make the object so it can be initialized when created. function Workflow(){ this.initialize = function(properties) { this.title = properties.title; } this.setTitle = function(newtitle){this.title = newtitle; return this;}; this.getTitle = function(){return this.title;}; } function testIn(){ var workflow = new Workflow().setTitle('Workflow Test'); Logger.log(workflow);//{title=Workflow Test} Logger.log(workflow.getTitle()); //Workflow Test var stringy = JSON.stringify(workflow); var newWorkflow = new Workflow().initialize(Utilities.jsonParse(stringy)); Logger.log(newWorkflow); //{title=Workflow Test} //Looks like the same properties as above Logger.log(newWorkflow.getTitle());//Error can't find getTitle } A: All you have to do is use call. Workflow.call(newWorkflow); EDIT: If your actual Workflow() implementation sets any attributes to default values during its initilization then calling on your new json object will also reset those. Which is what I'm assuming is going on, without being able to look at your actual implementation code. If that is the case, then you have two options. 1) Rather than blindly initilize your object (and assuming its empty), conditionally initilize your variables. function Workflow(){ this.setTitle = function(newtitle){this.title = newtitle; return this;}; this.getTitle = function(){return this.title;}; this.array = this.array || []; } for new empty objects. this.array will be null, and it'll be set to a new array. calling Workflow on a existing object that already has that property, it'll leave it alone. 2) Extract your methods into an Extension Module function Workflow(){ this.array = this.array || []; // Other work // Lastly include my method extensions. WorkflowMethodExtensions.call(this); } function WorkflowMethodExtensions(){ this.setTitle = function(newtitle){this.title = newtitle; return this;}; this.getTitle = function(){return this.title;}; } Then use: WorkflowMethodExtensions.call(newWorkflow); to extend an existing object with those methods defined in the existion
{ "language": "en", "url": "https://stackoverflow.com/questions/7562584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Batch To Delete File Less Than A Minute Old I'm trying to delete .zip, .jpg and .txt files that are under a minute old. I haven't added the file types yet. More about that later. But this does't seem to delete anything at this point. Any help is welcomed. This is in Windows. @echo off cd "c:\*\*" setlocal call :DateToMinutes %date:~-4% %date:~-10,2% %date:~-7,2% %time:~0,2% %time:~3,2% NowMins for /f "delims=" %%a in ('dir * /a-d /b') do call :CheckMins "%%a" "%%~ta" goto :EOF :CheckMins set File=%1 set TimeStamp=%2 call :DateToMinutes %timestamp:~7,4% %timestamp:~1,2% %timestamp:~4,2% %timestamp:~12,2% % timestamp:~15,2%%timestamp:~18,1% FileMins set /a MinsOld=%NowMins%-%FileMins% if %MinsOld% leq 1 del %file% goto :EOF :DateToMinutes setlocal set yy=%1&set mm=%2&set dd=%3&set hh=%4&set nn=%5 if 1%yy% LSS 200 if 1%yy% LSS 170 (set yy=20%yy%) else (set yy=19%yy%) set /a dd=100%dd%%%100,mm=100%mm%%%100 set /a z=14-mm,z/=12,y=yy+4800-z,m=mm+12*z-3,j=153*m+2 set /a j=j/5+dd+y*365+y/4-y/100+y/400-2472633 if 1%hh% LSS 20 set hh=0%hh% if /i {%nn:~2,1%} EQU {p} if "%hh%" NEQ "12" set hh=1%hh%&set/a hh-=88 if /i {%nn:~2,1%} EQU {a} if "%hh%" EQU "12" set hh=00 if /i {%nn:~2,1%} GEQ {a} set nn=%nn:~0,2% set /a hh=100%hh%%%100,nn=100%nn%%%100,j=j*1440+hh*60+nn endlocal&set %6=%j%&goto :EOF A: Firstly, your script doesn't work for me because it is dependent upon the date and time format, and for me it's: c:\>echo %date% Tue 27/09/2011 c:\>echo %time% 9:52:31.68 That aside, analyse what is going on by temporarily commenting out the @echo off at the top. I've edited your script to handle my date format and I can see two issues: * *The stray white space in the passing f the fifth parameter (although this might just be a cut and paste issue); and *The way you're iterating through the directories. Rather than using cd "c:**" I would alter the for statement as: for /f "delims=" %%a in ('dir /a-d /b /s c:\') do call :CheckMins "%%a" "%%~ta" As PA said in the comments, there are better answers at: How can I check the time stamp creation of a file in a Windows batch script?
{ "language": "en", "url": "https://stackoverflow.com/questions/7562585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting the background color of a UIVIew EDIT: People keep visiting this post which doesn't have much good information so I'll put this here to help you guys: Try setting the backgroundColor property of your UIView. For example: myView.backgroundColor = [UIColor blueColor]; Make sure your view has been instantiated and if it is controlled by an xib or storyboard at all, make sure that the view has already been loaded (otherwise whatever is set in interface builder will become the background color). If that doesn't work, something weird is going on. Keep looking, this post won't help you. Original post: I have an NSObject with a UIView property. Mostly I use this UIView for displaying a picture, but in some cases, I want to set the background color of it. However, each time I try to set the background color, the color stays as clear. Any images or other subviews appear but the background does not. How can I change the background color of a UIView? Here is some of my code: here is an example where I need a tiled image: (this is in a function called after I add the UIView to the viewcontroller's view) (picture is a UIView Property) picture.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Tile.png"]]; I have also tried in other cases: picture.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:0.5]; In both cases, the background remains clear. A: Are you allocating and initializing the UIView mentioned above? The problem should be that you have most likely forgotten to do that for the UIView called picture. Just try: picture = [[UIView alloc] initWithFrame:CGRectMake(10,10,200,200)]; picture.backgroundColor = [UIColor redColor]; Assuming that picture has already been declared an iVar of type UIView in your interface file. A: If you are good in using RGB value you can use picture.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:1]; Otherwise use UIColor to set the color for backgound picture.backgroundColor = [UIColor greenColor]; A: alpha has a valid range of 0.0 to 1.0. You have it set to 50, try 1 instead: picture.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:1]; A: I'm not sure what the problem was, although I do know it was not one of the problems you have answered with, but last time I went to work on the problem I noticed that it was working. Thank you for your help anyway. A: It's probably worth checking whether you're changing the background color on the main thread or not. If you change the background color in a dispatch queue (other than the main queue) it can sometimes not be reflected in the UI appearance. A: Can use attribute inspector for change color. Select color for 'Background'. A: Your code seems totally valid and it should change the background colour. You may want to double check that picture.opaque property is set to YES (it's the default value unless your code change it). But a more likely problem is that the frame of the view has zero size. I would advise to verify this. For example, by logging it: NSLog(@"Frame size: width=%f, height=%f", picture.frame.size.width, picture.frame.size.height); Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7562588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: stored procedure progress I have a huge stored procedure and I want to create a progress bar for it on asp.net VB front-end. So, as suggested before on stackoverflow, I have to use additional status table and timer on front-end. Then, I have to call another stored procedure that will return current status of stored proc. But I cannot do async procedure calls on sql server from front-end. What are the settings I should try to set on sql server end to allow asynchronious procedures? ANd on the front-end it looks like my program stops executing when it hits stored procedure #1. A: actually you don't need to start second proc in assync. Just open yet another connection on c# side and periodically (here can be used low-priority thread or Timer) call yours #2 - that checks progress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trim blank lines from textarea submission I have a form that submits text from textarea. The text can be formatted, i.e. have line breaks and paragraphs, however I want to remove blank lines at the end of the text. Shall I use rtrim or preg_replace? Can I use something like this to clear blank lines, carriage returns and tabs? rtrim($_POST['inviteMsg'], "\n\t\r"); A: Yes. In fact, that's precisely what rtrim is for. preg_replace just offers you loads of extra flexibility that you don't need in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Steps to run NUnit tests on OSX How do I run NUnit tests developed within VS2010 on a Mac? This seems like a very simple and naive question but I have been struggling to find all the steps. I have done my due diligence by scouring the web to find the exact steps. I have Mono on my Mac, but not monodevelop. How can i install NUnit on a Mac without mono develop? Do I need to add all the NUnit related dlls manually to Mono GAC or something? A: No need to have monodevelop. After getting nunit you can just call it via (for instance) mono nunit-console.exe your.dll You can also do this using only binaries downloaded from nunit site, just be in the nunit's directory. If there is no package for OS X, you can install it by making script invoking nunit (this is how standard nunit install on Linux works) and putting it in your search path. Adding assemblies to GAC is not necessary as long as they are with exe's. For example this is nunit-console script on Ubuntu (which can be usually found in /usr/bin): #!/bin/sh exec /usr/bin/mono --debug $MONO_OPTIONS /usr/lib/mono/2.0/nunit-console.exe "$@" Of course you should replace /usr/lib/mono/2.0/ with directory which contains nunit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Simple write to file does not work for me I cannot get this simple string to write to a file. Please look at my code. This is a simple nib with an NSTextField and a button. The log shows I am getting the string value fine, but it does not write. //Quick.h #import <Foundation/Foundation.h> @interface Quick : NSObject { IBOutlet NSTextField * aString; } -(IBAction)wButton:(id)sender; @end //Quick.m #import "Quick.h" @implementation Quick - (id)init { self = [super init]; if (self) { // Initialization code here. } return self; } -(IBAction)wButton:(id)sender{ NSString * zStr = [aString stringValue]; NSString * path = @"data.txt"; NSLog(@"test String %@", zStr); [zStr writeToFile:path atomically:YES encoding:NSASCIIStringEncoding error:nil]; } @end A: You have to provide an entire file path to most likely the Documents directory, not just a file name. NSString *zStr = [aString stringValue]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *directory = [paths objectAtIndex:0]; NSString *fileName = @"data.txt"; NSString *filePath = [directory stringByAppendingPathComponent:fileName]; [zStr writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil]; A: You need to provide an absolute path. This code from another answer gives you the path to the documents directory of your app: [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7562597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot Load RMagic in Rails, but can in IRB I'm having trouble getting RMagick to work properly. When I run the require in IRB: irb(main):001:0> require 'RMagick' => true But when I try to include it in my Rails app I get: no such file to load -- RMagick I installed RMagick through the Gem. gem list *** LOCAL GEMS *** bundler (1.0.18) daemon_controller (0.2.6) fastthread (1.0.7) minitest (1.6.0) passenger (3.0.8) rack (1.3.2) rake (0.8.7) rdoc (2.5.8) rmagick (2.13.1) Ruby version: ruby -v ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux] Passenger for Rails is loading: LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.8/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.8 Could the difference in ruby versions between the passenger module and the console be a problem? Thanks so much! ~James A: Definitely- the ruby versions need to be the same. I would urge you to move over to using RVM instead: http://beginrescueend.com/ as it'll be a lot painless in the long run. A: I setup RMagick in the past and based on a quick glance at old code, I had to do this: require 'RMagick' include Magick # not sure why, but we always have to do this w/ RMagick. I also remember that doing this worked on one particular system: require 'rmagick' # lowercase version of require 'RMagick'
{ "language": "en", "url": "https://stackoverflow.com/questions/7562599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android-Market bugs? i've got a problem with an app that i published 2 days ago. The app still doesn't appear in the market within the new entries (appear only with direct link) About 1 month ago, I've uploaded a previous version of that app..with the same name and a different package name. It was a beta so i disabled it in the console and i uploaded a NEW app with the same name but different package name...This can be related with the problems mentioned before? Anybody had similar problems? A: In my experience it won't last near the top for very long at all. after 2 days you'd probably have to scroll down pretty far to find yours. I have noticed that sometimes my apps show up in the new list within a few minutes of uploading, and sometimes not for an hour or so. But I've never witnessed it happen any longer. As for whether or not changing your package name could result in your problem. Perhaps, but I wouldn't think so. In general though you should strive to never change your package name. This will result in users having to un-install before they are able to install new versions. A: Seems that is the new Google design. You don't get your app listed in the new category (or any other) unless it's already a high-ranking app before it's launched, or, you are one of the top-rated developers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I json_encode the results of this query? foreach($hello_world as $key=>$product_id) { if(in_array($key,$exclude))continue; $query = $this->db->query("SELECT * FROM product where modelNumber = '$product_id'"); if ($query->num_rows() > 0) { foreach($query->result() as $row) { echo $row->name; } } } Can someone give me advice as to how I would json encode the results of this query? Thanks A: $data = array(); $query = $this->db->query("SELECT * FROM product where modelNumber = '$product_id'"); if ($query->num_rows() > 0) { foreach($query->result() as $row) { $data[$row->id] = $row->name; } } $json = json_encode($data);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What does `` provide, and where is it documented? The new C++11 standard mentions a header <cuchar>, presumably in analogy to C99's <uchar.h>. Now, we know that C++11 brings new character types and literals that are specifically designed for UTF16 and UTF32, but I didn't think the language would actually contain functions to convert the (system-dependent) narrow multibyte encoding to one of the Unicode encodings. However, I just came across the header synopsis for <cuchar> that mentions functions mbrtoc16/c16rtombr and mbrtoc32/c32rtombr that seem to do just that. Unfortunately, the standard says nothing about those functions beyond the header synopsis. Where are those functions defined, what do they really do and where can I read more about them? Does this mean that one can use proper Unicode entirely with standard C++ now, without the need for any extra libraries? A: These were described in a WG21 paper from 2005 but the description is not present in the final standard. They are documented in ISO/IEC 19769:2004 (Extensions for the programming language C to support new character data types) (draft), which the C++11 standard refers to. The text is too long to post here, but these are the signatures: size_t mbrtoc16(char16_t * pc16, const char * s, size_t n, mbstate_t * ps); size_t c16rtomb(char * s, char16_t c16, mbstate _t * ps); size_t mbrtoc32(char32_t * pc32, const char * s, size_t n, mbstate_t * ps); size_t c32rtomb(char * s, char32_t c32, mbstate_t * ps); The functions convert between multibyte characters and UTF-16 or UTF-32 characters, respectively, similar to mbrtowc. There are no non-reentrant versions, and honestly, who needs them? A: Probably the best documentation of which I'm aware is in n1326, the proposal to add TR19769 to the C standard library [Edit: though looking at it, the N1010 that R. Martinho Fernandes cited seems to have pretty much the same].
{ "language": "en", "url": "https://stackoverflow.com/questions/7562609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: NSURLRequest: EXC_BAD_ACCESS I'm building an application with loads content from an PHP file. I have 4 views with loads content from 4 different PHP files. For each view controller i'm using the following code: // // turmaAViewController.m // SamplePad // // Created by Mateus Nunes on 25/09/11. // Copyright 2011 NBM Company. All rights reserved. // #import "turmaAViewController.h" #import "DetailViewController.h" @implementation turmaAViewController @synthesize messageList; @synthesize studentImageView; @synthesize imageText; //############################################################################### //############################################################ DEVICE ORIENTATION - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ if(interfaceOrientation == UIInterfaceOrientationLandscapeRight){ return YES; } else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft){ return YES; }else return NO; } //############################################################################################################################## //################# CUSTOM VIEW INITIALIZATION #################// //############################################################################################################################## - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { lastId = 0; chatParser = NULL; } return self; } //############################################################################################################################## //################# DEALLOC - MEMORY RELEASE #################// //############################################################################################################################## -(void)dealloc { [messageList release]; [super dealloc]; } //############################################################################################################################## //################# DISPLAY PHP FILE INTEGRATION #################// //############################################################################################################################## -(void)getNewMessages { NSString *url = [NSString stringWithFormat:@"http://localhost/SPA/turmaa.php?past=%ld&t=%ld",lastId, time(0) ]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:url]]; [request setHTTPMethod:@"GET"]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (conn){ receivedData = [[NSMutableData data] retain]; }else{} } - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return nil; } //############################################################################################################################## //################# FETCHING PRAGMAS #################// //############################################################################################################################## -(void)timerCallback { [timer release]; [self getNewMessages]; } //############################################################################################################################## //################# CONNECTION PRAGMAS #################// //############################################################################################################################## -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData setLength:0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { if (chatParser) [chatParser release]; if (messages == nil) messages = [[NSMutableArray alloc] init]; chatParser = [[NSXMLParser alloc] initWithData:receivedData]; [chatParser setDelegate:self]; [chatParser parse]; [receivedData release]; [messageList reloadData]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector: @selector(timerCallback)]]; //[invocation setTarget:self]; [invocation setSelector:@selector(timerCallback)]; //timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO]; } //############################################################################################################################## //################# PARSING THE MESSAGE XML FILE LIST #################// //############################################################################################################################## -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ( [elementName isEqualToString:@"message"] ) { msgAdded = [[attributeDict objectForKey:@"added"] retain]; msgId = [[attributeDict objectForKey:@"id"] intValue]; msgAluno = [[NSMutableString alloc] init]; msgMatricula = [[NSMutableString alloc] init]; msgCpf = [[NSMutableString alloc] init]; msgImage = [[NSMutableString alloc] init]; msgCC = [[NSMutableString alloc] init]; inAluno = NO; inMatricula = NO; inCpf = NO; inImage = NO; inCC = NO; } if ( [elementName isEqualToString:@"aluno"] ) { inAluno = YES;} if ( [elementName isEqualToString:@"matricula"] ) { inMatricula = YES;} if ( [elementName isEqualToString:@"cpf"] ) { inCpf = YES;} if ( [elementName isEqualToString:@"image"] ) { inImage = YES;} if ( [elementName isEqualToString:@"CC"] ) { inCC = YES;} } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ( inAluno ) { [msgAluno appendString:string]; } if ( inMatricula ) { [msgMatricula appendString:string]; } if ( inCpf ) { [msgCpf appendString:string]; } if ( inImage ) { [msgImage appendString:string];} if ( inCC ) { [msgCC appendString:string];} } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ( [elementName isEqualToString:@"message"] ) { [messages addObject:[NSDictionary dictionaryWithObjectsAndKeys:msgAdded,@"added",msgAluno,@"aluno",msgMatricula,@"matricula",msgCpf,@"cpf",msgImage,@"image",msgCC,@"CC",nil]]; [[messages reverseObjectEnumerator] allObjects]; lastId = msgId; [msgAdded release]; [msgAluno release]; [msgMatricula release]; [msgCpf release]; [msgImage release]; [msgCC release]; } if ( [elementName isEqualToString:@"aluno"] ) { inAluno = NO;} if ( [elementName isEqualToString:@"matricula"] ) { inMatricula = NO;} if ( [elementName isEqualToString:@"cpf"] ) { inCpf = NO;} if ( [elementName isEqualToString:@"image"] ) { inImage = NO;} if ( [elementName isEqualToString:@"CC"] ) { inCC = NO;} } //############################################################################################################################## //################# PARSING FINISHED - START DISPLAYING #################// //############################################################################################################################## -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section { return ( messages == nil ) ? 0 : [messages count]; } -(UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"newsCustomCell"]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"newsCustomCell" owner:self options:nil]; cell = (UITableViewCell *)[nib objectAtIndex:0]; } NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row]; UILabel *timeDate = (UILabel *)[cell viewWithTag:1]; timeDate.text = [itemAtIndex objectForKey:@"added"]; UILabel *userL = (UILabel *)[cell viewWithTag:2]; userL.text = [itemAtIndex objectForKey:@"aluno"]; UILabel *textL = (UILabel *)[cell viewWithTag:3]; textL.text = [itemAtIndex objectForKey:@"matricula"]; UILabel *textL2 = (UILabel *)[cell viewWithTag:4]; textL2.text = [itemAtIndex objectForKey:@"cpf"]; UILabel *imageL = (UILabel *)[cell viewWithTag:5]; imageL.text = [itemAtIndex objectForKey:@"image"]; UILabel *videoL = (UILabel *)[cell viewWithTag:6]; videoL.text = [itemAtIndex objectForKey:@"CC"]; UIWebView *webView = (UIWebView *) [cell viewWithTag:7]; NSString *urlAddress = [itemAtIndex objectForKey:@"image"]; NSURL *url = [NSURL URLWithString:urlAddress]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView loadRequest:requestObj]; return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]]; NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row]; NSString *selectTime = [itemAtIndex objectForKey:@"added"]; NSString *selectUser = [itemAtIndex objectForKey:@"aluno"]; NSString *selectMessage = [itemAtIndex objectForKey:@"matricula"]; NSString *selectMessage2 = [itemAtIndex objectForKey:@"cpf"]; NSString *selectImage = [itemAtIndex objectForKey:@"image"]; NSString *selectVideo = [itemAtIndex objectForKey:@"CC"]; dvController.selectedTime = selectTime; dvController.selectedUser = selectUser; dvController.selectedImage = selectImage; dvController.selectedMessage = selectMessage; dvController.selectedMessage2 = selectMessage2; dvController.selectedVideo = selectVideo; [self.navigationController pushViewController:dvController animated:YES]; [dvController release]; dvController = nil; [tableView deselectRowAtIndexPath:indexPath animated:NO]; } //############################################################################################################################## //################# PARSING FINISHED - START DISPLAYING #################// //############################################################################################################################## -(void)viewDidLoad { messageList.dataSource = self; messageList.delegate = self; [messageList release]; [self getNewMessages]; [super viewDidLoad]; } @end First when i build one view with this code and tested it had worked well, no problems. But when i added this code to the others views the application started crashing, "EXC_BAD_ACCESS" Error! Because of this i suppose i need to kill the request when i run out of my view, but how can i do this or if you identify another problem! A: I will give you a hint, not the answer. EXC_BAD_ACCESS occurs when a method is called on an object that has been released. To see which object is being called, you will have to enable Zombies. To enable zombies in xcode 4, see How do I set up NSZombieEnabled in Xcode 4?.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there anything thing like pastescript without the paste part? I am looking for a simple lib/tool like paster that I can easily create custom commands without having anything to do with paste itself. I am looking to create a helper tool like paster or manage.py to do various tasks like build (maybe using buildout), build documentation and run scripts/tests for a non-web/non-wsgi based project. (that's why I don't want anything that needs paste) Any suggestions on a tool? Does my approach sound reasonable? A: Often I use Fabric as my general purpose project janitor. Usually I automate the following tasks with Fabric: * *generate documentation *run tests *make releases Initially Fabric has been developed to ease the automation/scripting of commands to run on remote hosts using SSH. However, Fabric is also an excellent tool to automate local project management related tasks. Fabric commands are plain Python functions within a so called fabfile. You don't need to know much about Fabric to get started. Here's a simple fabfile.py: from fabric.api import local def tests(): """Run the test suite.""" ... def release(version): """Make a relase.""" tests() local("hg tag %s" % version) ... which may be used like that: $ fab -l Available commands: release Make a relase. tests Run the test suite. $ fab release:version=0.1 ... [localhost] local: hg tag 0.1 ... Concerning buildout, just add this part to your buildout.cfg and Fabric is ready to use at bin/fab: [fabric] recipe = zc.recipe.egg eggs = <things-you-need-in-your-fabfile> fabric
{ "language": "en", "url": "https://stackoverflow.com/questions/7562616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is wrong with my code (using dojo xhrGet Ajax) I'm attemping to use this code to call a php file, access the database, retrieve values, and return them using a JSON object, then edit them into a text box. Code for Javascript end: As the user changes the option in the dropdown list, the app should call a PHP script to fetch the new values from the database, retrieve them from a JSON object, and modify a text area to show the new values. <select id="busSelect" name="busSelect"> <option>S053-HS - P</option> <option>S059-HS - P</option> <option>S064-HS - P</option> <option>S069-HS - P</option> <option>S070-HS - P</option> </select> <textarea id="memo"></textarea> <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js" type="text/javascript"></script> <script type ="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> <script type ="text/javascript"> <?php ?> dojo.ready(function(){ var myOptions = { zoom: 12, center: new google.maps.LatLng(26.4615832697227,-80.07325172424316), mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(dojo.byId("map_canvas"), myOptions); dojo.connect(busSelect,"onchange",function(){ dojo.xhrGet({ url: "getRoute.php", handleAs: "json", timeout: 1000, content: { route: dojo.byId("busSelect").value }, load: function(result) { var formResult = result.lat_json + " " + result.long_json + " " + result.name_json; dojo.byId(memo).value = formResult; } }); }); PHP Script: Should take the name it receives from the JS app, which is the "bus name" and find the bus id using that name. Then it should access bus stops using that ID (this all works, I'm just getting the JSON/AJAX bit wrong) <?php header('Content-type: application/json'); require_once 'database.php'; mysql_connect($server, $user, $pw); mysql_select_db("busapp") or die(mysql_error()); $route = $_GET["route"]; $result_id = mysql_query("SELECT * FROM routes WHERE name = $route"); $result_row = mysql_fetch_array($result_id); $route_id = $row['id']; $result = mysql_query("SELECT * FROM stops_routes WHERE route_id = $route_id") or die(mysql_error()); $markers; $stopid = array(); $time = array(); $lat; $long; $name; $waypts = array(); for ($x = 0; $row = mysql_fetch_array($result); $x++) { $stopid[$x] = $row['stop_id']; $time[$x] = $row['time']; } for ($x = 0; $x < sizeof($stopid); $x++) { $result = mysql_query("SELECT * FROM stops WHERE id = $stopid[$x]") or die(mysql_error()); $row = mysql_fetch_array($result) or die(mysql_error()); $lat[$x] = $row['lat']; $long[$x] = $row['long']; $name[$x] = $row['name']; } $size = count($stopid); $lat_json = json_encode($lat); $long_json = json_encode($long); $name_json = json_encode($name); ?> I'm also getting an error on dojo.xd.js:14 when running. A: Instead of individual variables passed to json_encode(), you should be creating an object and then encoding it as JSON, then simply echoing out the JSON with the correct Content-type header. // Start with an associative array $arr = array("lat_json" => $lat, "long_json" => $long, "name_json" => $name); // Cast it to an Object of stdClass $obj = (object)$arr; // Encode it $json = json_encode($obj); // And return it to the calling AJAX by just echoing out the JSON header("Content-type: application/json"); echo $json; exit(); Before encoding JSON, your object now looks like (with my example data): stdClass Object ( [lat_json] => 12345 [long_json] => 45678 [name_json] => the name ) // After json_encode() {"lat":12345,"long":45678,"name":"the name"} As you've setup your javascript on the receiving end, I believe it should work without modification. To be certain of the JSON structure from the javascript end, be sure to check console.dir(result) inside your load() function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: If HTML form was submtited check is if ($_POST['submit']) ... same as if (isset($_POST['submit']) ... or it means something else? Which one i should use to check if form was submitted? Is there some way to pull form name? A: Use if ($_SERVER['REQUEST_METHOD'] == 'POST'). All other methods are flawed. What if you rename the submit button? A: To get the form name you can either: 1) use a hidden input field whose value is the same as the form name 2) set the name of the submit button to the form name The actual form name is not sent in the POST or GET variables. A: isset Determines if a variable is set and is not NULL Boolean cast (same as !empty($var)) empty returns FALSE if var has a non-empty and non-zero value. The following things are considered to be empty: * "" (an empty string) * 0 (0 as an integer) * 0.0 (0 as a float) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class) Pages can have more than one form. It's best to give your submit element a value as well: <input type="hidden" name="submit" value="login" /> Then in your PHP code, you can: if (isset($_POST['submit']) && $_POST['submit'] == 'login') { } A: if(isset($_POST['submit'])) checks if the variable exists or in this case if the key exists under the array and is not null. if($_POST['submit']) will check if the value of $_POST['submit'] is equal to true (or some other value that evaluates to true). the second method there, will throw a notice error if the variable is not set. You should use isset to check if a variable is set, that's what it is for. A: they are the same but using if(isset($_POST['submit']) or if(!empty($_POST['submit']) are better
{ "language": "en", "url": "https://stackoverflow.com/questions/7562623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conditional Keybinding I was wandering if someone could explain to me how I could do a conditional key binding (using an MVVM pattern), at the moment I have <Window.InputBindings> <KeyBinding Command="{Binding Path=CMD_Login}" Gesture="Enter" /> </Window.InputBindings> but I would like this key-binding to only be active if the user is logging in. They login window is set to visible/collapse depending if the user is logging in or not, so was wandering if the conditional can possibly be based on that? Thank You A: If you have a command, shouldn't the CanExecute part handle that by not always returning true?
{ "language": "en", "url": "https://stackoverflow.com/questions/7562624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to end AsyncTask onBackPress() and also does it still run if it isnt finished? I use AsyncTask in several activities. i know how to Override onBackPress(). But when an AsyncTask is running i want to give the user the ability to go back even though the asynctask is still running. How can I do this? Also does an asynctask still run when activity that initiated it is closed before it finishes? A: AsyncTasks run on until they complete or are cancelled. So in your case (the user presses Back and you end the main activity), the AsyncTask will carry on. If you did want to end the AsyncTask from onBackPressed, the best you can do is to call myAsyncTask.cancel(true); but all that does is call the task's onCancelled() which can set a cancel flag that can be checked (usually) in doInBackground() - and if it is set the task can return. Note that using cancel(true) does not stop the task. The docs talk about "interrupting" the task for the true case, but all they mean is that onCancelled will be called while doInBackground is running - at which point the task has an opportunity to set a flag that doInBackground can inspect. For the true case, if the task does not implement onCancelled, and/or it does not set/inspect a flag, the task will complete doInBackground, but onPostExecute(Object) is never invoked - which is equivalent to the false case. A: The async task will continue to run even if your application was closed. You have to be careful with that since your task will leak your context (keep it in memory) if it has a reference to it (so the activity) as long as your task is still running. You can avoid that by referencing your activity by a WeakReference. You can stop a running task with cancel(true). A cancel will let the task finish its doInBackground but will never call onPostExecute. You could interrupt your background routine by checking isCanceled() and so return earlier since the task was killed. I deleted one half of my post! I did so confuse interrupt with a thread stop! Using true will of course NOT stop the actual thread. Thanks a lot to Torid and his answer which proved me wrong! Big lesson lernt, thanks for that!
{ "language": "en", "url": "https://stackoverflow.com/questions/7562625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do NSCoder and/or NSKeyedUnarchiver handle multiple decodings of the same object? I was wondering how NSCoder would handle an object that was shared and encoded by multiple objects the next time it was decoded. Will it make two copies of the object, or will one object be decoded and shared between all other objects that decode it? I've provided a small example of a situation like this below. Example: * *Application starts up *Object A and Object B set Object C as their delegate *Application receives termination notification. *Object A and Object B encode themselves and all of their objects (including their delegates) *Application shuts down and restarts *Object A and Object B decode themselves and all of their objects (including their delegates) Would Object A and Object B both share the same decoded object after step 6 or would they each have their own copy of it? A: They'll share a reference to the same object (unless you go to lengths to change that behavior). I.e. NSCoding can deal with fully cyclic, omni-directional, complexly connected, object graphs (as long as all graph participants correctly support NSCoding). Note that encoding delegates is highly atypical. Delegates are usually connected to an unarchived object graph after anarchival and delegates act as a sort of conduit between your archived model layer (or archived view layer, in the case of IB -- the story is more complex, really, for XIB files... but... close enough) and the rest of your app. A: This is a great question, and I always wondered about it myself. So, I wrote a small test program to try it out. Four classes: ClassA, ClassB, ClassC, and MyBaseClass. ClassA, ClassB, and ClassC inherit from MyBaseClass which conforms to NSCoding and provides two properties: name and age. The A, B, and C classes are identical except that ClassA and ClassB also contain a reference to an instance of ClassC. ClassA and ClassB also override initwithCoder: and encodeWithCoder: to decode and encode their references to the instance of ClassC. Here is what the top-level code looks like: ClassA *a = [[ClassA alloc] initWithName:@"Mr. A" age:11]; ClassB *b = [[ClassB alloc] initWithName:@"Mrs. B" age:22]; ClassC *c = [[ClassC alloc] initWithName:@"Ms. C" age:33]; b.c = c; a.c = c; NSArray *rootObject = @[a, b, c]; NSString *const kFilePath = @"/Users/myname/Documents/testarchive"; BOOL result = [NSKeyedArchiver archiveRootObject:rootObject toFile:kFilePath]; NSLog(@"result = %@", (result) ? @"YES" : @"NO"); NSArray *newRootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath]; NSLog(@"new root object = %@", newRootObject); The objects serialize and deserialize perfectly. Also, after deserializing, a.c and b.c point to the same instance of ClassC — that is, their object pointers have the same address. Apparently, within NSKeyedArchiver's encodeObject:forKey:, a test is done to see if the object being encoded isEqualTo: a previously encoded object, and if it is, a reference is stored instead of a complete object. The converse must happen in NSKeyedUnarchiver's decodeObject:forKey:. Very cool! A: I don't think the first answer is entirely correct. According to Apple's documentation, "The serialization only preserves the values of the objects and their position in the hierarchy. Multiple references to the same value object might result in multiple objects when deserialized". So it's not guaranteed that a single object serialized will result in a single object when deserialized from those multiple NSCoders. If you're implementation is anything like your example then you may not be thinking about things quite right. If you think about the logical organization of an application it might make sense that multiple objects could share the same delegate. But generally I wouldn't expect somebody to use the NSCoder protocol to encode/decode delegates. Normally I would expect the delegate to encode/decode the objects for which it is the delegate. For instance let's look at NSTableView. Perhaps the user gets the ability to configure how the NSTableView is displayed (perhaps the user is allowed to resize columns or choose which columns are displayed). This is useful information that you might want to save and restore using the NSCoding protocol. NSTableView's also have delegates. The delegate should be a controller (from the MVC paradigm) and should never really need to be encoded/decoded using NSCoding because it is generic code that does not have to maintain any runtime state. So Ideally you create your delegate/controller using an init method. It realizes it needs to configure a NSTableView to look the way it did the last time the user configured it, so it pulls an old table view from disk using NSCoding and then displays that to the user just as it was the last time they saw it. I think the same goes for the Model layer in the MVC Paradigm. Again, the Controller layer should be decoding the model objects which are specific to what the user has done through their use of the application. It sounds more like you are trying to instantiate the controller layer from the model or perhaps view layer. It doesn't really make sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQLAlchemy - How to map ManyToMany using autoloaded association tables I am autoloading an MSSQL db. There are a few ManyToMany assoc tables. I'm not sure how to map each side. Here's a typical example of how they look in the db: Table: tbUsersToGroups PK: ID_UserToGroup FK: User_ID FK: Group_ID So I can successfully autoload that assoc table and the Users and Groups tables per below, but everything I've tried to map the sides has failed. class UserToGroup(Base): __tablename__ = 'tbUsersToGroups' __table_args__ = {'autoload':True,'extend_existing':True,'schema':'dbo'} and class User(Base): __tablename__ = 'tbUsers' __table_args__ = {'autoload':True,'schema':'dbo'} and class Group(Base): __tablename__ = 'tbGoups' __table_args__ = {'autoload':True,'schema':'dbo'} Any help would be great. A: You have mapped the association table to a class. It's very unusual and probably going to cause you some pain to combine an association object with a many-to-many relationship. If the association table doesn't have any other columns of interest, you can drop the mapping and use a many-to-many relationship: Edit: I missed the fact that you're doing per-table reflection, rather than full database reflection; For a many-to-many, you have to tell sqlalchemy about the table, but without mapping it to a class: user_to_groups_table = sqlalchemy.Table('tbUsersToGroups', Base.metadata, autoload=True, extend_existing=True schema='dbo') class User(Base): __tablename__ = 'tbUsers' __table_args__ = {'autoload':True,'schema':'dbo'} class Group(Base): __tablename__ = 'tbGoups' __table_args__ = {'autoload':True,'schema':'dbo'} users = relationship(User, secondary=user_to_groups_table, backref="groups") If there are columns in the association table that you want to have an object-oriented access to, you should use two One-To-Many relationships to relate the three classes; Optionally, you can also use an association proxy to get a convenient many-to-many property for when you only need to use those extra columns occasionally (and they have defaults): from sqlalchemy.ext.associationproxy import association_proxy class UserToGroup(Base): __tablename__ = 'tbUsersToGroups' __table_args__ = {'autoload':True,'extend_existing':True,'schema':'dbo'} class User(Base): __tablename__ = 'tbUsers' __table_args__ = {'autoload':True,'schema':'dbo'} usergroups = relationship(UserToGroup, backref="user") groups = association_proxy("usergroups", "group") class Group(Base): __tablename__ = 'tbGoups' __table_args__ = {'autoload':True,'schema':'dbo'} usergroups = relationship(UserToGroup, backref="group") users = association_proxy("usergroups", "user")
{ "language": "en", "url": "https://stackoverflow.com/questions/7562646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Ajax not returning variables from external PHP I have this code that takes info from a form and sends it to form.php where it is processed. form.php echoes the variables (Fullname: $fullname E-mail: $email Link: $link Instructions: $instr) which are supposed to be inputted to #success. My code behaves two different ways in firefox and chrome. In Firefox, I am sent to form.php which displays the output properly but obviously I shouldn't be sent there, I should stay on my main page and see that output in #success. Basically, the ajax doesn't work. In Chrome, the ajax does work but only pulls Fullname: Email: Link: Instructions: into #success. In essence, the jQuery is not passing the variables via POST. mainpage.php: <script type="text/javascript"> $(document).ready(function() { var data = $(form).serialize(); $('#form').submit(function(event) { $.ajax({ url: '../wp-content/themes/MC/form.php', type: 'POST', data: data, success: function(result) { $('#success').html(result); } }); event.preventDefault(); }); }) </script> <div id="exchange_inside"> <div id="formdiv"> <br> <form method="post" id="form"> Name / Nom:<input type="text" name="fullname" /><br /> E-mail / Courriel:<input type="text" name="email" /><br /> Your Daily URL / Votre URL Quotidien:<input type="text" name="link" /><br /> Voting Instructions / Instructions de Vote:<textarea name="instr" style="width: 450px; height: 100px;"/></textarea><br /> <input type="submit" value="Submit" /> </form> </div> </div> <div id="success"> </div> form.php: <?php if (isset($_POST['fullname'])){ $fullname = $_POST['fullname']; }else{ echo "No name"; } if (isset($_POST['email'])){ $email = $_POST['email']; }else{ echo "No email"; } if (isset($_POST['link'])){ $link = $_POST['link']; }else{ echo "No link"; } if (isset($_POST['instr'])){ $instr = $_POST['instr']; }else{ echo "No instructions"; } echo "Name: " .$fullname. " E-mail: " .$email. " Link: " .$link. " Instructions: " .$instr; ?> A: Try changing up the jquery a bit by moving up event.preventDefault(); to before the ajax call and fix your var data = $("#form").serialize();: $(document).ready(function() { $('#form').submit(function(event) { event.preventDefault(); var data = $("#form").serialize(); $.ajax({ url: '../wp-content/themes/MC/form.php', type: 'POST', data: data, success: function(result) { $('#success').html(result); } }); }); }); //semicolon here Put a semicolon on the end of $(document).ready for good measure. Moving event.preventDefault() before the ajax call stops the form from submitting if the ajax fails for some reason or there is an error in the ajax call. Primarily with this method of form submit, you want to stop the default behavior of the form first. A: Try getting rid of the $('#form').submit, which is submitting the form without ajax, like this: $(document).ready(function() { var data = $('#form').serialize(); //this selector also needed to be fixed $.ajax({ url: '../wp-content/themes/MC/form.php', type: 'POST', data: data, success: function(result) { $('#success').html(result); } }); }); Edit: I misunderstood. Try serializing the data after submit has been pressed, rather than when the page loads, to fix the Chrome problem. $('#form').submit(function(event) { var data = $('#form').serialize(); //moved this line and fixed selector $.ajax({ url: '../wp-content/themes/MC/form.php', type: 'POST', data: data, success: function(result) { $('#success').html(result); } }); event.preventDefault(); }); You may also want to try changing the submit button to a regular button and binding the ajax to its onclick event. This would avoid problems with the form submitting without ajax, and fix the Firefox problem. A: $(document).ready(function() { $("#form").submit(function(event) { var data = $("#form").serialize(); $.ajax({ url: '/echo/json/', type: 'POST', data: data, success: function(data, status, xhr) { console.log(data); console.log(status); console.log(xhr); $('#success').html(result.responseText); } }); event.preventDefault(); return false; }); }) * *Your declaration of data wasn't in the global scope.(i packed it in the right local scope) *$(form).serialize() isn't equal to $("#form").serialize() *Edit back in your url =) *Use Jsfiddle and Firebug/Chrome Dev Tools to test your code! Hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7562649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does the Java compiler only report one kind of error at a time? I've a snippet class T{ int y; public static void main(String... s){ int x; System.out.println(x); System.out.println(y); } } Here there are two error, but on compilation why only one error is shown? The error shown is: non-static variable y cannot be referenced from a static context System.out.println(y); ^ But what about the error variable x might not have been initialized System.out.println(x); ^ A: @Greg Hewgill has nailed it. In particular, the checks for variables being initialized, exceptions being declared, unreachable code and a few other things occur in a later pass. This pass doesn't run if there were errors in earlier passes. And there's a good reason for that. The earlier passes construct a decorated parse tree that represent the program as the compiler understands it. If there were errors earlier on, that tree will not be an accurate representation of the program as the developer understands it. (It can't be!). If the compiler then were to go on to run the later pass to produce more error messages, the chances are that a lot of those error messages would be misleading artifacts of the incorrect parse tree. This would only confuse the developer. Anyway, that's the way that most compilers for most programming languages work. Fixing some compilation errors can cause other (previously unreported) errors to surface. A: The Dragon Book ("Compilers: Principles, Techniques, and Tools" by Aho, Sethi, and Ullman) describe several methods that compiler writers can employ to try to improve error detection and reports when given input files that don't conform to the language specification. Some of the techniques they give: * *Panic mode recovery: skip all input tokens in the input stream until you have found a "synchronizing token" -- think of ;, }, or end statement and block terminators or separators, or do, while, for, function, etc. keywords that can show intended starts of new code blocks, etc. Hopefully the input from that point forward will make enough sense to parse and return useful error messages. *Phrase level recovery: guess at what a phrase might have meant: insert semicolons, change commas to semicolons, insert = assignment operators, etc., and hope the result makes enough sense to parse and return useful error messages. *Error productions: in addition to the "legitimate" productions that recognize allowed grammar operators, include "error productions" that recognize mistakes in the language that would be against the grammar, but that the compiler authors recognize as very likely mistakes. The error messages for these can be very good, but can drastically grow the size of the parser to optimize for mistakes in input (which should be the exception, not the common case). *Global correction: try to make minimal modifications to the input string to try to bring it back to a program that can be parsed. Since the corrections can be made in many different ways (inserting, changing, and deleting any number of characters), try to generate them all and discover the "least cost" change that makes the program parse well enough to continue parsing. These options are presenting in the chapter on parsing grammars (page 161 in my edition) -- obviously, some errors are only discovered after the input file has been parsed, but is beginning to be converted into basic blocks for optimization and code generation. Any errors that occur in the earlier syntactic levels will prevent the typical compiler from starting the code optimization and generation phases, and any errors that might be detected in these phases must wait for fixed input before they can be run. I strongly recommend finding a copy of The Dragon Book, it'll give you some sympathy and hopefully new-found respect for our friendly compiler authors. A: The Java compiler compiles your code in several passes. In each pass, certain kinds of errors are detected. In your example, javac doesn't look to see whether x may be initialised or not, until the rest of the code actually passes the previous compiler pass. A: The whole point of an error is that the compiler doesn't know how to interpret your code correctly. That's why you should always ignore errors after the first one, because the compiler's confusion may result in extra/missing errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: CSS problem, showing unexpected background repeat in Internet explorer I have a class which is used to show correct message. This class works great in all browser, except I found error in Internet Explorer 8. .success{ border:#060 1px solid; margin-left:25%; margin-right:25%; padding:7px; background-color:#D9FF80; background-image:url(http://localhost/naju/home/css/css_img/ok.png); background-position:left; background-repeat:no-repeat; padding-left:30px; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; font-size:13px; color:#003300; font-weight:bold; -moz-border-radius:5px 5px 5px 5px; -moz-box-shadow:0 5px 3px #DDDDDD; -webkit-border-radius:5px 5px 5px 5px; behavior: url(border-radius.htc); } As I've showed above, the class contains the external behavior (border-radius.HTC), this shows rounded border in internet explorer too. But my problem is that, If I keep the line: behavior: url(border-radius.htc); Internet explorer shows background repeat. But above I set background repeat: no-repeat. If I remove behavior, then it is fine. but this problem is only at Internet Explorer. I've no idea, why it is going so...How to stop the unexpected background repeat in internet explorer ? plz any help? Contents of HTC file is below: --Do not remove this if you are using-- Original Author: Remiz Rahnas Original Author URL: http://www.htmlremix.com Published date: 2008/09/24 Changes by Nick Fetchak: - IE8 standards mode compatibility - VML elements now positioned behind original box rather than inside of it - should be less prone to breakage Published date : 2009/11/18 <public:attach event="oncontentready" onevent="oncontentready('v08vnSVo78t4JfjH')" /> <script type="text/javascript"> // findPos() borrowed from http://www.quirksmode.org/js/findpos.html function findPos(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return({ 'x': curleft, 'y': curtop }); } function oncontentready(classID) { if (this.className.match(classID)) { return(false); } if (!document.namespaces.v) { document.namespaces.add("v", "urn:schemas-microsoft-com:vml"); } this.className = this.className.concat(' ', classID); var arcSize = Math.min(parseInt(this.currentStyle['-moz-border-radius'] || this.currentStyle['-webkit-border-radius'] || this.currentStyle['border-radius'] || this.currentStyle['-khtml-border-radius']) / Math.min(this.offsetWidth, this.offsetHeight), 1); var fillColor = this.currentStyle.backgroundColor; var fillSrc = this.currentStyle.backgroundImage.replace(/^url\("(.+)"\)$/, '$1'); var strokeColor = this.currentStyle.borderColor; var strokeWeight = parseInt(this.currentStyle.borderWidth); var stroked = 'true'; if (isNaN(strokeWeight)) { strokeWeight = 0; strokeColor = fillColor; stroked = 'false'; } this.style.background = 'transparent'; this.style.borderColor = 'transparent'; // Find which element provides position:relative for the target element (default to BODY) var el = this; var limit = 100, i = 0; while ((typeof(el) != 'unknown') && (el.currentStyle.position != 'relative') && (el.tagName != 'BODY')) { el = el.parentElement; i++; if (i >= limit) { return(false); } } var el_zindex = parseInt(el.currentStyle.zIndex); if (isNaN(el_zindex)) { el_zindex = 0; } //alert('got tag '+ el.tagName +' with pos '+ el.currentStyle.position); var rect_size = { 'width': this.offsetWidth - strokeWeight, 'height': this.offsetHeight - strokeWeight }; var el_pos = findPos(el); var this_pos = findPos(this); this_pos.y = this_pos.y + (0.5 * strokeWeight) - el_pos.y; this_pos.x = this_pos.x + (0.5 * strokeWeight) - el_pos.x; var rect = document.createElement('v:roundrect'); rect.arcsize = arcSize +'px'; rect.strokecolor = strokeColor; rect.strokeWeight = strokeWeight +'px'; rect.stroked = stroked; rect.style.display = 'block'; rect.style.position = 'absolute'; rect.style.top = this_pos.y +'px'; rect.style.left = this_pos.x +'px'; rect.style.width = rect_size.width +'px'; rect.style.height = rect_size.height +'px'; rect.style.antialias = true; rect.style.zIndex = el_zindex - 1; var fill = document.createElement('v:fill'); fill.color = fillColor; fill.src = fillSrc; fill.type = 'tile'; rect.appendChild(fill); el.appendChild(rect); var css = el.document.createStyleSheet(); css.addRule("v\\:roundrect", "behavior: url(#default#VML)"); css.addRule("v\\:fill", "behavior: url(#default#VML)"); isIE6 = /msie|MSIE 6/.test(navigator.userAgent); // IE6 doesn't support transparent borders, use padding to offset original element if (isIE6 && (strokeWeight > 0)) { this.style.borderStyle = 'none'; this.style.paddingTop = parseInt(this.currentStyle.paddingTop || 0) + strokeWeight; this.style.paddingBottom = parseInt(this.currentStyle.paddingBottom || 0) + strokeWeight; } if (typeof(window.rounded_elements) == 'undefined') { window.rounded_elements = new Array(); if (typeof(window.onresize) == 'function') { window.previous_onresize = window.onresize; } window.onresize = window_resize; } this.element.vml = rect; window.rounded_elements.push(this.element); } function window_resize() { if (typeof(window.rounded_elements) == 'undefined') { return(false); } for (var i in window.rounded_elements) { var el = window.rounded_elements[i]; var strokeWeight = parseInt(el.currentStyle.borderWidth); if (isNaN(strokeWeight)) { strokeWeight = 0; } var parent_pos = findPos(el.vml.parentNode); var pos = findPos(el); pos.y = pos.y + (0.5 * strokeWeight) - parent_pos.y; pos.x = pos.x + (0.5 * strokeWeight) - parent_pos.x; el.vml.style.top = pos.y +'px'; el.vml.style.left = pos.x +'px'; } if (typeof(window.previous_onresize) == 'function') { window.previous_onresize(); } } </script> A: Your behaviour is causing the problem. These often try and redraw the element, so they're based on very specific css properties and require fixed widths and heights. Try using shorthand to declare your background, and if possible, set a fixed width and height on the element: background: #D9FF80 url(http://localhost/naju/home/css/css_img/ok.png) top left no-repeat; Or use CSS3 PIE, which supports many CSS3 properties: http://css3pie.com/ A: i think it has to do something with png. I had also unwanted repeatings. At first there were no problems. Then I made the image smaller and after that it really didn't matter what I did. It kept repeating :( When I changed the same image to a jpg or a gif it listened to the css settings. my 2 cents ... A: The htc is just a javascript, so anyone with javascript knowledge can tinker around with it. You can edit it in any text editor. The error lies in the htc, when assigning the background repeat, it always puts: fill.type='tile'; What I did was read the background-repeat property and assigned it to a variable, and then depending on the value of the variable, it set the background correctly: find this line => var fillColor=this.currentStyle.backgroundColor; right beneath put: var repeat=this.currentStyle.backgroundRepeat; then find the broken line => fill.type='tile'; and replace it with: if(repeat=='no-repeat')fill.type='Frame'; else fill.type='tile'; That's it! Here's the complete code: --Do not remove this if you are using-- Original Author: Remiz Rahnas Original Author URL: http://www.htmlremix.com Published date: 2008/09/24 Edited by Jorch72 Changes by Nick Fetchak: - IE8 standards mode compatibility - VML elements now positioned behind original box rather than inside of it - should be less prone to breakage Published date : 2009/11/18 <public:attach event="oncontentready" onevent="oncontentready('v08vnSVo78t4JfjH')" /> <script type="text/javascript"> // findPos() borrowed from http://www.quirksmode.org/js/findpos.html function findPos(obj){ var curleft = curtop = 0; if (obj.offsetParent){ do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return({ 'x': curleft, 'y': curtop }); } function oncontentready(classID){ if(this.className.match(classID)){return(false);} if(!document.namespaces.v){document.namespaces.add("v","urn:schemas-microsoft-com:vml");} this.className=this.className.concat(' ',classID); var arcSize=Math.min(parseInt(this.currentStyle['-moz-border-radius']||this.currentStyle['-webkit-border-radius']|| this.currentStyle['border-radius']||this.currentStyle['-khtml-border-radius'])/Math.min(this.offsetWidth,this.offsetHeight),1); var repeat=this.currentStyle.backgroundRepeat var fillColor=this.currentStyle.backgroundColor; var fillSrc=new String(this.currentStyle.backgroundImage.replace(/^url\("(.+)"\)$/, '$1')); var strokeColor=this.currentStyle.borderColor; var strokeWeight=parseInt(this.currentStyle.borderWidth); var stroked='true'; if(isNaN(strokeWeight)){ strokeWeight=0; strokeColor=fillColor; stroked='false'; } this.style.background='transparent'; this.style.borderColor='transparent'; // Find which element provides position:relative for the target element (default to BODY) var el = this; var limit = 100, i = 0; while ((typeof(el) != 'unknown') && (el.currentStyle.position != 'relative') && (el.tagName != 'BODY')) { el = el.parentElement; i++; if (i >= limit) { return(false); } } var el_zindex = parseInt(el.currentStyle.zIndex); if (isNaN(el_zindex)) { el_zindex = 0; } //alert('got tag '+ el.tagName +' with pos '+ el.currentStyle.position); var rect_size = { 'width': this.offsetWidth - strokeWeight, 'height': this.offsetHeight - strokeWeight }; var el_pos = findPos(el); var this_pos = findPos(this); this_pos.y = this_pos.y + (0.5 * strokeWeight) - el_pos.y; this_pos.x = this_pos.x + (0.5 * strokeWeight) - el_pos.x; var rect=document.createElement('v:roundrect'); rect.arcsize = arcSize +'px'; rect.strokecolor = strokeColor; rect.strokeWeight = strokeWeight +'px'; rect.stroked = stroked; rect.style.display = 'block'; rect.style.position = 'absolute'; rect.style.top = this_pos.y +'px'; rect.style.left = this_pos.x +'px'; rect.style.width = rect_size.width +'px'; rect.style.height = rect_size.height +'px'; rect.style.antialias = true; rect.style.zIndex = el_zindex - 1; var fill=document.createElement('v:fill'); fill.color=fillColor; fill.src=fillSrc; fill.type='Frame'; if(repeat=='no-repeat')fill.type='Frame'; else fill.type='tile'; rect.appendChild(fill); el.appendChild(rect); var css=el.document.createStyleSheet(); css.addRule("v\\:roundrect","behavior:url(#default#VML)"); css.addRule("v\\:fill","behavior:url(#default#VML)"); isIE6 = /msie|MSIE 6/.test(navigator.userAgent); // IE6 doesn't support transparent borders, use padding to offset original element if (isIE6 && (strokeWeight>0)) { this.style.borderStyle='none'; this.style.paddingTop=parseInt(this.currentStyle.paddingTop || 0) + strokeWeight; this.style.paddingBottom=parseInt(this.currentStyle.paddingBottom || 0) + strokeWeight; } if(typeof(window.rounded_elements)=='undefined'){ window.rounded_elements = new Array(); if(typeof(window.onresize)=='function'){window.previous_onresize=window.onresize;} window.onresize=window_resize; } this.element.vml=rect; window.rounded_elements.push(this.element); } function window_resize(){ if(typeof(window.rounded_elements)=='undefined'){return(false);} for(var i in window.rounded_elements){ var el = window.rounded_elements[i]; var strokeWeight = parseInt(el.currentStyle.borderWidth); if (isNaN(strokeWeight)){strokeWeight=0;} var parent_pos=findPos(el.vml.parentNode); var pos=findPos(el); pos.y=pos.y+(0.5*strokeWeight)-parent_pos.y; pos.x=pos.x+(0.5*strokeWeight)-parent_pos.x; el.vml.style.top=pos.y+'px'; el.vml.style.left=pos.x+'px'; } if(typeof(window.previous_onresize)=='function'){window.previous_onresize();} } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7562657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Picking up custom objects from dropdownlist I am having an issue with picking up custom data types from a drop down lists. To make this as easy to understand as possible, I'll use a simple example of what I want to be able to do So say I have a custom data type (Say of type Dog). Dog contains a name, breed and age. I store each instance of a dog in an ArrayCollection: [Bindable] private var dogData : ArrayCollection; This ArrayCollection holds 1..N Dog objects with the respective information. Now having a dropdown like so: <s:DropDownList x="81" y="178" id="dogSelected" prompt="Dog Selected:" dataProvider="{dogData}" labelField="dogNameData" /> the dogNameData would hypothetically come from a custom ActionScript class that has the 'name' field of the Dog in that object. Now I want to select a certain dog from the dropdown. I tried to just do it this way: var theDog : Dog; theDog = dogSelected.selectedItem; However, ActionScript does not seem to like this. Now, I read around and found out that using the label field is the way to be able to select this. I have been unable to select the dog item, so I can then bind it to: var selectedDogBreed : String; //var theDog : Dog = the selected object from my drop down selectedDogBreed = theDog.breed Would anyone be able to help me be able to select this object from the drop down? Much thanks in advance. Also to note, the ArrayCollection is dynamically generated. In my actual application I am trying to figure this out for, my array of custom data is dynamic. Nothing is hard coded A: To access the selectedItem of a drop down; you'll have to cast it as the type you want: var theDog : Dog; theDog = dogSelected.selectedItem as Dog The labelfield has nothing to do with accessing the selectedItem. The labelField is just used by the default itemRenderer to decide what value to display in the drop down. IF you're not seeing any text displayed in the drop down; or seeing [object object] or something similar, then that is where labelField comes into play. A: Have you tried? trace( 'name ' + (dogData[dogSelected.selectedIndex] as Dog).name ) or without type casting trace( 'name ' + dogSelected.selectedItem.name ) If this does not work then post your error codes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: calling Oracle stored procedures in R - how to get the result set? Looking for an example for calling Oracle stored proc using R, and returning a result set. I'm using RJDBC library, dbGetQuery to call Sybase procs and point the results to a variable, and this works the same for Oracle select stmts. However, I don't see how to get this to return Oracle result sets from an Oracle stored proc (i.e., from the sys_refcursor out param). The only examples I find for retrieving data from Oracle involve "select columns from table". Searching in google was led me to "dbCallProc – Call an SQL stored procedure" which sounds very promising, but every ref I found to it indicates that it is "Not yet implemented." Any pointers or examples for using procs? Greatly appreciated. Don't know why Oracle always has to be such a challenge for retrieving result sets.... Thanks, Mike UPDATE: I'd take an example that simply called an Oracle stored proc. Are Oracle procs simply not supported currently in RJDBC? A: I can't help you specifically with R, but you say you're having issues in calling Oracle procedures that use OUT params as sys_refcursors. You also indicate this ability may not be implemented yet. You do say, however, that you can "select columns from table" just fine. So, I propose changing the procedures to pipelined function calls, and then doing a simple select to get your data from Oracle. A small example: CREATE OR REPLACE package pkg1 as type t_my_rec is record ( num my_table.num%type, val my_table.val%type ); type t_my_tab is table of t_my_rec; function get_recs(i_rownum in number) return t_my_tab pipelined; END pkg1; The package body: create or replace package body pkg1 as function get_recs(i_rownum in number) return t_my_tab pipelined IS my_rec t_my_rec; begin -- get some data -- implement same business logic as in procedure for my_rec in (select num, val from my_table where rownum <= i_rownum) loop pipe row(my_rec); end loop; return; end get_recs; end pkg1; Usage: select * from table(pkg1.get_recs(3)); Or: select num, val from table(pkg1.get_recs(3)); This would return 3 rows of data, just as a procedure would return the same data. Only this way you can get it from a select statement (which you seem to be able to handle from R). Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: min/max number of records on a B+Tree? I was looking at the best & worst case scenarios for a B+Tree (http://en.wikipedia.org/wiki/B-tree#Best_case_and_worst_case_heights) but I don't know how to use this formula with the information I have. Let's say I have a tree B with 1,000 records, what is the maximum (and maximum) number of levels B can have? I can have as many/little keys on each page. I can also have as many/little number of pages. Any ideas? (In case you are wondering, this is not a homework question, but it will surely help me understand some stuff for hw.) A: I don't have the math handy, but... Basically, the primary factor to tree depth is the "fan out" of each node in the tree. Normally, in a simply B-Tree, the fan out is 2, 2 nodes as children for each node in the tree. But with a B+Tree, typically they have a fan out much larger. One factor that comes in to play is the size of the node on disk. For example, if you have a 4K page size, and, say, 4000 byte of free space (not including any other pointers or other meta data related to the node), and lets say that a pointer to any other node in the tree is a 4 byte integer. If your B+Tree is in fact storing 4 byte integers, then the combined size (4 bytes of pointer information + 4 bytes of key information) = 8 bytes. 4000 free bytes / 8 bytes == 500 possible children. That give you a fan out of 500 for this contrived case. So, with one page of index, i.e. the root node, or a height of 1 for the tree, you can reference 500 records. Add another level, and you're at 500*500, so for 501 4K pages, you can reference 250,000 rows. Obviously, the large the key size, or the smaller the page size of your node, the lower the fan out that the tree is capable of. If you allow variable length keys in each node, then the fan out can easily vary. But hopefully you can see the gist of how this all works. A: It depends on the arity of the tree. You have to define this value. If you say that each node can have 4 children then and you have 1000 records, then the height is Best case log_4(1000) = 5 Worst case log_{4/2}(1000) = 10 The arity is m and the number of records is n. A: The best and worst case depends on the no. of children each node can have. For the best case, we consider the case, when each node has the maximum number of children (i.e. m for an m-ary tree) with each node having m-1 keys. So, 1st level(or root) has m-1 entries 2nd level has m*(m-1) entries (since the root has m children with m-1 keys each) 3rd level has m^2*(m-1) entries .... Hth level has m^(h-1)*(m-1) Thus, if H is the height of the tree, the total number of entries is equal to n=m^H-1 which is equivalent to H=log_m(n+1) Hence, in your case, if you have n=1000 records with each node having m children (m should be odd), then the best case height will be equal to log_m(1000+1) Similarly, for the worst case scenario: Level 1(root) has at least 1 entry (and minimum 2 children) 2nd level has as least 2*(d-1) entries (where d=ceil(m/2) is the minimum number of children each internal node (except root) can have) 3rd level has 2d*(d-1) entries ... Hth level has 2*d^(h-2)*(d-1) entries Thus, if H is the height of the tree, the total number of entries is equal to n=2*d^H-1 which is equivalent to H=log_d((n+1)/2+1) Hence, in your case, if you have n=1000 records with each node having m children (m should be odd), then the worst case height will be equal to log_d((1000+1)/2+1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PEP 354-like implementation of enums At one point enums were considered by the Python developers to add to the language, but they dropped the feature. Is there some implementation of the PEP 354? — the specification seems pretty robust. A: http://pypi.python.org/pypi/enum/ is the implementation of this PEP. A: The PyPI package enum provides a Python implementation of the data types described in this PEP. Also, an implementation by Barry Warsaw. Finally, PEP 435 has been accepted for Python 3.4, the backport is enum34, and the advanced version is aenum.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Proper way to send username and password from client to server This question is not language specific. I'm curious how to properly send username and password from a website login form to a server. My guess is to hash the password, put username/password in the POST body and send it over HTTPS. What's a better way? For good measure I'll mention a less than ideal method: http://www.somesite.com/login?un=myplaintextusername&pw=myplaintextpassword A: The important parts are that you transmit the form data in the POST body (that way it's not cached anywhere, nor normally stored in any logfiles) and use HTTPS (that way, if you have a good SSL/TLS certificate, nobody can sniff out the password from observing your network traffic). If you do that, there is no big extra benefit in hashing the password, at least not during the transmission. Why do people talk about hashing passwords, then? Because normally you don't want to store the user's password in plaintext form in your server-side database (otherwise the impact of a compromised server is even worse than it would be otherwise). Instead, you usually store a salted/hashed form, and then apply the same salt/hash to the password received via the form data, so that you can compare the two. For more information on salting, see http://en.wikipedia.org/wiki/Salt_(cryptography) (and the links there). A: If you're using HTTPS, then you can send the name and password in a POST body which will be secure from eavesdroppers (assuming you trust SSL). You don't need to hash the password, if you do then the password hash is just as useful as the password itself, so it doesn't buy you anything. A more important question is how you store the password on the server side. Storing a hashed password is only acceptable if you use a good algorithm such as scrypt. But that's still not as good as an advanced protocol such as SRP. A: You should always use HTTPS and avoid homebrewed code. SSL will take care of hashing & encryption. That is the ONLY secure method. Also ensure you're hashing passwords on the server end and storing the hash, not the original password. Then compare the hashes to check logins. This will prevent attackers reading plaintext passwords straight out of your db if its compromised.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: logical operations between chunks of memory? I want to or two big chunks of memory... but it doesn't work Consider I have three char * bm, bm_old, and bm_res. #define to_uint64(buffer,n) {(uint64_t)buffer[n] << 56 | (uint64_t)buffer[n+1] << 48 | (uint64_t)buffer[n+2] << 40 | (uint64_t)buffer[n+3] << 32 | (uint64_t) buffer[n+4] << 24 | (uint64_t)buffer[n+5] << 16 | (uint64_t)buffer[n+6] << 8 | (uint64_t)buffer[n+7];} ... for (unsigned int i=0; i<bitmapsize(size)/8; i++){ uint64_t or_res = (to_uint64(bm_old,i*8)) | (to_uint64(bm,i*8)); memcpy(bm_res+i*sizeof(uint64_t), &or_res, sizeof(uint64_t)); } bm_res is not correct! Have any clue? Thanks, Amir. A: Enclose the definition of to_uint64 in parentheses () instead of braces {} and get rid of the semicolon at the end. Using #define creates a macro whose text is inserted verbatim wherever it's used, not an actual function, so you were attempting to |-together two blocks rather than those blocks' "return values." A: I think you need to advance your output pointer by the correct size: memcpy(bm_res + i * sizeof(uint64_t), &or_res, sizeof(uint64_t)); ^^^^^^^^^^^^^^^^^^^^ Since bm_res is a char-pointer, + 1 advances by just one byte. A: You're incrementing bm_res by one for every eight-byte block you move. Further, you never increment bm or bm_old at all. So you're basically tiling the first byte of or_res over bm_res, which is probably not what you want. More importantly, your code is byte-order sensitive - whether or_res is represented in memory as least-order-byte first or highest-order-byte first matters. I would recommend you just do a byte-by-byte or first, and only try to optimize it if that is too slow. When you do optimize it, don't use your crazy to_uint64 macro there - it'll be slower than just going byte-by-byte. Instead, cast to uint64_t * directly. While this is, strictly speaking, undefined behavior, it works on every platform I've ever seen, and should be byteorder agnostic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Firefox Extension cannot override element events I'm having trouble trying to override a form element's onsubmit event. I have no problem adding a listener with addEventListener, but for my particular case, I need to replace the onsubmit but for some reason when I do, it gives me this error: Error: Component is not available = NS_ERROR_NOT_AVAILABLE My code is simply this: gBrowser.contentDocument.getElementById("theform").onsubmit = function() { return false; }; Essentially I want to prevent the form from submitting, but this code fails and throws the above error. Using addEventListener to return false doesn't seem to stop the form from submitting. Thanks. A: For security reasons, the object returned by getElementById in an extension is an XPCNativeWrapper around the DOM element; it's not the element itself. This results in some important limitations. More details here: Assigning to or reading an on* property on an XPCNativeWrapper of a DOM node or Window object will throw an exception. (Use addEventListener instead, and use "event.preventDefault();" in your handler if you used "return false;" before.) * *https://developer.mozilla.org/en/XPCNativeWrapper#Limitations_of_XPCNativeWrapper
{ "language": "en", "url": "https://stackoverflow.com/questions/7562688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Issues with jQuery on IE9... Using IE9 F12 developer tools, I see these errors in the console: SCRIPT438: Object doesn't support property or method 'getElementsByTagName' jquery.min.js, line 16 character 59007 SCRIPT438: Object doesn't support property or method 'getElementsByTagName' jquery.min.js, line 16 character 59007 These errors may have nothing to do with my issue (even when the troubled code is commented out, this error appears once anyway...). The jQuery stops executing, definitely, because none of the jQuery on the site works in IE9. It works without any issue in FF, Chrome, Safari, and on the Iphone (safari as well). I have narrowed down the code that is breaking things to this below (I know, because everything works fine when this is gone): <script type="text/javascript"> $(document).ready(function() { var $alertdiv = $('<div id = "alertmsg"/>'); /*$alertdiv.text("");*/ $alertdiv.bind('click', function() { $(this).slideUp(200); }); $(document.body).append($alertdiv); $("#alertmsg").slideDown("slow"); setTimeout(function() { $alertdiv.slideUp(200) }, 10000); }); </script> This script, when functioning on other browsers, slides down a twitter-style notification bar with a message, as defined in the alertmsg div. Does anyone see anything that could be causing this problem in IE9 only? A: Ok, it was a bug in older versions of jQuery library ( jQuery Templates not working in IE9 RC )... I referenced the latest jQuery (v1.6.4) - and I was instantly up and running... Thanks all for the help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7562694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check If an object is empty? How can I check if a PHP object is empty (i.e. has no properties)? The built-in empty() does not work on objects according the doc: 5.0.0 Objects with no properties are no longer considered empty. A: ReflectionClass::getProperties http://www.php.net/manual/en/reflectionclass.getproperties.php class A { public $p1 = 1; protected $p2 = 2; private $p3 = 3; } $a = new A(); $a->newProp = '1'; $ref = new ReflectionClass($a); $props = $ref->getProperties(); // now you can use $props with empty echo empty($props); print_r($props); /* output: Array ( [0] => ReflectionProperty Object ( [name] => p1 [class] => A ) [1] => ReflectionProperty Object ( [name] => p2 [class] => A ) [2] => ReflectionProperty Object ( [name] => p3 [class] => A ) ) */ Note that newProp is not returned in list. get_object_vars http://php.net/manual/en/function.get-object-vars.php Using get_object_vars will return newProp, but the protected and private members will not be returned. So, depending on your needs, a combination of reflection and get_object_vars may be warranted. A: Here is the solution:; $reflect = new ReflectionClass($theclass); $properties = $reflect->getProperties(); if(empty($properties)) { //Empty Object } A: Can you elaborate this with some code? I don't get what you're trying to accomplish. You could anyhow call a function on the object like this: public function IsEmpty() { return ($this->prop1 == null && $this->prop2 == null && $this->prop3 == null); } A: I believe (not entirely sure) that you can override the isset function for objects. In the class, you can provide an implemention of __isset() and have it return accordingly to which properties are set. Try reading this: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
{ "language": "en", "url": "https://stackoverflow.com/questions/7562696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why custom intents in android [UPDATE] rephrasing my question. Could anyone please advise, when and how should i make the decision of using a custom intent vs using android's default intents? [ORIGINAL POST] A very very basic question. Could somebody explain in simple terms why do we create custom intents in android? I went through many articles on intents and custom intent creation, and was mentioned android would scan list of intent filters for actions. i don't clearly understand this part. My understanding and questions * *Intents - used as a message pasing framework that glues various components - ok understood *used to start activities and services and listen to various events - ok understood :) but by using a general Intent say ACTION_VIEW vs MY_CUSTOM_ACTION_VIEW - what exactly is the difference? When would we use one over the other? any example please. A: Custom intents are pretty useful, in my experience. For instance, my audio app can receive custom PLAY, RECORD and PAUSE intents. Custom intents make the framework extensible. It allows for innovation in regard to interaction between applications, be it apps from a single dev or third party.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PerformanceCounterCategory to string value I am trying to retrieve the value of my readyboost cache I wrote the following code but it says the value does not exist System.Diagnostics.PerformanceCounterCategory pc; pc = new System.Diagnostics.PerformanceCounterCategory("ReadyBoost Cache"); pc.GetCounters("Bytes cached"); MessageBox.Show(Convert.ToString(pc)); Spelling is correct, I can see the object following this code http://msdn.microsoft.com/en-us/library/2fh4x1xb(v=vs.71).aspx Thanks in advance A: the parameter of GetCounters should be the instance name of the performance Counter. change your code as follows: System.Diagnostics.PerformanceCounterCategory pc; pc = new System.Diagnostics.PerformanceCounterCategory("ReadyBoost Cache"); foreach (PerformanceCounter counter in pc.GetCounters()) { if (counter.CounterName == "Bytes cached") { //to do } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding string concatenation for ListBoxItem I have a listbox and I want to show two properties from my object. For one property it is pretty easy: <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name} "></TextBlock> </DataTemplate> </ListBox.ItemTemplate> However I would like something like Name - GroupName not just Name... I know that it is easy, but I am confused. I don't know how to add two textblocks into the same level of the XAML hierarchy. A: You can do this a couple of ways. One is with a MultiBinding and a StringFormat <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0} - {1}"> <Binding Path="Name" /> <Binding Path="GroupName" /> </MutliBinding> </TextBlock.Text> </TextBlock> The second is option is to set the root element of your DataTemplate to something that can have more than one child, like a StackPanel and have to TextBlock controls each bound to the appropriate value. <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=Name}" /> <TextBlock Text=" - " /> <TextBlock Text="{Binding Path=GroupName}" /> </StackPanel> </DataTemplate> I prefer the first option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to make python script self-executable Possible Duplicate: Calling a python script from command line without typing “python” first I've tried bash$ chmod +x script.py doesn't work. I also remember to put #!usr/bin/env python at the beginning of the script. bash$ ./script.py Does nothing, it just changes my cursor to a cross lol UPDATE: I've fixed #!/usr/bin/python i've also tried chmod a+x script.py still nothing. My script has import commands and uses sys.argv...I've followed the instruction on this link (look at the end of the page). Nothing works A: Here is the list of things to try, in rough order of likelihood: * *Ensure that the shebang line has correct syntax (you've done this already, #!/usr/bin/python). *Make sure the shebang is the first line in the file (not even a blank line or a comment above it). *Verify that /usr/bin/python actually exists and works. Your Python interpreter may be installed elsewhere. Type /usr/bin/python at a prompt and make sure Python starts. Type which python if you don't know where it is installed. *If . is not in your PATH (it may not be), you must run your script with ./script.py because the shell does not look for commands in the current directory by default. *Make sure the executable bit is set on your script (+x, verify with ls -l). *Make sure that you are using LF only line endings in your editor. Shells can be picky, and your shebang line must end with LF only and not CRLF. This is only likely to be a problem if you're using a Windows text editor, but it might be worth checking. *Make sure that your text editor does not silently insert a UTF-8 BOM at the start of the file. Again, this is only likely if you're using Notepad on Windows. A: the "shebang" needs to contain the full path to the executable. You're calling env, which is good, but you haven't given it the full path: start your script like so: #!/usr/bin/env python # ^
{ "language": "en", "url": "https://stackoverflow.com/questions/7562716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Using JLabel with libgdx's Pixmap I was wondering if you anybody knows an easy way to paint a JLabel in a libgdx's Pixmap, instead of using a BufferedImage. I have seen that libgdx uses JLabel in some tools, but I haven't seen any painting procedure, so I took the lazy way of asking before I keep looking. :) A: You can render to a BufferedImage and then copy out the bytes into a buffer which you can use to create a Pixmap. See here. This won't be fast though, and only works on the desktop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android : Getting CURRENT coordinates (not lastKnownLocation) Right now, I only know of one method to do this: - Get last known location - Have the location manager request location updates However, I really only need to get the CURRENT coordinates ONCE right when the application is called, but it's not doing what I want. What's the simplest way to get the current coordinates? Is there something I could call or some code I could use just to get the location RIGHT NOW ? thanks in advance! I'm still a little new with android development. A: What's the simplest way to get the current coordinates? There is no way to get the current coordinates on demand. Is there something I could call or some code I could use just to get the location RIGHT NOW ? No, for three related reasons: * *Not all location technologies are low power. GPS, for example, is a serious battery hog. Hence, GPS is not powered on unless something is actively seeking a GPS fix. *Not all location technologies are instantaneous. GPS, for example, takes some number of seconds to get a fix after being powered on. *No location technology is universally available. GPS, for example, may be unavailable because you are in a large building.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: convert css hover to jquery onclick for div layer We have a header, with username on it. Essentially, for now, the user hovers over there username and precariously moves the mouse onto the div to retain focus, and access different account functionality. But it is crap to be honest, and I wanted to convert it to onclick, ala google style. Here is a screenpic of what we have. Here is what I would like to achieve. Wondering if anyone knows how to do this. Sample fiddle here: http://jsfiddle.net/ozzy/WkLBF/ Essentially, I want it so user clicks on the name and the div panel displays and remains until they click again. Any help appreciated, we use jquery if thats any consolation ( this demo uses no javascript at all at present ) A: Well... this will work as far as you have described, but I'm not sure it's exactly what you want. :P Could you expound? Demo $(".category-filter>li").click(function(){ $(this).children("ul").toggle(); }); A: http://jsfiddle.net/WkLBF/25/ Javascript: jQuery(document).ready(function($){ $('ul li a').live('click', function(){ if($('.category-filter>li:hover>ul').css('display')=='none') { $('.category-filter>li:hover>ul').css('display', 'block'); $(this).addClass('userbox-on'); } else { $('.category-filter>li:hover>ul').css('display', 'none'); $(this).removeClass('userbox-on'); } }); }); CSS: .userbox-on { border: 1px solid red; border-bottom: none; background-color: #fff; padding: 5px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the value from only selected checkbox I am trying to get the value from a checkbox using javascript. I want only one checkbox value to be passed to the javascript function, and if multiple are selected, an alert box informing that only one box can be checked for the function. I've tried this: var publish_trigger = document.querySelector("#publish_trigger"); publish_trigger.onclick = function() { var _posts = document.getElementsByName('post_id[]'); var check = _posts.checked; var boxes = _posts.length; var txt = ""; if(check.length > 1) { alert("Only one at a time"); } else { for (i = 0; i < boxes; i++) { if (_posts[i].checked) { txt = txt + _posts[i].value + " " } } } alert(txt); return false; } A: This code is wrong: var _posts = document.getElementsByName('post_id[]'); var check = _posts.checked; getElementsByName() returns a NodeList (effectively an array) of elements, so your variable _posts doesn't have a checked property. You need to loop through _posts to count the checked property on the individual elements within _posts. You already have a for loop so add the validation in there: var count = 0; for (var i = 0; i < boxes; i++) { if (_posts[i].checked) { if (++count > 1) { alert("Only one checkbox may be checked at a time."); return false; } // I don't know what you're trying to do with the following line // but I've left it in. txt = txt + _posts[i].value + " " } } (Note: unrelated to your question, you should declare the loop counter i within your function otherwise it will be global and might lead to hard to debug problems if you are using it in other places too.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UTC DateTime problems I currently store all dateTimes in the DB as UTC dates. Each users time zone offset is also stored in the DB. When I retrieve a Date it is converted back to their local date using this offset. The problem occurs when I retrieve a date using an ajax call. The date (which is already converted using the offset) is, I think, returned as a Java Date object. The browser then decides to mess with my Date adding the clients computers time zone offset to the Date object. This is causing dates to be a day ahead of what they should be if the time component is more than 11.59am. The only solution I can come up with is to pass them as strings in which case this of course wouldn't happen. This is a laaaast resort for me though and I would love to find a better solution or workaround for this problem. A: Your browser is not messing with the dates given that browsers don't have a native date transfer variable. You have something else that is doing that. How are you sending your dates in ajax? Json? Json will only send numbers or strings. XML will only send strings. Something is converting your sent date into a javascript date object, find out what it is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Ruby, gaps in time for array of times I have query (for a MongoDB database) which returns objects which have been mapreduced, the objects are reported every 15 minutes, but the issue is that if say we have a critical error in one of servers that period of time will be unaccounted for. Take this array as an example: [ {:timestamp=>2011-09-26 19:00:00 UTC, :count=>318}, {:timestamp=>2011-09-26 19:15:00 UTC, :count=>308}, {:timestamp=>2011-09-26 19:30:00 UTC, :count=>222}, {:timestamp=>2011-09-26 19:45:00 UTC, :count=>215}, {:timestamp=>2011-09-26 20:00:00 UTC, :count=>166}, {:timestamp=>2011-09-26 21:15:00 UTC, :count=>149}, {:timestamp=>2011-09-26 21:30:00 UTC, :count=>145}, {:timestamp=>2011-09-26 21:45:00 UTC, :count=>107}, {:timestamp=>2011-09-26 22:00:00 UTC, :count=>137}, {:timestamp=>2011-09-26 22:15:00 UTC, :count=>135}, {:timestamp=>2011-09-26 22:30:00 UTC, :count=>191}, {:timestamp=>2011-09-26 22:45:00 UTC, :count=>235} ] You'll notice that the times are missing for the time range: {:timestamp=>2011-09-26 20:15:00 UTC}, {:timestamp=>2011-09-26 20:30:00 UTC}, {:timestamp=>2011-09-26 20:45:00 UTC}, {:timestamp=>2011-09-26 21:00:00 UTC} How can I take the top as the input and deduce that those would be the missing rows? The time increments will always be 15 minutes, and its actually a real date object not a string like that. I just can't picture how to iterate over this. Any help would be very appreciated. A: The easiest way I can think of is to order the array by the time stamp, and then do something like the following: missing_times = [] reports.each_with_index do |report, index| if reports[index + 1] if report.timestamp.advance(minutes: 15) < report[index + 1].timestamp i = 0 while(report.timestamp.advance(minutes: 15*i) < report[index+1].timestamp) missing_times << report.timestamp.advance(minutes: 15*i) end end end end I had previously written similar code to find half hour gaps in a series of appointments Although it may look like my solution will loop multiple times over the 15 minute increments between reports.first and reports.last, it will actually loop only once over all available increments between reports.first and reports.last A: Rather than doing multiple loops within loops, it'd be more efficient with large data sets if you create an array of the total timespan in 15 minute increments, and just compare against your report set and remove any matches. start_time = report.first span = ((report.last - start_time)/60/15).to_i # this gives the number of 15min blocks test_array = [] span.times do |i| test_array << start_time + i*15.minutes end report.each do |r| test_array.delete(r) # or in your case, r.timestamp end I think it works, but couldn't think of a good way to make a reference table of timestamps, so I hacked my way up there. A: Simply start at the first timestamp, then increment by 15 minutes, verify that that entry exists, and keep going until you reach the last timestamp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: RGBImageFilter Produces All Black Empty Images I'm trying to use the RGBImageFilter to produce a simple transparency effect on an image, however during testing I found that all of my filtered images come out as blank with black backgound. I simplified my filter to a simple "No Operation" filter that just returns the RGB value that was passed in. Even this simplified NoOp filter produces a blank image. I've tried this with importing and exporting both JPG and PNG with the same affect. I've tried various example filters off the internet that produce the same all black image problem. Has anyone encountered this before? The "load status" and the "write status" below are both returning true so I know from MediaTracker that the original image is loading fully and that the produced image is writing successfully. Thanks in advance for any help! Here is the code: import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.io.File; import javax.imageio.ImageIO; import javax.swing.ImageIcon; class NoOpFilter extends RGBImageFilter { public NoOpFilter() { canFilterIndexColorModel = true; } public int filterRGB(int x, int y, int rgb) { return rgb; } public static void main(String[] args) throws Exception{ String originalImageLocation = args[0]; String baseFileName = args[1]; String directory = args[2]; ImageIcon originalImage = new ImageIcon(Toolkit.getDefaultToolkit().getImage(originalImageLocation)); NoOpFilter filter2 = new NoOpFilter(); ImageProducer ip = new FilteredImageSource(originalImage.getImage().getSource(), filter2); Image filteredImage = Toolkit.getDefaultToolkit().createImage(ip); System.out.println("Load Status: " + ( originalImage.getImageLoadStatus() == java.awt.MediaTracker.COMPLETE)); BufferedImage bim = new BufferedImage( originalImage.getIconWidth(),originalImage.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bim.createGraphics(); g2.drawImage(filteredImage, 0, 0, null); g2.dispose(); File file = new File(directory + File.separator + baseFileName + ".png"); file.createNewFile(); boolean status = ImageIO.write(bim, "png", file); System.out.print("write() status: " + status); } } A: Here is the fix that worked for me. Right after creating the fileredImage above, it was necessary to actually add the filtered image to a JLabel and the JLabel to a JFrame in order to force it to be rendered to screen first before writing it into my buffer and saving to disk: ... Image filteredImage = Toolkit.getDefaultToolkit().createImage(ip); ImageIcon swingImage = new ImageIcon(filteredImage); JFrame frame = new JFrame(); JLabel label = new JLabel(swingImage); frame.add(label); frame.setVisible(true); frame.dispose(); BufferedImage bim = new BufferedImage( originalImage.getIconWidth(),originalImage.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bim.createGraphics(); g2.drawImage(filteredImage, 0, 0, null); g2.dispose(); File file = new File(directory + File.separator + baseFileName + ".png"); file.createNewFile(); boolean status = ImageIO.write(bim, "png", file); System.out.print("write() status: " + status); } I don't quite yet understand why this can't be done completely off-screen like I wanted to do, however it was easy enough to dispose the JFrame right after opening it. A better solution would not require using UI components to do this since I don't really need anything displayed on screen in this case and just want the end product. Thanks to Hovercraft for pointing me in the right direction. A: You have to call prepareImage, then you don't have to use the JLabel-workaround. Image filteredImage = Toolkit.getDefaultToolkit().createImage(ip); Toolkit.getDefaultToolkit().prepareImage(filteredImage, -1, -1, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In MySQL, MyISAM, Is it possible to alter table with partition into multiple hard drive? In MySQL, MyISAM, Is it possible to alter table with partition into multiple hard drive ? My hard drive is nearly used up its disk space. is there anyone facing this problem and how do you solve it? A: Yes, it's possible to partition a table over multiple drives. Have a look at the official manual, which covers this subject in depth. http://dev.mysql.com/doc/refman/5.5/en/partitioning.html Here's an example to partition an existing table over multiple drives: ALTER TABLE mytable PARTITION BY RANGE (mycolumn)( PARTITION p01 VALUES Less Than (10000) DATA DIRECTORY = "/mnt/disk1" INDEX DIRECTORY = "/mnt/disk1", PARTITION p02 VALUES Less Than (20000) DATA DIRECTORY = "/mnt/disk2" INDEX DIRECTORY = "/mnt/disk2", PARTITION p03 VALUES Less Than MAXVALUE DATA DIRECTORY = "/mnt/disk3" INDEX DIRECTORY = "/mnt/disk3" ); Mind that this needs NO_DIR_IN_CREATE to be off. It doesn't seem to work in windows, and it doesn't seem to work with InnoDB. If you run out of diskspace on your last partition, you can split it with following statement: ALTER TABLE mytable REORGANIZE PARTITION p03 INTO ( PARTITION p03 VALUES Less Than (30000) DATA DIRECTORY = "/mnt/disk3" INDEX DIRECTORY = "/mnt/disk3", PARTITION p04 VALUES Less Than MAXVALUE DATA DIRECTORY = "/mnt/disk4" INDEX DIRECTORY = "/mnt/disk4" ); A: You can move the entire mysql data directory. Change the datadir option in /etc/mysql/my.cnf. If you want to just move one database, you can stop the server, move the directory (/var/lib/mysql/DATABASE_NAME) somewhere else, then add a symlink to the new location (ln -s NEW_LOCATION /var/lib/mysql/DATABASE_NAME). Make certain to make backups!!!!!! Before messing with this!!!!! (mysqldump --all-databases as a user that has access to everything, root probably.) A: The trick is to create partitions like you'd usually do, move selected partitions to other harddrives and symlink them back to /var/lib/mysql.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android, Doing the AnimationDrawable from the docs... not working :( I am trying to get this example working: http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html but as it starts, it crashes (force closes) and I am not really sure where the problem is as I am new to this. My code: (Java file) package com.ryan.test; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.widget.ImageView; public class TestAnimationActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image); img.setBackgroundResource(R.drawable.spin_animation); AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); frameAnimation.start(); setContentView(R.layout.main); } } Animation XML file <?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false"> <item android:drawable="@drawable/note0" android:duration="50" /> <item android:drawable="@drawable/note1" android:duration="50" /> </animation-list> Main.xml file <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/note0" android:id="@+id/spinning_wheel_image"></ImageView> </LinearLayout> Note that the animation xml file is in res/drawable-hdpi, putting it in the res/anim folder was giving me errors. Also note I am an Android noobie ;) Thanks! Ryan EDIT; There IS a bug in the demo code: http://code.google.com/p/android/issues/detail?id=1818 so i modified the code: pastebin.com/ZtLf8J87 and it works ;) A: The animation xml should always decide in res/anim. The reason it is throwing an error is due to the fact that you are using ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image); before setting the content view i.e setContentView(R.layout.main); For tracking the errors and debugging use Logcat.You may find that in Eclipse at following location. Windows => Open Perspective => Logcat
{ "language": "en", "url": "https://stackoverflow.com/questions/7562748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to force container elements to contain horizontal content? Here's an example of what I'm trying to work with: http://jsfiddle.net/U2YkF/3/ I need #container to expand to fit #right when #right extends off the right hand side of the screen. Clearfix doesn't seem to be the answer as I've tried that: it only affects the vertical content. A: try this #container { outline: 1px solid red; min-width: 100%; height: 50px; display:inline-block; } A: I was able to achieve what you needed with a few lines of JQuery: x1=$("#right").width(); x2=$("#left").width(); $("#container").width(x1+x2); A: The simplest method is to add float: left to #container. http://jsfiddle.net/U2YkF/6/
{ "language": "en", "url": "https://stackoverflow.com/questions/7562755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3 - link/button to run ajax request without redirecting What's the best way for a link to run an ajax command (I'm using jquery in Rails 3.1)? So far I am trying to use a link to run code via the controller action "update_me." views/products/new.html.erb has the following line: <%= link_to "Update", :action => 'update_me' %> In my products controller, I have: def update_me logger.debug 'ajax code will be here' end But this gives a missing template error: Template is missing Missing template products/update_me, application/update_me with {:handlers=>[:erb, :builder, :coffee], :formats=>[:html], :locale=>[:en, :en]}. Searched in: * "/home/ubuntu/code/preevio/app/views" * "/home/ubuntu/.rvm/gems/ruby-1.9.2-p290@rails31/gems/devise-1.4.3/app/views" Why do I need to have a update_me.html.erb in my views? I assume that's what they want. Can't I just launch the code in the controller action/method without having to have a view for it? Or am I approaching this the wrong way? A: I know this answer is a bit late, but I post it for anyone else who may get here trying to do something similar. If you change your line of html to <%= link_to "Update", :action => 'update_me', :remote => true %> That should have the link to the provided action and do the ajax call for you. You can look at the provided link to see the docs. http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to A: Since Rails has convention over configuration, Rails expects an appropriate view for the action in the controller. If you want to render nothing: http://guides.rubyonrails.org/layouts_and_rendering.html#using-render render :nothing => true
{ "language": "en", "url": "https://stackoverflow.com/questions/7562757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Point handling for closed loop searching I have set of line segments. Each contains only 2 nodes. I want to find the available closed cycles which produces by joining line segments. Actually, I am looking for the smallest loop if there exist more than one occurrence. If can, please give me a good solution for this. So, for example I have added below line list together with their point indices to get idea about m case. (Where First value = line number, second 2 values are the point indices) 0 - 9 11 1 - 9 18 2 - 9 16 3 - 11 26 4 - 11 45 5 - 16 25 6 - 16 49 7 - 18 26 8 - 18 25 9 - 18 21 10 - 25 49 11 - 26 45 So, assume I have started from the line 1. That is I have started to find connected loops from point 9, 18. Then, could you please explain (step by step) how I can get the "closed loops" from that line. A: Well, I don't see any C++ code, but I'll try to suggest a C++ solution (although I'm not going to write it for you). If your graph is undirected (if it's directed, s/adjacent/in-edges' vertices/), and you want to find all the shortest cycles passing through some vertex N, then I think you could follow this procedure: G <= a graph N <= some vertex in G P <= a path (set of vertexes/edges connecting them) P_heap <= a priority queue, ascending by distance(P) where P is a path for each vertex in adjacent(N): G' = G - edge(vertex, N) P = dijkstraShortestPath(vertex, N, G') push(P, P_heap) You could also just throw out all but the shortest loop, but that's less succinct. As long as you don't allow negative edge weights (which, since you'll be using line segment length for weights, you don't), I think this should work. Also, fortunately Boost.Graph provides all of the necessary functionality to do this in C++ (you don't even have to implement Dijkstra's algorithm)! You can find documentation about it here: http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/table_of_contents.html EDIT: you will have to create the graph from that data you listed first before you can do this, so you'll just define your graph's property_map accordingly and make sure the distance between a vertex you're about to insert and all vertexes currently in the graph is greater than zero, because otherwise the vertex is already in the graph and you don't want to insert it again. Happy graphing!
{ "language": "en", "url": "https://stackoverflow.com/questions/7562768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dragon Curve in Python I created a program to draw a dragon curve using turtle graphics.. but my result doesn't really look like the picture does in the link: One problem I noticed is that I want to save the produced string into the variable newWord.. but I can't use newWord as a parameter in my function drawit, which actually draws lines based on the string. When I try to do that I get the error "global variable newWord not defined." So in my code I just copied the output of newWord to be drawn, without actually passing the variable that I wanted to pass. I'm not sure if the problem is with my createWord function or if I'm just not 'drawing enough' in drawit. import turtle def createWord(max_it, axiom, proc_rules): word = axiom t = 1 while (t < max_it): word = rewrite(word, proc_rules) t=t+1 newWord = word def rewrite(word, proc_rules): wordList = list(word) for i in range(len(wordList)): curChar = wordList[i] if curChar in proc_rules: wordList[i] = proc_rules[curChar] return "".join(wordList) def drawit(newWord, d, angle): newWordLs = list(newWord) for i in range(len(newWordLs)): cur_Char = newWordLs[i] if cur_Char == 'F': turtle.forward(d) elif cur_Char == '+': turtle.right(angle) elif cur_Char == '-': turtle.left(angle) else: i = i+1 #sample test of dragon curve def main(): createWord(10, 'FX', {'X':'X+YF','Y':'FX-Y'}) drawit('FX+YF+FX-YF+FX+YF-FX-YF+FX+YF+FX-YF-FX+YF-FX-YF', 20, 90) if __name__=='__main__': main() A: newWord is locally scoped inside of createWord(), so after createWord() is finished, newWord disappears. Consider creating newWord in the global scope so you can modify it with createWord - or better yet, let createWord() return a value, and set newWord to that value. I would think that printing "word" and then using it as a parameter in drawit would result in the same thing as using a variable. It does, but if you want to change the length of your dragon curve, you'll have to copy/paste the string every time instead of simply changing the value of max_it. Edit: My solution with some sexy recursion (= import turtle def dragon_build(turtle_string, n): """ Recursively builds a draw string. """ """ defining f, +, -, as additional rules that don't do anything """ rules = {'x':'x+yf', 'y':'fx-y','f':'f', '-':'-', '+':'+'} turtle_string = ''.join([rules[x] for x in turtle_string]) if n > 1: return dragon_build(turtle_string, n-1) else: return turtle_string def dragon_draw(size): """ Draws a Dragon Curve of length 'size'. """ turtle_string = dragon_build('fx', size) for x in turtle_string: if x == 'f': turtle.forward(20) elif x == '+': turtle.right(90) elif x == '-': turtle.left(90) def main(): n = input("Size of Dragon Curve (int): ") dragon_draw(n) if __name__ == '__main__': main()
{ "language": "en", "url": "https://stackoverflow.com/questions/7562772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Design Question for ActiveAdmin I'm a newbie to the ROR world and I'm trying to use ActiveAdmin to design the Admin Panel for an Artists Portfolio Website. The idea is that each artist has a login/password and can manage assets. The models are set with has_many in the AdminUser table, and belongs_to in the linked models. For example, an AdminUser has_many Videos. There are many linked assets. What would be the best approach so that: * *The currently logged in AdminUser only has access to his own assets? *The currently logged in AdminUser is set as the admin_user_id field for each newluyy created asset? Thank you very much for your help! A: I am not sure if this answer is in time. Q1. The currently logged in AdminUser only has access to his own assets. A1. use cancan for your authorization framework. By default ActiveAdmin doesn't provide the authorization ability for you. so , the key code may looks like: # in your app/models/ability.rb class Ability include CanCan::Ability def initialize(user) can :read, Asset, :admin_user_id => user.id end end for more detailed steps of using Cancan (very easy, you can deal with it in 15 minutes ), please refer to : https://github.com/ryanb/cancan Q2. The currently logged in AdminUser is set as the admin_user_id field for each newluyy created asset. A2: AdminUser is just a "User" model. so, you can call it "current_user" in your view and controller as the regular Devise's way. e.g. #in your controller def create_xx # save the admin_user_id to the newly created asset. Asset.create(:admin_user_id => current_user.id) end for more details of Devise, see its official website: https://github.com/plataformatec/devise
{ "language": "en", "url": "https://stackoverflow.com/questions/7562774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Deriving a class from TestCase throws two errors I have some basic setup/teardown code that I want to reuse in a whole bunch of unit tests. So I got the bright idea of creating some derived classes to avoid repeating code in every test class. In so doing, I received two strange errors. One, I cannot solve. Here is the unsolvable one: AttributeError: 'TestDesktopRootController' object has no attribute '_testMethodName' Here is my base class: import unittest import twill import cherrypy from cherrypy._cpwsgi import CPWSGIApp class BaseControllerTest(unittest.TestCase): def __init__(self): self.controller = None def setUp(self): app = cherrypy.Application(self.controller) wsgi = CPWSGIApp(app) twill.add_wsgi_intercept('localhost', 8080, lambda : wsgi) def tearDown(self): twill.remove_wsgi_intercept('localhost', 8080) And here is my derived class: import twill from base_controller_test import BaseControllerTest class TestMyController(BaseControllerTest): def __init__(self, args): self.controller = MyController() BaseControllerTest.__init__(self) def test_root(self): script = "find 'Contacts'" twill.execute_string(script, initial_url='http://localhost:8080/') The other strange error is: TypeError: __init__() takes exactly 1 argument (2 given) The "solution" to that was to add the word "args" to my __init__ function in the derived class. Is there any way to avoid that? Remember, I have two errors in this one. A: It's because you're overriding __init__() incorrectly. Almost certainly, you don't want to override __init__() at all; you should do everything in setUp(). I've been using unittest for >10 years and I don't think I've ever overridden __init__(). However, if you really do need to override __init__(), remember that you don't control where your constructor is called -- the framework calls it for you. So you have to provide a signature that it can call. From the source code (unittest/case.py), that signature is: def __init__(self, methodName='runTest'): The safe way to do this is to accept any arguments and just pass 'em up to the base class. Here is a working implementation: class BaseTest(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) def setUp(self): print "Base.setUp()" def tearDown(self): print "Base.tearDown()" class TestSomething(BaseTest): def __init__(self, *args, **kwargs): BaseTest.__init__(self, *args, **kwargs) self.controller = object() def test_silly(self): self.assertTrue(1+1 == 2) A: In BaseController's __init__ you need to call unittest.TestCase's __init__ just like you did in TestMyController. The call to construct a TestCase from the framework may be passing an argument. The best way to handle this for deriving classes is: class my_subclass(parentclass): def __init__(self, *args, **kw): parentclass.__init__(self, *args, **kw) ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7562775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: How to deal with race conditions in multi-threading? Here's an example: if (control.InvokeRequired) { control.BeginInvoke(action, control); } else { action(control); } What if between the condition and the BeginInvoke call the control is disposed, for example? Another example having to do with events: var handler = MyEvent; if (handler != null) { handler.BeginInvoke(null, EventArgs.Empty, null, null); } If MyEvent is unsubscribed between the first line and the if statement, the if statement will still be executed. However, is that proper design? What if with the unsubscription also comes the destruction of state necessary for the proper invocation of the event? Not only does this solution have more lines of code (boilerplate), but it's not as intuitive and can lead to unexpected results on the client's end. What say you, SO? A: In my opinion, if any of this is an issue, both your thread management and object lifecycle management are reckless and need to be reexamined. In the first example, the code is not symmetric: BeginInvoke will not wait for action to complete, but the direct call will; this is probably a bug already. If you expect yet another thread to potentially dispose the control you're working with, you've no choice but to catch the ObjectDisposedException -- and it may not be thrown until you're already inside action, and possibly not on the current thread thanks to BeginInvoke. It is improper to assume that once you have unsubscribed from an event you will no longer receive notifications on it. It doesn't even require multiple threads for this to happen -- only multiple subscribers. If the first subscriber does something while processing a notification that causes the second subscriber to unsubscribe, the notification currently "in flight" will still go to the second subscriber. You may be able to mitigate this with a guard clause at the top of your event handler routine, but you can't stop it from happening. A: There are a few techniques for resolving a race condition: * *Wrap the whole thing with a mutex. Make sure that there's a lock that each thread must first acquire before it can even start running in the race. That way, as soon as you get the lock, you know that no other thread is using that resource and you can complete safely. *Find a way to detect and recover from them; This can be very tricky, but some kinds of application work well; A typical way of dealing with this is to keep a counter of the number of times a resource has changed; If you get finished with a task and find that the version number is different from when you started, read the new version and start the task over from the beginning (or just fail) *redesign the application to use only atomic actions; basically this means using operations that can be completed in one step; this often involves "compare-and-swap" operations, or fitting all of the transaction's data into a single disk block that can be written atomically. *redesign the application to use lock-free techniques; This option only makes sense when satisfying hard, real-time constrains is more important than servicing every request, because lock-free designs inherently lose data (usually of some low priority nature). Which option is "right" depends on the application. Each option has performance trade-offs that may make the benefit of concurrency less appealing. A: If this behavior is spreading multiple places in your application, it might deserve to re-design the API, which looks like: if(!control.invokeIfRequired()){ action(action); } Just the same idea as standard JDK library ConcurrentHashMap.putIfAbsent(...). Of course, you need to deal with synchronization inside this new control.invokeIfRequired() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Python 2.7.1 Blogger API problem I recently started writing a simple client using the Blogger API to do some basic posting I implemented the client in Python and used the example code verbatim from the Blogger Developer's Guide to login, get the blog id, and make a new post. I ran the script and everything went fine until I got to this line: return blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id) I got the error message: Traceback (most recent call last): File "cs1121post.py", line 38, in <module> cs1121post() File "cs1121post.py", line 33, in cs1121post return blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id) File "/usr/local/lib/python2.7/dist-packages/gdata/service.py", line 1236, in Post media_source=media_source, converter=converter) File "/usr/local/lib/python2.7/dist-packages/gdata/service.py", line 1322, in PostOrPut headers=extra_headers, url_params=url_params) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 93, in optional_warn_function return f(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/atom/service.py", line 176, in request content_length = CalculateDataLength(data) File "/usr/local/lib/python2.7/dist-packages/atom/service.py", line 736, in CalculateDataLength return len(str(data)) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 377, in __str__ return self.ToString() File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 374, in ToString return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 369, in _ToElementTree self._AddMembersToElementTree(new_tree) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 331, in _AddMembersToElementTree member._BecomeChildElement(tree) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 357, in _BecomeChildElement self._AddMembersToElementTree(new_child) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 342, in _AddMembersToElementTree ExtensionContainer._AddMembersToElementTree(self, tree) File "/usr/local/lib/python2.7/dist-packages/atom/__init__.py", line 224, in _AddMembersToElementTree tree.text = self.text.decode(MEMBER_STRING_ENCODING) AttributeError: 'list' object has no attribute 'decode' By which I'm taking it that ElementTree is at fault here. I installed ElementTree via sudo python setup.py install in case it matters. Is there some known incompatibility between ElementTree and Python v2.7.1? Has this happened to anybody else and how did you get it working? If you need any additional information, please reply to the thread. All the source code that is relevant is basically just the example code from the Developers Guide mentioned above. I haven't modified that at all (not even the variable names). Any input is greatly appreciated. A: The stacktrace is actually pretty clear about this: You're calling decode() on a list instead of a tree element. Try getting the first element from the list and calling decode() on that: firsttext = self.text[0].decode(MEMBER_STRING_ENCODING)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby/Slim: parse Markdown from a YAML file Been struggling for a while with some YAML parsing inside a Slim template. my YAML file contain shortdesc: > markdown: if you want to up the feelgood factor Cuban style, then this Monday night at The Buffalo Bar is for you... But when I output the shortdesc node in my template it's displayed as a string and not interpreted. ("markdown: if you....") Is there a way to parse the YAML output string to interpret the markdown code? If I try p markdown: = shortdesc the template doesn't understand the call to the variable containing the YAML node. Is that even possible? A: Yes it's possible. Just need to use interpolation: p markdown: #{shortdesc} A: It depends on the Markdown Library that you are using. In BlueCloth, it would be something like this: = BlueCloth.new(shortdesc).to_html
{ "language": "en", "url": "https://stackoverflow.com/questions/7562784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: First run popup dialog I am trying to make a popup dialog that only shows after the app's first run that will alert users of the new changes in the app. So I have a dialog popup like this: new AlertDialog.Builder(this).setTitle("First Run").setMessage("This only pops up once").setNeutralButton("OK", null).show(); Once they dismiss it, it won't come back until the next update or they reinstall the app. How can I set the dialog code above to run only once? A: Use SharedPreferences to store the isFirstRun value, and check in your launching activity against that value. If the value is set, then no need to display the dialog. If else, display the dialog and save the isFirstRun flag in SharedPreferences. Example: public void checkFirstRun() { boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true); if (isFirstRun){ // Place your dialog code here to display the dialog getSharedPreferences("PREFERENCE", MODE_PRIVATE) .edit() .putBoolean("isFirstRun", false) .apply(); } } A: Like this you can make a difference between a new install and a update. String StoredVersionname = ""; String VersionName; AlertDialog LoginDialog; AlertDialog UpdateDialog; AlertDialog FirstRunDialog; SharedPreferences prefs; public static String getVersionName(Context context, Class cls) { try { ComponentName comp = new ComponentName(context, cls); PackageInfo pinfo = context.getPackageManager().getPackageInfo( comp.getPackageName(), 0); return "Version: " + pinfo.versionName; } catch (android.content.pm.PackageManager.NameNotFoundException e) { return null; } } public void CheckFirstRun() { VersionName = MyActivity.getVersionName(this, MyActivity.class); prefs = PreferenceManager.getDefaultSharedPreferences(this); StoredVersionname = (prefs.getString("versionname", null)); if (StoredVersionname == null || StoredVersionname.length() == 0){ FirstRunDialog = new FirstRunDialog(this); FirstRunDialog.show(); }else if (StoredVersionname != VersionName) { UpdateDialog = new UpdateDialog(this); UpdateDialog.show(); } prefs.edit().putString("versionname", VersionName).commit(); } A: I use this to display a help dialog on first run. I don't want this to show after an update. That is better suited for a changelog. private void doFirstRun() { SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); if (settings.getBoolean("isFirstRun", true)) { showDialog(DIALOG_HELP); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("isFirstRun", false); editor.commit(); } } A: There is no actual question, but I assume you want to know how to achieve the intended effect. If that's the case, then use a SharedPreference object to get a boolean 'first run' which defaults to true, and set it to false just after the first run. A: loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE); loginPrefsEditor = loginPreferences.edit(); doFirstRun(); private void doFirstRun() { SharedPreferences settings = getSharedPreferences("PREFERENCE", MODE_PRIVATE); if (settings.getBoolean("isFirstRun", true)) { loginPrefsEditor.clear(); loginPrefsEditor.commit(); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("isFirstRun", false); editor.commit(); } } I used this code to ensure that its the first time someone runs the application. The loginPrefsEditor is cleared from data because i have a "Remember Me" Button which stores the data to the sd card. Hope it helps ! A: While the general idea of the other answers is sound, you should keep in the shared preferences not a boolean, but a timestamp of when was the last time the first run had happened, or the last app version for which it happened. The reason for this is you'd likely want to have the first run dialog run also whenthe app was upgraded. If you keep only a boolean, on app upgrade, the value will still be true, so there's no way for your code code to know if it should run it again or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: ASP.NET - how to change requested page names transparently? Very new to this subject and under the gun to come up with a solution. The problem is how I could load one of several versions of the same ASPX page, for any given page. E.g. unknown to the unsuspecting user who requests catalog.aspx, I would actually serve one of catalog_1.aspx, catalog_2.aspx, or catalog_3.aspx, etc. Strange request indeed. It's due to an inherited decade-old product having inlined styles all over the ASPXs. Instead of re-writing the hundreds of ASPXs to be flexible, I'm trying to regexp-replace them to get versions suitable for various screen sizes. I'd then choose the best one after measuring window size at user login (and perhaps store the size in a cookie). I thought this would involve some lower level object like an http handler. Close? LJ Update: I ended up doing this through url rewriting which works much better. The easiest place to do this in asp.net is apparently global.asax, and under Application_BeginRequest event. Call context.RewritePath(newpath, False) to send the request to a different page than requested. In the way I did it, the destination page can change from request to request, and that apparently upsets postbacks, if the recipient of the postback isn't the exact version of the page that generated the viewstate. I tried to turn off viewstate validation but didn't help. So had to prevent flipping between versions once a user's logged in. Hope this helps someone. A: Server.Transfer is probably the quickest way of doing just that. string TransferTo = string.Empty; if( Something ) TransferTo = "catalog_1.aspx"; else if( SomethingElse ) TransferTo = "catalog_2.aspx"; else TransferTo = "catalog_3.aspx"; Server.Transfer( TransferTo, false ); Documentation Note If the subsequent pages have postback controls on them, they will reveal the true URL of the page at that point. If that matters, then this method will not work. A: I don't like this method, but maybe you could use a full-window IFRAME to hold the appropriate page - catalog.aspx would be nothing but a big frame, and you could set the source of that frame in your codebehind.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using grep/gsub To Find First Colon Only I have a long file which is written as ONLY one column. This column contains gene names followed by a colon (:) then by the name of a microRNA fragment. Unfortunately, the microRNA name MAY ALSO contain a colon (:). I want to replace ONLY the first colon with a tab (\t) and then write.table to produce two columns in R. Here is a representative sample of one gene name with multiple microRNAs: CHD5:miR-329/362-3p:2 CHD5:miR-329/362-3p:1 CHD5:miR-30a/30a-5p/30b/30b-5p/30cde/384-5p CHD5:miR-15/16/195/424/497 CHD5:miR-26ab/1297 CHD5:miR-17-5p/20/93.mr/106/519.d CHD5:miR-130/301 CHD5:miR-19 CHD5:miR-204/211 Any suggestions? A: Maybe use sub instead of gsub? A: If x is your column or vector: sub(":", "\t", x) See ?sub, which says ‘sub’ and ‘gsub’ perform replacement of the first and all matches respectively. A: Here's a slightly more complete example if you have your 'inFile' and want 'outFile'... lines <- readLines('inFile') lines <- sub(':', '\t', x) writeLines(lines, 'outFile') A: If you are all right with using sed, you can do the following (assuming your data is in a file named data.txt). sed 's/\([^:]\):/\1 /' data.txt That space after the \1 is really a tab. To insert it in my shell, I needed to do Ctrl-v, <tab>. Here's my result after running the command: CHD5 miR-329/362-3p:2 CHD5 miR-329/362-3p:1 CHD5 miR-30a/30a-5p/30b/30b-5p/30cde/384-5p CHD5 miR-15/16/195/424/497 CHD5 miR-26ab/1297 CHD5 miR-17-5p/20/93.mr/106/519.d CHD5 miR-130/301 CHD5 miR-19 CHD5 miR-204/211
{ "language": "en", "url": "https://stackoverflow.com/questions/7562792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I create a working framework with dylib files in Xcode 4 I have created a new cocoa framework in Xcode, removed all the libraries and files it includes at the beginning except the supporting files. I have 2 files: add.h #ifndef add_add_h #define add_add_h void add(void); #endif and add.c #include <stdio.h> #include "add.h" void add(void) { printf("adfding"); } in build phases I add add.c to compile sources and add.h to compile headers public. The project build without a problem but in the framework there is no dylib file and when I drag and drop the framework to another project it says that dylib file could not be found. dyld: Library not loaded: @rpath/add.framework/Versions/A/add Referenced from: /Users/vjoukov/Desktop/Projects/test/build/Debug/test.app/Contents/MacOS/test Reason: image not found How can I make a simple framework and keep dylib files inside it ? A: I think you're misunderstanding the error message. A .framework works as a dynamic library, but there won't be any Mach-O loadable object file with an actual .dylib filename extension inside the .framework folder. There are a couple of reasons you might be getting that error message from dyld, the dynamic link library loader, at runtime. The first is that you forgot to copy the .frameworks into the built application bundle during the build process. While they can be copied to about any location inside the app bundle, the traditional place is in AppName.app/Contents/Frameworks/. If you haven't done so already, choose Project > New Build Phase > New Copy Files Build Phase. Change the Destination popup to Frameworks like in the image below. You'll then drag the icon of the framework into the folder so that it's copied during the build process. The second and more likely reason the framework can't be found at runtime is that you haven't specified any runpath search paths for your main executable. (This is needed, because, as we saw from your error message, your framework was built using the newer @rpath/ style install name (@rpath/add.framework/Versions/A/add) rather than the older @executable_path/ or @loader_path/ styles). Provided you copy the custom frameworks to the location mentioned above, you'd add a runpath search path entry of @loader_path/../Frameworks, like shown in the image below: The following excerpt that explains how dynamic libraries are found at runtime is from the manpage of dyld: DYNAMIC LIBRARY LOADING Unlike many other operating systems, Darwin does not locate dependent dynamic libraries via their leaf file name. Instead the full path to each dylib is used (e.g. /usr/lib/libSystem.B.dylib). But there are times when a full path is not appropriate; for instance, may want your binaries to be installable in anywhere on the disk. To support that, there are three @xxx/ variables that can be used as a path prefix. At runtime dyld substitutes a dynamically generated path for the @xxx/ prefix. @executable_path/ This variable is replaced with the path to the directory containing the main executable for the process. This is useful for loading dylibs/frameworks embedded in a .app directory. If the main executable file is at /some/path/My.app/Contents/MacOS/My and a framework dylib file is at /some/path/My.app/Contents/Frameworks/Foo.framework/Versions/A/Foo, then the framework load path could be encoded as @executable_path/../Frameworks/Foo.framework/Versions/A/Foo and the .app directory could be moved around in the file system and dyld will still be able to load the embedded framework. @loader_path/ This variable is replaced with the path to the directory containing the mach-o binary which contains the load command using @loader_path. Thus, in every binary, @loader_path resolves to a different path, whereas @executable_path always resolves to the same path. @loader_path is useful as the load path for a framework/dylib embedded in a plug-in, if the final file system location of the plugin-in unknown (so absolute paths cannot be used) or if the plug-in is used by multiple applications (so @executable_path cannot be used). If the plug-in mach-o file is at /some/path/Myfilter.plugin/Contents/MacOS/Myfilter and a framework dylib file is at /some/path/Myfilter.plugin/Contents/Frameworks/Foo.framework/Versions/A/Foo, then the framework load path could be encoded as @loader_path/../Frameworks/Foo.framework/Versions/A/Foo and the Myfilter.plugin directory could be moved around in the file system and dyld will still be able to load the embedded framework. @rpath/ Dyld maintains a current stack of paths called the run path list. When @rpath is encountered it is substituted with each path in the run path list until a loadable dylib if found. The run path stack is built from the LC_RPATH load commands in the depencency chain that lead to the current dylib load. You can add an LC_RPATH load command to an image with the -rpath option to ld(1). You can even add a LC_RPATH load command path that starts with @loader_path/, and it will push a path on the run path stack that relative to the image containing the LC_RPATH. The use of @rpath is most useful when you have a complex directory structure of programs and dylibs which can be installed anywhere, but keep their relative positions. This scenario could be implemented using @loader_path, but every client of a dylib could need a different load path because its relative position in the file system is different. The use of @rpath introduces a level of indirection that simplies things. You pick a location in your directory structure as an anchor point. Each dylib then gets an install path that starts with @rpath and is the path to the dylib relative to the anchor point. Each main executable is linked with -rpath @loader_path/zzz, where zzz is the path from the executable to the anchor point. At runtime dyld sets it run path to be the anchor point, then each dylib is found relative to the anchor point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Can I use email addresses as usernames in django-auth? I'd like to use email addresses as a pseudo-username of sorts while using Django's auth module. Can I do this? User.username is limited to 30 characters which really isn't acceptable for longer email addresses. I know that the User object also has an email_address property, but I'm not sure that this is for authentication. The problem is that username is required, but is too short for my application to be usable. For my application, a pseudonym such as a username doesn't make any sense, so I don't know how I can make this work. Is there a way to do what I'm talking about? A: Generate the username programatically and subclass the auth backend to support emails: from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class CustomAuthBackend(ModelBackend): def authenticate(self, email=None, password=None, username=None, *args, **kwargs): try: user = User.objects.get(email=email) if user.check_password(password): return user except User.DoesNotExist: pass # fallback to login + password return super(CustomAuthBackend, self).authenticate(username=username, password=password, *args, **kwargs)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling a method with an index on ArrayList in c# Ok here is my dilemma, I want to create an array of custom objects but then be able to do something like list[index].method call. as an example: * *program starts *program creates a master array which holds GenericClass< T >(param) *each generic class then creates an array of type T I can get that part to work ok but then when I try to use my object methods such as object[] MasterList = new object[MASTER_LIST_SIZE]; // add contents to MasterList MasterList[index].setValueAt(MethodIndex, value); I get a message that reads object has no method named setValueAt which requires one parameter(s) I will admit that what I am trying to do is rather dumb and I could probably do it easier with reading a text file or something but if there is a way to do it like this I would like to know how or at least what I am missing. A: There are a lot of unknowns about what you are doing but my best guess is that you need to cast the result to the type you need. ((GenericClass<T>)MasterList[index]).setValueAt(MethodIndex, value);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert JSON object to Objective-C Cocoa object? Am developing a cocoa application, where I have to invoke java web scripts and fetch the response of the web script object and convert it into Objective C readable objects. I would then need to manipulate the fetched data for import, print, etc. How to I interact with the web script and convert into cocoa readable objects? Any pointers on the same, will be appreciated. Thanks, Nana A: * *Convert the JSON string into an NSDictionary using tools like yajl, JSONKit or iOS5 JSON *Use https://github.com/elado/jastor to convert this NSDictionary to a real Objective-C class with typed properties, nested properties, arrays etc. A: In iOS 5 native JSON parsing is supported (documentation). In addition you can use a number of third party libraries to download and parse JSON (see JSONKit and HTTPRiot or RestKit) A full reference of awesome libraries can be found here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pointer problems? buffer is a protected void* part of my class. void* ptr; ptr= buffer; if(ptr == pvTxt) return ptr; while (*((unsigned char*)ptr) || *(((unsigned char*)ptr)+1)) ((unsigned char*)ptr)++; return *((unsigned char*)ptr)+1; Everything up to the: ((unsigned char*)ptr)++; return *((unsigned char*)ptr)+1; is fine but I know there is something wrong with the casting? Also in my main I have: g_pvTxt = new unsigned char[BUFSIZE]; memset (g_pvTxt,0,BUFSIZE); Given the question above how do I append an array. Create an array/append to it. Can't use std::vector because it's an embedded system To further explain the loop: After an txt entry there is a null termination. At the end of all entries there is a double null. So, in the while loop if the value the pointer is pointing at is false (either 0 or 00) or ptr || ptr+1, it will increment the counter until it gets to the next spot where I can append values. A: I think you blew it before then. if(ptr = Txt) is assigning Txt to ptr and then testing whether the value is null or not. So the previous statement assigning ptr= buffer; has no effect. And you'll never get past the first return so long as Txt has a value coming in. A: Why don't you just make the cast to unsigned char* only once? unsigned char* ptr= static_cast<unsigned char*>(buffer); if(ptr == pvTxt) return ptr; while (ptr[0] || ptr[1]) // *(ptr+1) would work as well ptr++; return *ptr+1; If you want to append to a buffer, and cannot use std::vector you can do something similar: allocate a bigger buffer, copy everything over and delete the old buffer. A: Also be careful your scan or your response doesn't walk off the end of buffer. I think you mistyped the variable names from your main example, but if you need to resize g_pvTxt you need to use "new" to get one of the newer size (current + append amount) then copy the two pieces to the new one manually, then discard the old array(s).
{ "language": "en", "url": "https://stackoverflow.com/questions/7562826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting all array values from a specific offset and on I have an array that has 120~ or so offsets and I was wondering how you would delete all the values of said array after a certain offset containing a specified string. For example: Offset [68] has the string 'Overflow'. I want to remove everything including 68 and beyond and rebuild the array (with its current sorting in tact). I tried messing around with slice and splice but I can't seem to get it to return the right values. I was also thinking of just grabbing the offset number that contains 'Overflow' and then looping it through a for statement until $i = count($array); but that seems a little more intensive than it should be. Would this be the best way? Or is there some function to do this that I'm just using wrong? A: Use array_slice(). $desired = array_slice($input, 0, $upTo); A: First you need to find the string occurrence in the array, and, if the value was found, trim the array from that point; function removeString($string, $array) { # search for '$string' in the array $found = array_search($string, $array); if ($found === false) return $array; # found nothing # return sliced array return array_slice($array, $found); } And if you need to make the array sequential (to avoid surprises due to missing offsets), you can always add in the first line $array = array_values($array). This will reorganize the array values in a new array with ordered offsets: 0, 1, 2, 3, 4...
{ "language": "en", "url": "https://stackoverflow.com/questions/7562829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Trigger on Insert, Delete, Updated I have the following trigger ALTER TRIGGER [dbo].[RefreshProject] ON [dbo].[Project] AFTER INSERT,DELETE,UPDATE AS BEGIN SET NOCOUNT ON DECLARE @percentage decimal(18,2) DECLARE @ProjectID int DECLARE @TASKID int IF EXISTS(SELECT * FROM Inserted) BEGIN SELECT @ProjectID = Inserted.ProjectID, @TASKID = ISNULL(Inserted.TASKID,-1) from Inserted join Project on Inserted.ScheduleID = Project.ScheduleID END IF EXISTS(SELECT * FROM Deleted) BEGIN SELECT @ProjectID = Deleted.ProjectID,@TASKID = ISNULL(Deleted.TASKID,-1) from Deleted join Project on Deleted.ScheduleID = Project.ScheduleID END BEGIN SET @percentage = (SELECT percentage from Project where ProjectID = @ProjectID) EXEC LoadSummary @percentage,@ProjectID, @TASKID END END For Inserts and updates I am able to get the ProjectID of the modified object, however when an item is deleted, I can not get the ProjectID or TaskID... Any Idea what I'm doing wrong? A: The problem is that your trigger is an AFTER trigger, which means that the row has already been deleted from the Project table by the time the trigger is fired. So, you can't join the deleted view to Project, because the corresponding row won't exist. You will need to assign the variables you want directly from the deleted view. Also, as Mitch's note mentions above, you may want to use a cursor to iterate over all rows in the inserted/deleted views if multiple rows can be updated at a time. Alternatively, you could raise an error at the beginning of your trigger if @@ROWCOUNT is greater than one, to prevent multiple row updates from causing your trigger to misbehave.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python inserting backslashes during regular expression I'm trying to do a regex to substitute in a backslash, but Python seems to be inserting a double-backslash, and I can't make it stop! >>> re.sub('a', '\\ b', 'a') '\\ b' Double backslash is supposed to be backslash (escape + backslash = backslash), but it ends up being literal. If I remove the double slash, it doesn't print one at all: >>> re.sub('a', '\ b', 'b') 'b' How do I get Python to sub in just one backslash? A: It's not inserting a double backslash. That is simply the interactive interpreter showing the string as a string literal. Use print to see the actual string: >>> "\\n" '\\n' >>> print "\\n" \n A: I suppose this isn't an answer (I second Liquid_Fire), but a suggestion: "\\b" -> \b r"\b" -> \b Use r"" raw strings to simplify backslashes in Python. A: Prefix the string with the letter "r". This instructs Python to interpret the string literally. For your code: re.sub('a', r'\ b', 'a') You will often find "r" used with Python and regular expressions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Installing NumPy I have Windows Vista and am running Python 2.7. I am having trouble installing some Python libraries including, NumPy, SciPy, and pygame. I am currently trying to copy the NumPy file straight to my computer (C:\numpy) and then unziping the file there. In a command prompt I then run the code; cd c:\numpy python setup.py config python setup.py install When I get to the "python setup.py config" part, the command prompt says "this is the wrong setup.py file to run" Any suggestions? A: This is the ANSWER for installing numpy on Windows 8 64 bit. All you need is: 1.Python, installed in your system, in my case its c:\Python27, its 2.7 version. 2.Install pip if not available. *download "numpy-1.9.2+mkl-cp27-none-win_amd64.whl" file for 64 bit, you can find this here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy if you don't find it there use mine at: https://github.com/pawanputtaswamy/Libs How to install: 1.open command prompt (Windows + r and type cmd) 2.Go to pip directory, in my case (cd c:\Python27\Scripts\pip.exe) 3.Run the following command: pip.exe install \numpy-1.9.2+mkl-cp27-none-win_amd64.whl Done A: Numpy, Scypy and pygame all have windows installers; You are advised to use these installers in favor of archive versions. Make sure you match the version (3.2, 2.7) and archetecture (i386 or x86_64) as the python binary you have installed. A: Alternatively, depending on your time constraints and situation you could use Enthought's prepackaged python distribution for Windows. The free version: http://www.enthought.com/products/epd_free.php has everything you need except pygame which you should be able to install with easy_install once everything else is in place. A: Open the Python shell and input as such: >>> import pip >>> pip.main(["install","numpy"]) A: In fact,the method of installing numpy is very easy and quick.First,make sure that Python has already been installed.Then,download the numpy module on sites,such as http://sourceforge.net/projects/numpy/files/NumPy/, which provides the numpy module for python2.6. Finally,double click the module,the rest you have to do is just let it go on.and,it will be installed naturally. A: Just go here http://continuum.io/downloads and download the graphical installer. It will install Numpy, Scipy and a tonne of other useful stuff. A: This is a screenshot that can help, Note that I use Ubuntu as operating System
{ "language": "en", "url": "https://stackoverflow.com/questions/7562834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Silverlight wcf ria services : Validation Annotation questions How do i do the equivalent of [Required] in xaml code behind? I have a dataform that autogenerates the fields from a domain service class. Is it possible to add or remove the [Required] validation in the _AutoGeneratingField method? Thanks A: Try to create extension class for your entity, where you can use [Required] attribute. If you need some examples - let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot get selected type from GetTypes I want to initialize classes in the following assembly which are inheriting from the EntityBase class using reflection. I am guessing the lambda expression is correct but I don't know how to get those 2 classes (there are 2 classes in assembly which inherit EntityBase) from types2. Assembly a = Assembly.LoadFrom("X:\\Workspace\\Operations\\ItemSupplierSetupRequest\\Main\\Source\\ItemSupplierSetupRequest.Entity\\bin\\Debug\\xxxx.ItemSupplierSetupRequest.Entity.dll"); IEnumerable<Type> types2 = a.GetTypes().Where(x => x.BaseType.ToString().Equals("xxxx.ItemSupplierSetupRequest.Entity.EntityBase")); I also tried var result = a.GetTypes().Where(x => x.BaseType.FullName.Equals("xxxx.ItemSupplierSetupRequest.Entity.EntityBase")); but don't know how to use or to check if this returns those 2 classes? A: Your queries should probably work. But there is no need to use Equals() or to compare the types using strings. You can use (assuming EntityBase is in a referenced assembly and its namespace is in a using): a.GetTypes().Where(x => x.BaseType == typeof(EntityBase)) Keep in mind this will not return all types that inherit from EntityBase, only those that inherit from it directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: json object referencing I have the following list of search terms in JSON: http://completion.amazon.com/search/complete?method=completion&q=halo&search-alias=aps&mkt=1 [ "halo", [ "halo reach", "halo anniversary", "halo 4", "halo 3", "halo mega bloks", "halo 2", "halo sleepsack", "halo wars", "halo reach xbox 360", "halo combat evolved" ], [ { "nodes" : [ { "name" : "Video Games", "alias" : "videogames" } ] }, {}, {}, {}, {}, {}, {}, {}, {}, {} ], [] ] I am using jQuery to return the results in an autocomplete. My question is, how would I reference the categories (nodes) in the object? I can reference the terms in the first part like so: var myQuery = "harry" , myCount = 0 ; $.ajax({ url : "http://completion.amazon.com/search/complete", type : "GET", cache : false, dataType : "jsonp", success : function (data) { $(data[1]).each(function(index) { alert(data[1][myCount]); myCount++; } ); }, data : { q : myQuery, "search-alias" : "aps", mkt : "1", callback : '?' } }); A: $(data[2][0].nodes).each(function () { alert(this.name) }) Edit: Fixed by question author. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding visibility of a control to 'Count' of an IEnumerable I have a list of objects contained in an IEnumerable<>. I would like to set the visibility of a control based on the count of this list. I have tried: Visibility="{Binding MyList.Count>0?Collapsed:Visible, Mode=OneWay}" But this doesn't work. I tried binding MyList.Count to the text in a text block to ensure that the count value was correct, and it is. It just doesn't seem to set the visibility correctly. A: You cannot use logical or code-expressions in bindings (it expects a PropertyPath). Either use a converter or triggers, which is what i would do: <YourControl.Style> <Style TargetType="YourControl"> <Setter Property="Visibility" Value="Collapsed" /> <Style.Triggers> <DataTrigger Binding="{Binding MyList.Count}" Value="0"> <Setter Property="Visibility" Value="Visible" /> </DataTrigger> </Style.Triggers> </Style> </YourControl.Style> (You can of course refactor the style into a resource if you wish.) A: There is three ways: * *to use Triggers mentioned by H.B. *to use convertors by implementing IValueConverter in a class and setting the Converter property of Binding to an instance of IValueConverter in that class *to define a property in your ViewModel to directly return the Visibility state. You could always use Triggers method and it always is a good approach. The third method is useful(and is best) when you are using MVVM pattern (and you are not restricting yourself from referencing UI related assemblies in your ViewModel) I suggest using Triggers, but if you dont want to make your xaml dirty by that much markup codes use converters. A: You should use a converter, which converts the Count property to a Visibility value, or perhaps a new "HasItems" boolean property to a Visibility value. We use something, for example, called boolToVisibilityConvert, to handle jobs like this. I can give you more precise details, if you need them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Testing in Rails3.1 is very slow. Is there some sort of solution to load the tests faster? I am assuming that the tests are loading slower because of the asset pipeline. I am wondering if there is some sort of gem, or magical spell that I can use to make the tests load faster. rake test:units takes forever. A: There's a bunch of different ways. A popular one right now is Spork, which avoids loading the entire Rails stack multiple times. There's also Parallel Test, which runs multiple test suites in parallel (taking advantage of the multiple cores/processors on your machine).
{ "language": "en", "url": "https://stackoverflow.com/questions/7562863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I dynamically define a Ruby method that takes a block? I know that I can dynamically define methods on a class using define_method, and that I specify the parameters this method takes using the arity of the block. I want to dynamically define a method that accepts both optional parameters and a block. In Ruby 1.9, this is easy because passing a block to a block is now allowed. Unfortunately, Ruby 1.8 doesn't allow this, so the following won't work: #Ruby 1.8 class X define_method :foo do |bar, &baz| puts bar baz.call if block_given? end end x = X.new x.foo("foo") { puts "called!"} #=> LocalJumpError: no block given Replacing the explicit block.call with yield doesn't fix the problem either. Upgrading to Ruby 1.9 is unfortunately not an option for me. Is this an intractable problem, or is there a way around it? A: This works with Ruby 1.8.7, but not 1.8.6: class X define_method(:foo) do |bar, &baz| puts bar baz.call if baz end end Testing with: X.new.foo("No block") X.new.foo("With block") { puts " In the block!"} p = proc {puts " In the proc!"} X.new.foo("With proc", &p) gives: No block With block In the block! With proc In the proc! (with 1.8.6 it gives syntax error, unexpected tAMPER, expecting '|'.) If you want optional arguments as well as block, you could try something like this: class X define_method(:foo) do |*args, &baz| if args[0] bar = args[0] else bar = "default" end puts bar baz.call if baz end end testing with: X.new.foo X.new.foo { puts " No arg but block"} gives: default default No arg but block A: What you could do is use class_eval with a string instead of define_method. The downside to this (apart from not being as elegant) is that you lose lexical scoping. But this is often not needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Converting correctly between tz unaware time, UTC and working with timezones in python I have a string in the form '20111014T090000' with associated timezone ID (TZID=America/Los_Angeles) and I want to convert this to UTC time in seconds with the appropriate offset. The problem seems to that my output time is off by 1 hour (it's in PST when it should be PDT) and I'm using the pytz to help with timezo import pytz def convert_to_utc(date_time) # date_time set to '2011-10-14 09:00:00' and is initially unaware of timezone information timezone_id = 'America/Los_Angeles' tz = pytz.timezone(timezone_id); # attach the timezone date_time = date_time.replace(tzinfo=tz); print("replaced: %s" % date_time); # this makes date_time to be: 2011-10-14 09:00:00-08:00 # even though the offset should be -7 at the present time print("tzname: %s" % date_time.tzname()); # tzname reports PST when it should be PDT print("timetz: %s" % date_time.timetz()); # timetz: 09:00:00-08:00 - expecting offset -7 date_time_ms = int(time.mktime(date_time.utctimetuple())); # returns '1318611600' which is # GMT: Fri, 14 Oct 2011 17:00:00 GMT # Local: Fri Oct 14 2011 10:00:00 GMT-7 # when expecting: '1318608000' seconds, which is # GMT: Fri, 14 Oct 2011 16:00:00 GMT # Local: Fri Oct 14 2011 9:00:00 GMT-7 -- expected value How do I get the correct offset based on the timezone Id? A: The following snippet will do what you wish def convert(dte, fromZone, toZone): fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone) return fromZone.localize(dte, is_dst=True).astimezone(toZone) The crucial part here is to pass is_dst to the localize method. A: simple-date was written to make conversions like this trivial (you need version 0.2.1 or later for this): >>> from simpledate import * >>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp 1318608000.0 A: If changing the global time zone in your program is (temporarily) allowed, you can also do this: os.environ['TZ'] = 'America/Los_Angeles' t = [2011, 10, 14, 9, 0, 0, 0, 0, -1] return time.mktime(time.struct_time(t)) The expected 1318608000.0 is returned. A: To convert given string to a naive datetime object: >>> from datetime import datetime >>> naive_dt = datetime.strptime('20111014T090000', '%Y%m%dT%H%M%S') >>> naive_dt datetime.datetime(2011, 10, 14, 9, 0) To attach the timezone (make it an aware datetime object): >>> import pytz >>> tz = pytz.timezone('America/Los_Angeles') >>> local_dt = tz.localize(naive_dt, is_dst=None) >>> print(local_dt.strftime("%Y-%m-%d %H:%M:%S %Z%z")) 2011-10-14 09:00:00 PDT-0700 Note: is_dst=None is used to raise an exception for non-existing or ambiguous local times. To get POSIX timestamp from an aware datetime object: >>> (local_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() 1318608000.0 The main issues in your question are: * *You replace tzinfo attribute, tz.localize should be used instead *mktime() works with local time (your computer timezone), not UTC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SUM a subquery? Looked through questions with similar titles, but none quite covered my question. I have a query that looks something like this. SELECT bus_products.id , bus_products.prod_name , ( SELECT SUM(bus_warehouse_entries.quantity) * bus_products.weight FROM bus_warehouse_entries WHERE bus_warehouse_entries.org_product_code = bus_products.prod_code AND bus_warehouse_entries.type = 0 AND bus_warehouse_entries.request_date >= 'some_date_here' ) AS reg_yr FROM bus_products WHERE 1'some_search_params' GROUP BY bus_products.prod_name ORDER BY 'some_sort' While I am grouping by product name, the subquery selects by matching product code. Multiple product codes may have the same product name. If there is multiple codes with the same name, the above query only grabs the quantity of the first code due to the grouping. I would like to just add a SUM() around the subquery in order to get the total of all product codes with that particular product name, but that causes a syntax error at the beginning of the subqueries SELECT. any suggestions on how to accomplish this another way? for simplifications sake, the tables look something like this bus_products id | prod_code | prod_name | weight bus_warehouse_entries org_product_code | quantity | type | request_date A: SELECT x.prod_name , SUM(x.total) FROM ( SELECT bp.prod_name , ( SELECT SUM( wh.quantity ) * bp.weight FROM bus_warehouse_entries wh WHERE bp.prod_code = wh.org_product_code ) AS total FROM bus_products bp ) x GROUP BY x.prod_name You can add more subqueries in the select inside the from and sum them in the outside query. A: Try this: select b.id, b.prod_name, sum(bwe.quantity)*b.weight as reg_yr from bus_products b inner join bus_warehouse_entries bwe on bwe.org_product_code=b.prod_code where bwe.type=0 and bwe.request_date>='some date' group by b.id,b.prod_name, b.weight UPDATE: How about this then? SELECT bus_products.id , bus_products.prod_name , f.part_total FROM bus_products bus_products inner join ( SELECT SUM(bus_warehouse_entries.quantity) * bus_products.weight as part_total ,bus_products.prod_code as p_code FROM bus_warehouse_entries bus_warehouse_entries join bus_products on bus_products.prod_code=bus_warehouse_entries.org_product_code WHERE bus_warehouse_entries.type = 0 AND bus_warehouse_entries.request_date >= 'some_date' group by bus_products.prod_code,bus_products.weight ) f on f.p_code=bus_products.prod_code A: Try wrapping the whole thing in another query. SELECT id, prod_name, sum(reg_yr) FROM (your query) GROUP BY id, prod_name A: To help support my answer, and your comments in the question, it sounds like you want the product NAME and not the ID... Ex: you could have 20 products that are all Televisions where the product name actually would sound like a category vs a specific product name. Each "product name" one would have more specific "what" about it. So, the ONLY reason you would need to join on the ID is to get the proper weight associated with warehouse inventory. That said, I would try this... select bp.prod_name, sum( wh.quantity * bp.weight ) as TotalWeight from bus_warehouse_entries wh join bus_products bp on wh.org_product_code = bp.prod_code where wh.type = 0 and wh.request_date >= 'some_date' and (any other criteria) group by bp.prod_name order by bp.prod_name (or whatever else)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to go about updating the GAE SDK? I'm thinking about updating my version of the GAE SDK (1.5.1 -> 1.5.4). However, I've never updated a SDK before and I can't find any tools provided by GAE to facilitate this task nor am I aware that GAE does this automatically. I realize I could just download the new version of the SDK and reconfigure it manually to suit my situation but this process seems error prone and excessive. Is there a systematic or conventional way that most programmers accomplish this task? A: Delete (uninstall) the old SDK; install the new one. That's what I do on my personal (Linux) laptop. Co-workers who use MacOS do the same. The only "reconfiguration" I've found necessary is when using the Google Plugin for Eclipse, which needs to be prodded to copy the new Java jars into my Java projects' WEB-INF/lib directories. Python hasn't required any reconfiguration at all. A: In terms of the GAE SDK updating, the production environment is updated automatically by Google. That is to say whenever a new version being released, the production version will be updated to that new version. So you never need to worry about the version being running in production environment. Regarding the local testing environment, some manual task is needed to update the version. As @splix asked what language you are actually using, the process may vary a bit. In my case as a Java developer, we are here using Maven plugin to handle all this stuff. So essentially what you need to do is update your pom.xml to point to the right version of GAE, and run mvn gae:unpack, all latest version will be downloaded and used by your local environment. This process is also pretty handy in Eclipse plugin, as basically what you need to do is update the Google Plugin for Eclipse as what you had done to install it. And after that, the local environment will pick up the latest version it got. I am not a Python guy, so if you are after Python, my above answer my not be helpful. Sorry about that. A: If you are working with Android Studio, you don't need to download (directly from the Google download site ) or delete anything. Just go to build.gradle (module:backend) dependencies { appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.18' } Change the version number of the SDK (from 1.9.18 for example) to the latest and perform project sync (Of course you have to be connected to the Internet). The latest version will be downloaded from the maven/jcenter repository.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Oauth 2.0 October 1st deadline, what exactly happens with old FBML apps? I'd like a clarification from someone at Facebook about the Oct 1st HTTPS deadline and it's impact on old FBML apps.. As per: http://developers.facebook.com/docs/oauth2-https-migration/ Facebook says: "an SSL Certificate is required for all Canvas and Page Tab apps (not in Sandbox mode and not FBML)" Well, my app is NOT in sandbox mode and FBML.. which would mean HTTPS is not required. Am I misunderstanding this? If I'm not, then how will this be working after Oct 1st? As, https://apps.facebook.com/app-name doesn't work without a Secure URL listed.. and you'll get error messages saying Secure URL will be required by October 1st. And to make matters even more confusing, if you do keep it as FBML, and add a valid Secure URL, you'll get the error "No Response Received". (It's not a server side / ssl issue, because changing the app to iframe works) This is very worysome.. I'd like a straight answer with what will happen, or if they'll give us a couple days to straighten things out, etc.. Others have shown concern, but with no official answer: Are FBML apps required to provide HTTPS canvas url by 1st of October? Are FBML apps required to upgrade to OAUTH access token by October 1st? A: I think I've finally found the answer on this page: http://developers.facebook.com/roadmap/ Under "October 1, 2011", 2. Apps on Facebook Authentication and security migration (HTTPS) ..... You must provide an SSL certificate in the Dev App settings to avoid having your app disabled. It looks like they're saying FBML will continue to work (I can't find a date that this will end) but iframe apps without SSL will be disabled. A: Just received this email from facebook, which I guess answers my question.. with meaning YES, you have to migrate to iframe+ssl? :( Dear Developer of Fish Wrangler, Reminder: Upgrade Your App to OAuth 2.0 and HTTPS by October 1st. In May we announced that all apps on Facebook need to support OAuth 2.0 and HTTPS to make the platform more secure. All apps, including page tab apps, must migrate to OAuth 2.0 for authentication. The old SDKs, including the old JavaScript SDK (FeatureLoader.js) and old iOS SDK (facebook-iphone-sdk) will no longer work. In addition, non-iframe Canvas and Page Tab apps must support HTTPS and provide a secure canvas or secure page tab URL. If you haven't already made these changes, visit the Developer Roadmap before October 1st for more information about how to upgrade your app and avoid having it disabled. You can also seek support in the Facebook Developer Group: https://www.facebook.com/groups/fbdevelopers/ A: There are still a few Apps out there that are working but most of them are not because they were not using SSL. So when using a third party app to create a fan page tab, it may cease to work as well. You can always use Versitek Tabs as an alternative if you don't have access to SSL. http://tabs.versitek.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7562884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django get all related Choices where Event=Event.id I'm trying to create my first application using Django. I'm using the following code to create a list of events. {% for Event in location_list %} {{ Event.lat }}, {{ Event.long }}, html: "{{ Event.id }}", }] {% endfor %} I need to edit the code so that {{ Event.id }} Becomes something like {{ Get all Choice in choice_list WHERE event IS Event.id }} What is the proper syntax for doing this? Model.py from django.db import models class Event(models.Model): info = models.CharField(max_length=200) long = models.CharField(max_length=200) lat = models.CharField(max_length=200) def __unicode__(self): return self.info class Choice(models.Model): event = models.ForeignKey(Event) choice = models.CharField(max_length=200) link = models.CharField(max_length=200) def __unicode__(self): return self.choice views.py def index(request): location_list = Event.objects.all() choice_list = Choice.objects.all() t = loader.get_template('map/index.html') c = Context({ 'location_list': location_list, 'choice_list': choice_list, }) return HttpResponse(t.render(c)) Update I have replaced {{ Event.id }} with {% for choice in event.choice_set.all %} {{ choice }} {% endfor %} It doesn't print any events. A: It looks like you're trying to follow relationships backward. # In the shell # fetch events from the db >>> events = Event.objects.all() >>> for event in events: ... # fetch all the choices for this event ... event_choices = event.choice_set.all() ... print event_choices In the template, you don't include the parenthesis for the method call. {% for event in location_list %} {{ event.lat }}, {{ event.long }} <ul> {% for choice in event.choice_set.all %} <li>{{ choice }}</li> {% endfor %} </ul> {% endfor %} You may want to define the related_name parameter in your foreign key definition: class Choice(models.Model): event = models.ForeignKey(Event, related_name="choices") Then you can use event.choices.all() in your views and {% for choice in event.choices.all %} in your templates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get response from loading movie to youtube i am using the ZEND Gdata and youtube api to upload vidoes to youtube http://code.google.com/apis/youtube/2.0/developers_guide_php.html#Direct_Upload When I upload a Video how do I capture the Video ID that was generated and also the youtube link ? try { $newEntry = $yt->insertEntry($myVideoEntry,$uploadUrl,'Zend_Gdata_YouTube_VideoEntry'); } catch (Zend_Gdata_App_HttpException $httpException) { echo $httpException->getRawResponseBody(); } catch (Zend_Gdata_App_Exception $e) { echo $e->getMessage(); } thank you very much A: This line: $newEntry = $yt->insertEntry($myVideoEntry,$uploadUrl,'Zend_Gdata_YouTube_VideoEntry'); returns a Zend_Gdata_YouTube_VideoEntry object. The Zend Framework API docs for Zend_Gdata_YouTube_VideoEntry lists all the methods and properties that class makes available. There is similar documentation for all Zend Framework classes, and it's automatically generated, so it's often a good place to go if the manual doesn't answer a question. From looking there, I'd say that you'd call: * *$newEntry->getVideoId() to get the video ID *$newEntry->getVideoWatchPageUrl() to get the video URL
{ "language": "en", "url": "https://stackoverflow.com/questions/7562886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autocomplete Google Map V3 Places impossible to customize? I narrowed autocomplete to a region and to a bounds that cover only Australia, but I am still receving autocomplete with Chile and China and other country out of the selected area. Does anyone have a good solution to work this problem? I also can't change the styling off Google autocomplete, it is a self generated Div with style tag that overcomes my style to autocomplete DIV? I started to use Geocoder and Jquery autocomplete to filter the results but it doesn't work as well as Google Autocomplete the results are less than google maps autocomplete? I call the Library like this: Here is the code of creating the auto complete: var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-47.5765257137462, 106.259765625), new google.maps.LatLng(-9.6, 179.359375)); var options = { bounds: defaultBounds, types: ['geocode'], offset: 5 }; var input = document.getElementById('store-locator-header'); var autocomplete = new google.maps.places.Autocomplete(input,options); A: Nowadays, you can restrict to a country with: componentRestrictions: {country: 'us'}, A: When Adding Autocomplete with bounds, results are biased towards, but not restricted to, Places contained within these bounds. This is the same as when using Viewport Biasing in the Geocoding API. I'm afraid I don't have a method to filter out those suggestions that fall outside of the bounds. A: Another way to qucikly customise can be to set component restriction like shown below var autocomplete = new google.maps.places.Autocomplete(input); //autocomplete.bindTo('bounds', map);//restrict to bounds or viewport autocomplete.setComponentRestrictions({'country': 'uk'});//restrict to country more about places biasing here A: The problem is that LatLngBounds expects south-west and north-east corners. Instead of: var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-47.5765257137462, 106.259765625), new google.maps.LatLng(-9.6, 179.359375)); It should be: var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-9.6, 106.259765625), new google.maps.LatLng(-47.5765257137462, 179.359375)); There is actually documentation to style the UI elements of Autocomplete.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Basic question complicated solution - Tomcat to JBoss Why can't the JSTL jars having tld files present in my web-inf/lib directory be read nicely by tomcat but not when i move to jBoss 5? Is it a classloader issue? I tried researching but there exists no clear answer. I read a huge classloader related article but not sure how that applies practically to my application. Any help would be appreciated. Thanks in advance Asif A: Tomcat is a simple JSP/Servlet container which ships with JSP and Servlet APIs only. JBoss is a more full fledged Java EE application server which ships with almost the entire Java EE API, including JSTL. When you ship JSTL along with your own webapp, then chances are big that its API/impl version will conflict with the one which JBoss is already using. JBoss will load its own JSTL API (the jstl.jar), but the webapp will load the JSTL impl (the standard.jar). You should actually remove the JSTL JARs from your webapp and utilize the JBoss ones. In order to get JSTL to work for the same webapp on Tomcat as well, you could also add the JARs to Tomcat's own /lib folder. This way every webapp deployed to Tomcat will be able to utilize JSTL without the need to include the JARs in /WEB-INF/lib.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MEF/Unity Dependency Resolution failing on multiple threads My web application uses Unity for DI. Another section of the webapp uses MEF. The code works fine in a single threaded session. But as soon as I click on the same link from two different web sessions (CHrome and FIrefox). I'm not sure if this is a circular reference loop issue or a threading issue... It works just fine on a single session, this error only occurs when clicking on the same link in two different sessions. I get the following error: Exception information: Exception type: ResolutionFailedException Exception message: Resolution of the dependency failed, type = "MefContrib.Integration.Unity.Extensions.TypeRegistrationTrackerExtension", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - Currently composing another batch in this ComposablePartExportProvider. Only one batch can be composed at a time. More detail regarding the error: Server Error in '/' Application. GetExportedValue cannot be called before prerequisite import 'MyApp.Core.Services.RuleService..ctor (Parameter="productService", ContractName="MyApp.Core.Services.IProductService")' has been set. InvalidOperationException: GetExportedValue cannot be called before prerequisite import 'MyApp.Core.Services.RuleService..ctor (Parameter="productService", ContractName="MyApp.Core.Services.IProductService")' has been set.] System.ComponentModel.Composition.ReflectionModel.ReflectionComposablePart.EnsureGettable() +422 System.ComponentModel.Composition.ReflectionModel.ReflectionComposablePart.GetExportedValue(ExportDefinition definition) +208 System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) +131 System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(ComposablePart part, ExportDefinition export, Boolean isSharedPart) +102 System.ComponentModel.Composition.Hosting.CatalogExport.GetExportedValueCore() +148 System.ComponentModel.Composition.Primitives.Export.get_Value() +76 System.ComponentModel.Composition.ReflectionModel.ImportingItem.Cast(Type type, Export export) +63 System.ComponentModel.Composition.ReflectionModel.ImportingItem.CastSingleExportToImportType(Type type, Export export) +149 System.ComponentModel.Composition.ReflectionModel.ImportingItem.CastExportsToSingleImportType(Export[] exports) +163 System.ComponentModel.Composition.ReflectionModel.ImportingItem.CastExportsToImportType(Export[] exports) +118 System.ComponentModel.Composition.ReflectionModel.ReflectionComposablePart.SetImport(ImportingItem item, Export[] exports) +74 System.ComponentModel.Composition.ReflectionModel.ReflectionComposablePart.SetImport(ImportDefinition definition, IEnumerable`1 exports) +230 System.ComponentModel.Composition.Hosting.PartManager.TrySetImport(ImportDefinition import, IEnumerable`1 exports) +91 System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImportSubset(PartManager partManager, IEnumerable`1 imports, AtomicComposition atomicComposition) +449 System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImportsStateMachine(PartManager partManager, ComposablePart part) +571 System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImports(PartManager partManager, ComposablePart part, Boolean shouldTrackImports) +277 System.ComponentModel.Composition.Hosting.ImportEngine.SatisfyImports(ComposablePart part) +201 System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) +77 System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(ComposablePart part, ExportDefinition export, Boolean isSharedPart) +102 System.ComponentModel.Composition.Hosting.CatalogExport.GetExportedValueCore() +148 System.ComponentModel.Composition.Primitives.Export.get_Value() +76 System.ComponentModel.Composition.ExportServices.GetCastedExportedValue(Export export) +54 System.ComponentModel.Composition.<>c__DisplayClass10`2.<CreateSemiStronglyTypedLazy>b__d() +107 System.Lazy`1.get_Value() +136 MefContrib.Integration.Unity.Strategies.CompositionStrategy.PreBuildUp(IBuilderContext context) +361 Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\StrategyChain.cs:110 Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\BuilderContext.cs:215 Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilderCustomization\NamedTypeDependencyResolverPolicy.cs:51 BuildUp_MyApp.Core.Services.ClientService(IBuilderContext ) +591 Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\DynamicMethod\DynamicMethodBuildPlan.cs:37 Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\BuildPlanStrategy.cs:43 Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\StrategyChain.cs:110 Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:511 [ResolutionFailedException: Resolution of the dependency failed, type = "MyApp.Core.Services.ClientService", name = "IFClientService". Exception occurred while: while resolving. Exception is: InvalidOperationException - GetExportedValue cannot be called before prerequisite import 'MyApp.Core.Services.RuleService..ctor (Parameter="productService", ContractName="MyApp.Core.Services.IProductService")' has been set. ----------------------------------------------- At the time of the exception, the container was: Resolving MyApp.Core.Services.ClientService,IFClientService Resolving parameter "companyClientValidator" of constructor MyApp.Core.Services.ClientService(MyApp.Core.Repository.IClientRepository repository, MyApp.Core.Validators.IClientValidator validator, MyApp.Core.Validators.IChildClientValidator childClientValidator, MyApp.Core.Services.IReferenceService referenceService, MyApp.Core.Services.IProductService productService, MyApp.Core.Services.IOccupationService occupationService, MyApp.Core.Services.IAdviserService adviserService, MyApp.Core.Validators.ICompanyClientValidator companyClientValidator, MyApp.Core.Repository.IAddressRepository addressRepository) Resolving MyApp.Core.Validators.ICompanyClientValidator,(none) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: GetExportedValue cannot be called before prerequisite import 'MyApp.Core.Services.RuleService..ctor (Parameter="productService", ContractName="MyApp.Core.Services.IProductService")' has been set. A: How have you constructed your CompositionContainer? By default, containers are not constructed as thread safe. There is an overloaded constructor that accepts a flag to specify whether it should be constructed as thread-safe: CompositionContainer(ComposablePartCatalog catalog, bool threadSafe, params ExportProvider[] providers)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does an embedded form not respond to arrow keys? I am building a simple plugin framework in Delphi (XE) where the plugins are forms than can be optionally embedded into a TabSheet on a main application. There are examples on the web that explain how to do the embedding, for example: http://delphi.about.com/od/adptips2005/a/bltip0305_5.htm. I have tried this myself and it appears successful. However I find that if I put a TMemo on the embedded form, the arrow keys do not work on the embedded TMemo, ie the cursor on the TMemo will not move. Other keys such as backspace, delete, Ctrl-V etc and alphanumeric keys work as expected (The TAB will not traverse the controls in the embedded form either). A TMemo on the main application works fine. Any idea why the TMemo in the embedded form will not respond to the arrow keys? A: I in counter the same way before and i use the Form.Preview := True to inherit the key activity to make it global. try to see this example it be useful for you. A: The problem lies with the plugin system I build (which remains to be identified) not with the embedding itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }