text
stringlengths
8
267k
meta
dict
Q: Using EF over WCF How can I expose an Entity Framework IQueryable<T> over WCF? I'm thinking of writing an N-tier application framework and I would like to use Entity Framework and WCF. I am aware of WCF Data Services, but I do not want REST or HTTP. This is because I want to have bidirectional communication between the clients and the server. Right now, it will be WinForms/WPF and ASP.NET applications will consume the services. A: It seems like you may be looking for WCF RIA Services or WCF Data Services A: Take a look at WCF Data Services / OData. In particular, I think this video shows an example of what you are trying to do. A: You could to write the query handling for yourself similar to what the already mentioned Data Services do. Unfortunately you can't serialize LINQ queries, but you can probably serialize LINQ expressions. Check the answer to Serializing and Deserializing Expression Trees in C#. Another option would be to offer a specific service contract with parameters for every query that you need to make.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Combining different datatypes into a void type I am creating a search tree that would handle concatenated key. ie a key is a combination of multiple data types. For example key might be a concatenation of student_id,student_name,student_age...How should i create such a key when i pass these three values to create key function? Also given two keys how can i compare them? A: Implementation of the comparison function is left as an excercise to the reader. #include <cstdlib> #include <string> using namespace std; class StudentKey { public: string id_, name_; unsigned age_; bool operator<(const StudentKey& rhs) const; }; StudentKey CreateKey(const std::string& student_name, const std::string& student_id, unsigned student_age) { StudentKey ret; ret.name_ = student_name; ret.id_ = student_id; ret.age_ = student_age; return ret; } int main() { StudentKey key = CreateKey("name","id",42); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: 3 vertical divs floating with 1 background, background scrolls with shortest Well I have 3 div's floating next to eachother. And the 3 divs are in a bigger div with background image. Now are the left and right div 600px in height and that is set and the middle (container) is auto height. But I want the background of the 3 divs always to be the same height as the left and right div dut it only scrolls with the middle div. Maby I can't explaine this correct so if you could take a real quick look at the website. This is when its correct with lots of content: Good This is the incorrect page... Bad I'm guessing its not something big and I dont know what coding to post here so to overcome lots and lots of coding here maby this is better if you could take a quick peek. Thanks! A: Add overflow: hidden to the #mainbg div #mainbg { overflow: hidden; } A: try add: <div style="clear:both;line-height:0"></div> after the last div. edit: i don't watch to the source code first so a little bit change... * *create a new div into mainbg and add all 3 middle part divs in it *then you can use clearing div after this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mdpi and hdpi images are not correctly loaded into the device android i have images accordingly int the hdpi and mdpi folder but when i run the application the hdpi images are loading fine on the high resolution devices but when i run on medium resolution 320 x 480 the hdpi images are loading not the medium ones. i have also tested moving the images to res/drawble but nothing happens.. please help me on this i have set the manifest file with <supports-screens android:smallScreens="false" android:normalScreens="true" android:largeScreens="true" android:anyDensity="true"> <uses-sdk android:minSdkVersion="8" /> A: Please check if your drawable folders are correctly named. They should be: * *drawable-mdpi *drawable-hdpi Also, be sure that your file names are identical. It works fine for me. Sometimes it may even work to clean the project using Eclipse. EDIT: I think your project is working fine, but you're making some mistakes with your setup. You probably haven't read the developer guide properly: http://developer.android.com/guide/practices/screens_support.html Anyway, what you're essentially doing is saying that mdpi = 320 x 480 and hdpi = 480 x 800 pixels. But that's not correct. The DPI (dots per inch) has nothing to do with the actual resolution of the screen. You can easily have a medium DPI screen with a resolution larger than 320 x 480 pixels. Read the link that I posted - especially the part called "How to Test Your Application on Multiple Screens". That should help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EF-Code First: Unable to create a constant value of type ''. Only primitive types ('such as Int32, String, and Guid') are supported in this context I am currently having trouble with some some linq using EF code first. My current code works fine: My database model public class MyDatabase : DbContext { public DbSet<Person> People { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<Visit> Visits { get; set; } } public class Person { public int PersonId { get; set; } public string Forename { get; set; } public string Surname { get; set; } } public class Visit { public int VisitId { get; set; } public string Name {get; set;} public int PersonId { get; set; } public string VisitStatus { get; set; } public virtual Person People { get; set; } //There is a one to many relationship to person } public class Role { public Role() { People = new HashSet<Person>(); } [Key] public int RoleId { get; set; } public string Name { get; set; } public virtual ICollection<Person> People { get; set; } //There is a many to many relationship to person } My query public IEnumerable<VisitDetails> GetGuestVisiterList() { using (var db = new MyDatabase()) { return (from p in db.People where p.Roles.Any(a => a.Name == "Guest") select new GuestVisitDetails { PersonId = p.PersonId, Forename = p.Forename, Surname = p.Surname, NumberOfVisits = db.Visits.Count(v => v.PersonId == p.PersonId && v.VisitStatus != "Complete") }).ToList(); } } My View model public class GuestVisitDetails { public int PersonId { get; set; } public string Forename { get; set; } public string Surname { get; set; } public int NumberOfVisits { get; set; } } But when I try to use an interface for my database model so I can unit test, it get the following error: Unable to create a constant value of type 'MyVisits.Data.Model.Visit'. Only primitive types ('such as Int32, String, and Guid') are supported in this context My Datebase interface public class MyDatabase : DbContext, IDolphinDatabase { public IDbSet<Person> People { get; set; } public IDbSet<Role> Roles { get; set; } public IDbSet<Visit> Visits { get; set; } } public interface IMyDatabase : IDisposable { public IDbSet<Person> People { get; set; } public IDbSet<Role> Roles { get; set; } public IDbSet<Visit> Visits { get; set; } } My new Query, I created a dbFactory to just get the IMyDatabase public IEnumerable<VisitDetails> GetGuestVisiterList(int paperId) { using (var db = _dbFactory.GetDatabase()) { return (from p in db.People where p.Roles.Any(a => a.Name == "Guest") select new GuestVisitDetails { PersonId = p.PersonId, Forename = p.Forename, Surname = p.Surname, NumberOfVisits = db.Visits.Count(v => v.PersonId == p.PersonId && v.VisitStatus != "Complete") }).ToList(); } } I've found out that it is the 'NumberOfVisits' that is causing the problem but am unsure why or how to fix it. As requested the stack trace [NotSupportedException: Unable to create a constant value of type 'MyVisits.Data.Model.Visit'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.] System.Data.Objects.ELinq.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) +902 System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54 System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110 System.Data.Objects.ELinq.<>c__DisplayClass77.<TypedTranslate>b__75(Expression e) +11 System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151 System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator`3.Validate(IEnumerable`1 argument, String argumentName, Int32 expectedElementCount, Boolean allowEmpty, Func`3 map, Func`2 collect, Func`3 deriveName) +237 System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator`3.Validate() +46 System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.CreateExpressionList(IEnumerable`1 arguments, String argumentName, Boolean allowEmpty, Action`2 validationCallback) +142 System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateNewCollection(IEnumerable`1 elements, DbExpressionList& validElements) +72 System.Data.Objects.ELinq.NewArrayInitTranslator.TypedTranslate(ExpressionConverter parent, NewArrayExpression linq) +121 System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54 System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110 System.Data.Objects.ELinq.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) +520 System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54 System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110 System.Data.Objects.ELinq.AggregateTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +86 System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +14 System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +102 System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54 System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110 System.Data.Objects.ELinq.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq) +310 System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54 System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110 System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) +80 System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding) +88 System.Data.Objects.ELinq.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda) +85 System.Data.Objects.ELinq.SelectTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +37 System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +14 System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +102 System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54 System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110 System.Data.Objects.ELinq.ExpressionConverter.Convert() +16 System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) +110 System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +149 System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44 System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +40 System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315 System.Linq.Enumerable.ToList(IEnumerable`1 source) +58 MyVisits.Business.<GetGuestVisiterList>c__Binding.Invoke(Object& instance, Arguments arguments, Object aspectArgs) in E:\Visual Studio\Projects\MyVisits_current\MyVisits.Business\VisitService.cs:459 PostSharp.Aspects.Internals.MethodInterceptionArgsImpl`1.Proceed() +23 MvcMiniProfiler.Aop.MiniProfilerAttribute.OnInvoke(MethodInterceptionArgs args) in E:\Visual Studio\Projects\MyVisits_current\MvcMiniProfiler.Aop\MiniProfilerAttribute.cs:17 MyVisits.Business.VisitService.GetGuestVisiterList() in :0 MyVisits.Web.Areas.RegionalAdministrator.Controllers.VisitController.EditVisitor() in E:\Visual Studio\Projects\MyVisits_current\MyVisits.Web\Areas\RegionalAdministrator\Controllers\VisitController.cs:85 lambda_method(Closure , ControllerBase , Object[] ) +101 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod_callback(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget() +154 Castle.DynamicProxy.AbstractInvocation.Proceed() +56 Glimpse.Mvc3.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation invocation) +336 Castle.DynamicProxy.AbstractInvocation.Proceed() +94 Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +214 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8920029 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Any help would be great A: First, you should change your entities, to support your relationships: public class Person { public int PersonId { get; set; } public string Forename { get; set; } public string Surname { get; set; } // add a collection-reference to roles public virtual ICollection<Role> Roles { get; set; } // add a collection-reference to visites public virtual ICollection<Visit> Visits { get; set; } } public class Visit { public int VisitId { get; set; } public string Name {get; set;} public string VisitStatus { get; set; } public int PersonId { get; set; } public virtual Person People { get; set; } //There is a one to many relationship to person } public class Role { public Role() { People = new HashSet<Person>(); } [Key] public int RoleId { get; set; } public string Name { get; set; } public virtual ICollection<Person> People { get; set; } //There is a many to many relationship to person } Your problem resolved now. But you can also change the query like this: public IEnumerable<VisitDetails> GetGuestVisiterList(int paperId) { using (var db = _dbFactory.GetDatabase()) { return (from p in db.People where p.Roles.Any(a => a.Name == "Guest") select new GuestVisitDetails { PersonId = p.PersonId, Forename = p.Forename, Surname = p.Surname, NumberOfVisits = p.Visits.Count(v => v.VisitStatus != "Complete") }).ToList(); } } Let me know if you have any problem or questions or need clarifications on any part. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problems with XSL and HTML tags I'm just learning XML and XSL, so please bear with me if this is a stupid question. I can't seem to find an easy answer to this, so I'm assuming I'm making a simple mistake that folks who write guides wouldn't think to address. I have the following XML (just a snippet, here), that I lifted from w3c for learning: <catalog>My CD Collection <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> </catalog> And then the following XSL: <xsl:template match="/"> <html> <body> <xsl:for-each select="/"> <h2><xsl:value-of select="catalog" /></h2> </xsl:for-each> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title" /></td> <td><xsl:value-of select="artist" /></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> For some reason, the XSL is not reading the closing h2 tag and it's not reading the opening table tag, rendering the entire thing into one huge heading. A: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <html> <body> <xsl:for-each select="/"> <h2><xsl:value-of select="catalog" /></h2> </xsl:for-each> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title" /></td> <td><xsl:value-of select="artist" /></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> Try this. First you were outputing the complete catalog element to the header. Other than this you should probably add this : <xsl:output omit-xml-declaration="yes" indent="yes"/> On the top of your sheet. The output is what you would expect : <html> <body> <h2>My CD Collection </h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <tr> <td>Empire Burlesque</td> <td>Bob Dylan</td> </tr> </table> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7584016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using pair and make_pair in standard C Is there any way to use std::pair and std::make_pair in C? seems that they are applicable in C++. As I used #include "utility" it says it can not find such file thansk for any suggestion A: It's C++-only. C has no templates, so you will have to roll your own with macros to emulate them to some extent, for example: #define PAIR_TYPE(type1, type2)\ typedef struct {\ type1 first;\ type2 second;\ } #define MAKE_PAIR(val1, val2) {val1, val2} PAIR_TYPE(int, float) mypair; mypair p = MAKE_PAIR(1, 12.0); But it's really not worth the trouble, result code is more verbose and less obvious than just using plain structs. A: No, you cannot use the STL in C (as the STL only works with C++ and Objective-C++). You can mimic std::pair with a struct and with pointers (as C doesn't support templates): struct pair { void *first; void *second; }; void FreePair(struct pair* pair) { free(pair->first); free(pair->second); free(pair); } struct pair* MakePair(void *f, void *s, size_t fsize, size_t ssize) { struct pair* p = malloc(sizeof(struct pair)); if (p == NULL) return NULL; p->first = malloc(fsize); p->second = malloc(ssize); if (p->first == NULL || p->second == NULL) { FreePair(p); return NULL; } memcpy(p->first, f, fsize); memcpy(p->second, s, ssize); return p; } int main() { int a = 42; const char* str = "Hello"; struct pair* p = MakePair(&a, &str, sizeof(a), sizeof(str)); printf("%d, %s", *(int*)p->first, *(const char**)p->second); // output: "42, Hello" FreePair(p); // ^^ yes, this pointer pointer is correct return 0; } A: Is there any way to use std::pair and std::make_pair in C? seems that they are applicable in C++. No. std::pair is a template class in C++, and there are no classes in C. There is nothing similar (ie. easily usable predefined data structure) to pairs in C either. A: No, those are types from the C++ standard library. Which explains the std:: namespace syntax (C doesn't support namespaces either). A: "utility" is not a standard C header. And no, the standard C++ library depends entirely on templates which are not part of the C language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to preview an ad using the preview_url in the creative_spec? I'm developing a Facebook connect site that manage Facebook Ad Campaigns and I have a small problem. When I'm creating an Ad using the API I receive the preview_url in the creative_specs of the ad created and then I want to show it in my website. However, the URL i get is inside Facebook. example: http://www.facebook.com/ads/api/creative_preview.php?cid=6003167825281 I can't show it in an iframe because of facebook frame detect code, and i can't request to it in an AJAX call (i keep geting Bad Request 4xx)... So how on earth I can preview an ad I created using the Facebook ads api in my site?? thanks, Yaniv A: You can check out this ref : http://developers.facebook.com/docs/reference/ads-api/generatepreview/ --- First you need to get the account CSS by $url = 'https://graph.facebook.com/act_' . $bizId . '/adpreviewscss?access_token=' . $access_token; --- Then get the HTML part by $url = 'https://graph.facebook.com/' . $adId . '/previews?access_token=' . $accessToken; --- Add this CSS patch /* ---- Ads Preview Styles ----------------------- */ a.forceLTR{cursor:pointer;color:#3B5998;text-decoration:none} .fbEmuPreview{border:1px solid #E5E5E5;background-color:#FFF;width:234px;padding:10px} .fbEmuEgo{line-height:13px} .fbEmu .title{font-weight:700;margin-bottom:0!important} .fbEmu .forceLTR{direction:ltr;text-align:left;display:block} .fbEmu .adInfo a.identity{color:gray;display:block;white-space:nowrap} .fbEmu .image_body_block{padding-top:3px} .clearfix{zoom:1} .clearfix::after{clear:both;content:".";display:block;font-size:0;height:0;line-height:0;visibility:hidden} .fbEmuEgo .image{width:100px;display:block} .lfloat{float:left} .-cx-PRIVATE-uiImageBlock__mediumImage{margin-right:8px} .-cx-PRIVATE-uiImageBlock__content{overflow:hidden} .-cx-private-uiimageblock__content a{font-size:11px} .fbEmu .body .fbEmuLink{color:#333} div.fbEmuEgo .image .img{padding-top:3px;max-height:72px;max-width:100px} .fbEmuEgo .action{color:#777;margin-top:5px} .uiIconText{padding-left:21px;position:relative} .uiIconText .img{left:0;position:absolute;top:-1px;vertical-align:middle} .sx_39ed22{width:12px;height:11px;background-position:-49px -154px} .sp_buw69i{background-image:url(http://static.ak.fbcdn.net/rsrc.php/v2/yR/r/hqPYFjMiGCV.png);background-repeat:no-repeat;display:inline-block;height:16px;width:16px} a.forceLTR,a.uiIconText{cursor:pointer;color:#3B5998;text-decoration:none} A: from the data you store in your database at the same time or from retrieving the ad details with the ad id from the api.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamic Code Generation and security I encounter a problem with the JSON.Net serialization library and I wanted opinion of people more expert than me in CAS and AppDomain management. To have more information on the problem, you can refer to the issue 21575. I submitted a patch for this issue. The idea is that DynamicCodeGeneration flag is statically set once and for all in the current application domain when you first access it. However, I think that permission allowed for an application domain can change. For example, if you call a method of an object in an application domain, across another application domain, it seems that you inherit of the permissions of the most restrictive application domain. So for me this assumption that permissions won't change for an application domain and that you can statically set DynamicCodeGeneration once and for all is wrong. Am I correct ? Or do I miss something about CAS and AppDomain management ? EDIT: I added a little schema about what I think it is happening: http://www.sp4ce.net/data/temp/appdomain.png Do you think it is correct ? A: I think your unit tests are providing evidence for your theory. In cross-appdomain calls, it looks like the more restrictive CAS restrictions are enforced. I don't think, though, that future calls local to the less restrictive appdomain (no remoting to restrictive appdomain) will continue to enforce the more restrictive permission set. The issue with JSON.Net that you are attempting to address is that the permission set is checked once and not re-verified in future calls that may be coming from a more restrictive appdomain. Given that permissions can change depending on the calling context, it makes sense to demand permissions in the scope most local to the use of the permission. Your solution is to make the calling code responsible for informing JSON.Net of whether DynamicCodeGeneration is used. I think a better solution in the JSON.Net library would be to demand the requierd permissions in the JsonTypeReflector.DynamicCodeGeneration getter every time it is called, rather than caching the value as it does now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this code Oauth 2.0 compatible? Facebook announced that all apps must migrate to OAuth 2.0 by 1st of October 2011 October 1, 2011 OAuth 2.0 Migration As we announced in May, all apps must migrate to OAuth 2.0 for authentication and expect an encrypted access token. The old SDKs, including the old JS SDK and old iOS SDK will no longer work. Read more here: https://developers.facebook.com/docs/oauth2-https-migration/ Now I am pretty confused by all the different flows and versions. I have a simple authentication going on that looks basically like this (I stripped the un essential parts) ## setup ### $url = "https://graph.facebook.com/oauth/authorize?client_id=".$this->appid."&redirect_uri=".$myurl; header("Location: $url"); exit(); and when the user returns... ## authentication check ## $code = isset($_GET["code"]) ? $_GET["code"] : false; if(!$code) { // user has not authenticated yet, lets return false so setup redirects him to facebook return false; } $url = "https://graph.facebook.com/oauth/access_token?client_id=".$this->appid."&redirect_uri="; $redirecturl = urlencode($redirecturl); $url .= $redirecturl; $url .= "&client_secret=".$this->secret; $url .= "&code=".$code; $data = $this->get_data($url); // fetches content over https parse_str($data,$data); $token = $data['access_token']; $data = $this->get_data('https://graph.facebook.com/me?access_token='.urlencode($token)); $data = json_decode($data); $id = $data->id; if($id > 0) { // yeah authenticated! } else { // login failed } Is this method ready for the compulsory migration? A: short answer... it is..................
{ "language": "en", "url": "https://stackoverflow.com/questions/7584030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android: Softkeyboard perform action when Done key is pressed I have an EditText. I want that after typing some text, when user presses the Done key of the softkeyboard, it should directly perform some search operation which I have also implemented in a button click event. A: Try this editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(actionId==EditorInfo.IME_ACTION_DONE){ //do something } return false; } }); A: Try this It works both for DONE and RETURN. EditText editText= (EditText) findViewById(R.id.editText); editText.setOnEditorActionListener(new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) { // Do your action return true; } return false; } }); A: You catch the KeyEvent and then check its keycode. FLAG_EDITOR_ACTION is used to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done" if (event.getKeyCode() == KeyEvent.FLAG_EDITOR_ACTION) //your code here Find the docs here. Second Method myEditText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { int result = actionId & EditorInfo.IME_MASK_ACTION; switch(result) { case EditorInfo.IME_ACTION_DONE: // done stuff break; case EditorInfo.IME_ACTION_NEXT: // next stuff break; } } }); A: Try this This will work in both condition whether your keyboard is showing enter sign or next arrow sign YourEdittextName.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(actionId== EditorInfo.IME_ACTION_DONE||actionId==EditorInfo.IME_ACTION_NEXT) { //Perform Action here } return false; } }); if u r facing red line then do this... import Keyevent and EditorInfo by pressing alt+enter then all the errors remove it will properly....... A: In Kotlin use viewBinding.editText.setOnEditorActionListener { view, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE) { //react to action } false } You can also return true inside 'if' braces to consume event - this way keyboard won't go down when you press done
{ "language": "en", "url": "https://stackoverflow.com/questions/7584036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: Glassfish - Unable to open Admin Console - throws NPE I have a Glassfish 3.1 production server that is suddenly acting up. Last week it was fine. This morning the it is throwing an NPE when attempting to load the admin console (localhost:4848). It is also throwing this same error when trying to run 3 of the 4 applications on the server. One of the apps works fine. All of the apps are JSF with LDAP security. I have a test server on a different box that uses nearly the same configuration files and works fine. The server is Win2003R2SP2. Java is jdk1.6.0_26. I have restarted the service and even rebooted the host server. I have also tried the -Dcom.sun.enterprise.tools.admingui.NO_NETWORK=true setting. These are the log entries that occur when I attempt to connect to the Admin Console or run one of these applications: [#|2011-09-28T09:15:53.059-0400|SEVERE|glassfish3.1|org.apache.catalina.connector.CoyoteAdapter|_ThreadID=21;_ThreadName=Thread-1;|PWC3989: An exception or error occurred in the container during the request processing java.lang.NullPointerException at java.util.concurrent.ConcurrentHashMap.remove(ConcurrentHashMap.java:922) at org.apache.catalina.session.ManagerBase.remove(ManagerBase.java:915) at org.apache.catalina.session.StandardSession.expire(StandardSession.java:847) at org.apache.catalina.session.StandardSession.expire(StandardSession.java:769) at org.apache.catalina.session.StandardSession.expire(StandardSession.java:757) at org.apache.catalina.session.StandardSession.setMaxInactiveInterval(StandardSession.java:587) at org.apache.catalina.session.ManagerBase.createSession(ManagerBase.java:762) at org.apache.catalina.session.StandardManager.createSession(StandardManager.java:311) at org.apache.catalina.connector.Request.doGetSession(Request.java:2899) at org.apache.catalina.connector.Request.getSession(Request.java:2561) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:920) at org.glassfish.admingui.common.security.AdminConsoleAuthModule.validateRequest(AdminConsoleAuthModule.java:169) at com.sun.enterprise.security.jmac.config.GFServerConfigProvider$GFServerAuthContext.validateRequest(GFServerConfigProvider.java:1171) at com.sun.web.security.RealmAdapter.validate(RealmAdapter.java:1311) at com.sun.web.security.RealmAdapter.invokeAuthenticateDelegate(RealmAdapter.java:1189) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:551) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:623) at org.apache.catalina.core.StandardPipeline.doChainInvoke(StandardPipeline.java:600) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:96) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:228) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:662) |#] [#|2011-09-28T09:15:53.105-0400|SEVERE|glassfish3.1|org.apache.catalina.connector.CoyoteAdapter|_ThreadID=18;_ThreadName=Thread-1;|PWC3989: An exception or error occurred in the container during the request processing java.lang.NullPointerException at java.util.concurrent.ConcurrentHashMap.remove(ConcurrentHashMap.java:922) at org.apache.catalina.session.ManagerBase.remove(ManagerBase.java:915) at org.apache.catalina.session.StandardSession.expire(StandardSession.java:847) at org.apache.catalina.session.StandardSession.expire(StandardSession.java:769) at org.apache.catalina.session.StandardSession.expire(StandardSession.java:757) at org.apache.catalina.session.StandardSession.setMaxInactiveInterval(StandardSession.java:587) at org.apache.catalina.session.ManagerBase.createSession(ManagerBase.java:762) at org.apache.catalina.session.StandardManager.createSession(StandardManager.java:311) at org.apache.catalina.connector.Request.doGetSession(Request.java:2899) at org.apache.catalina.connector.Request.getSession(Request.java:2561) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:920) at org.glassfish.admingui.common.security.AdminConsoleAuthModule.validateRequest(AdminConsoleAuthModule.java:169) at com.sun.enterprise.security.jmac.config.GFServerConfigProvider$GFServerAuthContext.validateRequest(GFServerConfigProvider.java:1171) at com.sun.web.security.RealmAdapter.validate(RealmAdapter.java:1311) at com.sun.web.security.RealmAdapter.invokeAuthenticateDelegate(RealmAdapter.java:1189) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:551) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:623) at org.apache.catalina.core.StandardPipeline.doChainInvoke(StandardPipeline.java:600) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:96) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:228) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:662) |#] Any suggestions on what to look into would be greatly appreciated. I can post more configurations as needed. Thanks A: I had exactly the same exception after it was necessary to kill all the Glassfish processes via a command line kill -9 command. A normal asadmin restart-domain was not possible to execute. So after this forced kill the admin web-frontend was not available anymore. I've solved this problem by executing asadmin set server.web-container.session-config.session-properties.timeout-in-seconds=3600 After that I restarted Glassfish via the normal asadmin restart-domain and then the Glassfish Admin console appears like usual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ODBC Connection in Asp.Net (Connect and Dispose) I Open and Close ODBC connection while the page is up and running. When and where should i put the Connection.Dispose method? I tried on the Page_Disposed but it never makes it there. Public Class _WepPage1 Inherits System.Web.UI.Page Dim MyConnection As New Odbc.OdbcConnection Private Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed MyConnection.Dispose() End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'String comes from Web.Config MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString If Not IsPostBack Then Call LoadSomeData() Else 'Do some more stuff End If End Sub Private Sub LoadSomeData() If MyConnection.State = ConnectionState.Closed Then MyConnection.Open() Dim MyCommand As New Odbc.OdbcCommand("select * from tablename", MyConnection) Try Dim dataR As Odbc.OdbcDataReader = MyCommand.ExecuteReader While dataR.Read DropDownList1.Items.Add(dataR("column1")) End While Catch ex As Exception End Try MyCommand.Dispose() If MyConnection.State = ConnectionState.Open Then MyConnection.Close() End Sub A: I would not use the Page_Load to start the connection. In .NET, the "real" connection object returns to the pool when you Dispose(), so it is there for other work. Even if you open, close and dispose numerous times, there is but a few microseconds of overhead max, so open a connection early and then keeping it open for the entire page duration does not really help you. In addition, opening connection in Page_Load means you have tightly coupled your data access to your UI, leaving you a lot of rearchitecture and not just rearrangement to divide the work into proper tiers. What this means is the connection should be created, used and disposed in one method (in your example). This means it is both logically separated and easy to separate into different classes and/or assemblies, should the application grow so you need a full DAL. I would, at minimum, move all realting to connection to the LoadSomeData() method. If you want more proper separation of concerns, make a GetSomeData() routine and have the LoadSomeData() routine call the GetSomeData() routine and shape the data so it can be easily bound, rather than consume one row at a time (In your example, instead of binding a data object to the drop down, you are pushing one item at a time). I hope this helps and I am sorry that many of the examples out there are really bad at best practices. And, yes, this includes many samples from people who should know better. ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Solr DataImportHandler with XML Files? I'm researching using DataImportHandler to import my data files utilizing FileDataSource with FileListEntityProcessor and have a couple questions before I get started that I'm hoping you guys can assist with. 1) I would like to put a file on the local filesystem in the configured location and have Solr see and process the file without additional effort on my part. Is this doable in any way? From what I've seen, this is not supported and I must manually call a URL (e.g. http://foo/solr/dataimport?command=full-import). The manual, URL-based invocation method seems perfectly logical in a database-oriented world, where one might schedule an update to run regularly but in my case I have a couple identical indexes I load balance between and don't want to run the same hefty query multiple times in parallel. As such, I'm doing one query, writing the results to an XML file, pushing that file to each box, and then wanting that file processed. I'd like the process to be as automated as possible. 2) I would like any files processed by Solr to be deleted after they've been imported. I haven't seen any way to do this currently. I thought I might be able to subclass something, but FileListEntityProcessor, for example, doesn't seem to give any handles at the right time in the workflow to delete a file. Is there somewhere else I can look? 3) When reading the DIH documentation, I ran across this statement: "When delta-import command is executed, it reads the start time stored in conf/dataimport.properties. It uses that timestamp to run delta queries and after completion, updates the timestamp in conf/dataimport.properties." If it really does update the date to the completion date, what happens to any files added between the start and end dates? Are they lost? 4) For delta imports, I don't see mention of how processed files are ordered other than that it tries not to re-import files older than that mentioned in the conf/dataimport.properties file. In cases where order matters, does it order the files by name or creation date or ...? A: the idea of solr/lucene is not to work as an database. It's an index. This means, it's an index for data, which resit somewhere else - regardless of the possibility to (index and) store the data in solr/lucene additional for special features (highlighting, etc). Therefore there is no out-of-the-box possibility to add single documents and delete those documents after importing. By the way, it's best practice to keep to original documents at an database, file system, etc. Probably you keep the original documents, but not on solr/lucene server?! URL-based invocation method seems perfectly logical in a database-oriented world, where one might schedule an update to run regularly but in my case I have a couple identical indexes I load balance between and don't want to run the same hefty query multiple times in parallel. You could define an operating-system scheduled job (cronjob) to start an delta import. I would like any files processed by Solr to be deleted after they've been imported I never heard about, that solr is able to do that. As i wrote above, the idea is, that solr is an index of data which is stored somewhere else. So the DIH expected the data/all the documents at "somewehere". If you remove the original documents from "somewehere" and updates the index, the intended target is to synchronize the index content with the (now) available documents... Are they lost? No. it reads the start time stored in conf/dataimport.properties. It uses that timestamp to run delta queries and after completion, updates the timestamp in conf/dataimport.properties." Solr reads the start time, run the delta queries and (...if it is finished, solr...) updates(... the start time...) as timestamp in conf/dataimport.properties." does it order the files by name or creation date or ...? Not sure, but i think it reads the files in the given order from the filesystem A: Got a great response from Erick Erickson on the Solr Mailing List: http://mail-archives.apache.org/mod_mbox/lucene-solr-user/201109.mbox/browser Specific replies below, but what I'd seriously consider is writing my own filesystem-aware hook that pushed documents to known Solr servers rather than using DIH to pull them. You could use the code from FileSystemEntityProcessor as a base and go from there. The FileSystemEntityProcessor isn't really intended to do very complex stuff..... 1> Don't think this is possible OOB. There's nothing built in to the DIH that puts in filesystem hooks and automatically tries to index it.... 2> Nope. DIH is pretty simple that way as per the FileListEntityProcessor. 3> I'm pretty sure this is irrelevant to FileSystemEntityProcessor, it's really used for the database importation. 4> "whatever order Java returns them in". Take a look at the FileListEntityProcessor code, but the relevant bit is below. So the ordering is whatever Java does which I don't know what, if any, guarantees are made. private void getFolderFiles(File dir, final List<Map<String,Object>> fileDetails) { // Fetch an array of file objects that pass the filter, however the // returned array is never populated; accept() always returns false. // Rather we make use of the fileDetails array which is populated as // a side affect of the accept method. dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { File fileObj = new File(dir, name); if (fileObj.isDirectory()) { if (recursive) getFolderFiles(fileObj, fileDetails); } else if (fileNamePattern == null) { addDetails(fileDetails, dir, name); } else if (fileNamePattern.matcher(name).find()) { if (excludesPattern != null && excludesPattern.matcher(name).find()) return false; addDetails(fileDetails, dir, name); } return false; } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plone: Pass a variable from PloneFormGen Custom Script Adapter to Mailer Adapter I have a PloneFormGen form with a Custom Script Adapter that, on form submission, generates a new uid and creates a folder with that uid as its ID. from DateTime import DateTime uid = str(DateTime().millis()) target.invokeFactory("Folder", id=uid, title=form['your-name']) It uses input from the form to create various items in that folder, including a document called "newpage", which I then want to include a link to in an email. Is there a way to pass the uid variable from the script adapter to the mailer adapter, so that I can generate the link to the new documents inside the folder? For instance, the script adapter creates a folder with the ID 1317142676351, so when the form is submitted, the URL for one of the new pages is http://mysite.com/submissions/1317142676351/newpage/. I want to be able to include that link in one of my Mailer Adapter templates, but I don't know how to get the uid that was generated in the Custom Script Adapter, or if that's even possible. What happens first, the Mailer, or the Custom Script Adapter? Any push in the right direction is greatly appreciated! A: Just copy the id value to the request. In the script, code like: request.set('custom_id', id) will do it. If you need the variable to be automatically handled, create a matching hidden variable in the form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check for IP address in table - mySQL PHP Alright. I have this contest signup form with 3 fields that inserts it into a mySQL DB... as well as emailing it. I am adding this code that will check the form for the users current IP, and disallow the submission if it exists. This seems to be executing without error now... but it allows multiple submissions from the same IP. Anything jump out as incorrect? FULL CODE BELOW: <?php //include the connection file require_once('connection.php'); function sanitize($value, $type) { $value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value; switch ($type) { case "text": $value = ($value != "") ? "'" . $value . "'" : "NULL"; break; case "long": case "int": $value = ($value != "") ? intval($value) : "NULL"; break; case "double": $value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL"; break; case "date": $value = ($value != "") ? "'" . $value . "'" : "NULL"; break; } return $value; } //save the data on the DB and send the email if(isset($_POST['action']) && $_POST['action'] == 'submitform') { //recieve the variables $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $email = $_POST['email']; $ip = gethostbyname($_SERVER['REMOTE_ADDR']); mysql_select_db($database, $connection); $QUERY = "SELECT COUNT(IP) AS `count` FROM `contest` WHERE IP = 'value'"; $RESULT = mysql_query($QUERY) or die(mysql_error()); // Read the firs row $row = mysql_fetch_assoc($RESULT); // Check how many rows MySQL counted if($row['count'] > 0) { echo "value already exists"; } else { //save the data on the DB mysql_select_db($database, $connection); $insert_query = sprintf("INSERT INTO contest (First_Name, Last_Name, Email_Address, Date, ip) VALUES (%s, %s, %s, NOW(), %s)", sanitize($firstname, "text"), sanitize($lastname, "text"), sanitize($email, "text"), sanitize($ip, "text")); $result = mysql_query($insert_query, $connection) or die(mysql_error()); if($result) { //send the email $to = "EMAIL ADDY"; $subject = "SUBJECT LINE"; //headers and subject $headers = "MIME-Version: 1.0rn"; $headers .= "Content-type: text/html; charset=iso-8859-1rn"; $headers .= "From: ".$firstname." <".$email.">rn"; $body = "New contact "; $body .= "First Name: ".$firstname." "; $body .= "Last Name: ".$lastname." "; $body .= "Email: ".$email." "; $body .= "IP: ".$ip." "; mail($to, $subject, $body, $headers); //ok message header ('Location: thanks.html'); exit (); } } } ?> A: You need to use backticks instead of single quotes to escape table names/reserved words: $QUERY = "SELECT COUNT(IP) AS `count` FROM `contest` WHERE IP = 'value'"; Also if your IP column is string you need to enclose the value for that in single quotes :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stuck with understanding this regex I'm stuck with this regex ((["0"-"9"])+ ("-")*)* (["0"-"9"])* ["a"-"z"] ( ["a"-"z","0"-"9"] )* ( ("-")+ (["a"-"z","0"-"9"])+)* What I understand so far is: ((["0"-"9"])+ ("-")*)* can be a number between 0-9. The plus means it can be repeated (e.g. 1157). Not sure about what the star does :S I think an example of this first line could be 1157- ? (["0"-"9"])* ["a"-"z"] ( ["a"-"z","0"-"9"] )* starts with a number, followed by a letters and numbers e.g. 1test5 ( ("-")+ (["a"-"z","0"-"9"])+)* optionally starts with a minus and follows by letters and numbers. e.g -54 If anyone could give me an example of a string that matches the regex it would be helpful. Finding is hard to understand this. :) A: + means at least one of the preceding expression * means 0 or more of the preceding expression So ((["0"-"9"])+ ("-")*)* (I will ignore the quotes) means: At least 1 digit, a space 0 or more - and all this can be repeated 0 or more times. that means it will match: * *The empty string *1 ------234 - *1 2 3 Normally, if you put a space into a regex it will then try to match a space. In my explanation I used it in this way. BUT there is e.g. in some languages an extended modifier, where space in the regex will not be interpreted, they can then be used to make the regex more readable. I don't know what your regex engine is doing in this case. You can see your regex here on Regexr (cleaned from the quotes) with some matching examples A: * *((["0"-"9"])+ ("-")*)* *(["0"-"9"])* *["a"-"z"] *( ["a"-"z","0"-"9"] )* *( ("-")+(["a"-"z","0"-"9"])+)* where: * is 0 or more + is one or more To better understand this regex I have broken it into segments which are far easier to read. To get the total string just follow each segment and you will get strings that match this complete regex. For segment 1: 1 or more digit followed by 0 to many hyphens '-', which can be repeated 0 or more times. segment 2: 0 or many digits segment 3: only 1 lower case character ("abcdefghijklmnopqrstuvwxyz") segment 4: 0 or many lower case characters or digits. segment 5: a hyphen 1 or more times followed by one or more lower case characters or digits, repeated 0 or more times. By putting this together we can get the minimum string needed to fit this regex: 0a-a where segments 2 and 4 can be ignored because they include 0 or more. Some more examples will be: 9-0a0a-a0 4456---4456---890aasd-asda-a434 to infinite length. A: Those quotes are odd, but I would guess at * *( 0-9 one or more times followed by "-" ) zero or more times. *then 0-9 zero or more times. *then a-z followed by a-z or 0-9 any number of times *then ( "-" at least once followed by a-z or 0-9 at least once ) zero or more times. So you might find matches like 0-a-a 9123-9123-312346-1412312-123223abcd992-a90898-z08333218457 123-1a92-----abcdef---------123456-a The options beyond that most basic capture are almost limitless...
{ "language": "en", "url": "https://stackoverflow.com/questions/7584060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combine delegates with an OR operator Looking up values in two different tables with LinqToSQL, and combining the results based on what is found in what resultset. How can I combine two Funcs based on given conditions: // a filter for a LinqToSQL query: Func<ComputerDetail, bool> filter; // declare the default filter filter = x => x.ComputerName.Contains(searchTerm); then if a condition is met it would like to add the below lambda to the above one: x => computernames.Contains(x.ComputerName) so it both would result in: x => computernames.Contains(x.ComputerName)) || x.ComputerName.Contains(searchTerm); Creating a multicast delegate with a plus operator almost seems to do it, however, I am not sure how to apply the OR (||) in this case: filter += computernames.Contains(x.ComputerName) note: computernames is a List<String> , ComputerName is a property of ComputerDetail which is a Class representing a View in LinqToSQL A: If it's LINQ to SQL, you don't want to combine two delegates - you want to combine two expression trees. Otherwise all of your filtering will be done on the client side. If that's the case, I believe you basically just need PredicateBuilder - use predicate1.Or(predicate2) to combine two predicates. If you really want the delegate form, you can take the same code and just change all the signatures to use delegates instead of expression trees.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails 3, redirect from https to https, overwrite _path helper I want to have mixed https/http site. Moreover I want have redirects from https to http(ie. after user login successfully it should redirect to root page at http). Gems like: * *rack-ssl *rack-ssl-enforcer works perfectly but only If you want to have entire site at https "Mixed http/https" with only ssl at A, B, C actions and only http at D, E, F - dont work. I checked solution from another SO thread: Rails 3 SSL routing redirects from https to http Almost works. Its easy to write script which will change(on entire views) helper from "_path" to "_url". But there is a problem with links like: <%= link_to "model", some_model %> <%= link_to "edit model", edit_mode_url(model) %> ... There are many diffrent models and I use often "model" at iteration blocks, so solution based on 'rewrite' script will dont work with that. Questions: Is there a way to change behavior of <%= link_to 'model', model %> code to fix that? Is there a possibility to overwrite path helper(standard protocol will be http, on giver parameter - https)? Or maybe there is a another solution which I have not found yet? Edit: I work with Rails 3.0.9. A: If you would like to add https to a particular route you can use this code before_filter :redirect_to_https def redirect_to_https redirect_to :protocol => "https://" unless (request.ssl? || request.local?) end You can define the routes you would like to use with the before_filter action simply by doing the following before_filter :redirect_to_https, :except => [:action1 , :action2] before_filter :redirect_to_https, :only => [:action1 , :action2] A: Use this gem: https://github.com/retr0h/ssl_requirement gem install ssl_requirement Then to add ssl_required :new, :destroy #others actions to your controllers. If you use devise you have to overwrite each controller and specify all actions devise_for :users, :controllers => { :confirmations => "confirmations", :omniauth_callbacks => "omniauth_callbacks", :passwords => "passwords", :registrations => "registrations", :sessions => "sessions", :unlocks => "unlocks" } do # etc end It works with Rails 3.0.x
{ "language": "en", "url": "https://stackoverflow.com/questions/7584062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use ScrollViewer inside another Scrollviewer The structure of my wpf application is like: <Scrollviewer> <Grid> <Scrollviewer> <DataGrid> My Goal is, if the DataGrid exceeds the height of the screen to use it's own Scrollviewer. At the Moment only the outside ScrollViewer is used and so i have to scroll the whole Grid. Can someone please tell me how to do this? A: You need to set a height on the inner ScrollViewer, otherwise it'll stretch as much as it needs based on it's content's size. <Window x:Name="RootWindow"> <ScrollViewer> <Grid Height="{Binding ElementName=RootWindow, Path=ActualHeight}"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="2*" /> </Grid.RowDefinitions> <ScrollViewer Grid.Row="1"> <DataGrid /> </ScrollViewer> </Grid> </ScrollViewer> </Window> Also, the DataGrid has built-in properties for it's own ScrollBars which you can use instead of wrapping the DataGrid in a ScrollViewer. This will scroll the data and always leave the headers visible, instead of scrolling the entire datagrid. <DataGrid HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" /> A: You might want to place the DataGrid outside the Scrollviewer then. Therefore you can set two Grid.Rows, and let it part the available size for you (default would be "equal" or if you use only two rows, 50%-50%). So if the DataGrid exceeds its available size it will use its own ScrollViewer. If the content below is exceeding the size, it will use your manually placed ScrollViewer. At least, that is how i would solved it based on your initial input. Feel free to add code / comments so we might find a better way. If you place two ScrollViewers plus a datagrid inside each other you will be forced to start passing out concrete Height or Width values if you want that kind of fine grained control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to read xml data from a DATASET object in c# I just used this code to read xml data from an XML file.It successfully reads the data from file.I Just want to know how can I read SelectSingleNode data from an xml dataset. public DataSet ds =new DataSet(); public FileStream stream = null; stream = new FileStream(schdlpath, FileMode.Open); ds.ReadXml(stream); //after this even if i delete the xml file it won't hamper the appliaction. stream.Close(); //this way I can print all the data.. Console.WriteLine(ds.GetXml()); All I want is to read the data like this public XmlDocument document = new XmlDocument(); XmlNode ht = document.DocumentElement.SelectSingleNode("/Schedule/AudioVedioPlayer/Height"); Actually I want to read the xml data and store it into a variable. A: public XmlDocument document = new XmlDocument(); document.LoadXml(ds.GetXml()); XmlNode ht = document.DocumentElement.SelectSingleNode("/Schedule/AudioVedioPlayer/Height"); A: You can write the xml from the dataset into a stream and then use the stream to read it into an XmlDocument object. From there, you can use the DOM to navigate. Now, are you trying to store a part of the data, as XML, into a variable? Or are you looking for the height value? If the former, I have no issue with your plan. If the later, I assume, from looking at your XPath statement (SelectSingleNode()) that you have the following: DataSet: Schedule Table: AudioVedioPlayer Property: Height If I am correct about your setup, then you can easily get to the value you require by drilling down into the DataSet. public DataSet ds =new DataSet(); public FileStream stream = null; stream = new FileStream(schdlpath, FileMode.Open); ds.ReadXml(stream); You can then get to the table: ScheduleTable table = ds.Schedule; And get the value int height = table.Height; Or you can just shortcut it int height = ds.Schedule.Height; No reason to get XML unless you want an entire section of XML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Maximum Combobox items in Windows Forms I need to have a combobox that can have a large number of items (around 700), but there seems to be a limitation on how many items a combobox can contain (100!). Is there a way that this limitation can be extended? UPDATE: I cant really explain the scope here, but a search box would not be appropriate. If MaxDropDownItems is set to 10 with 20 items, it provides a scroll bar to access the other 10, but is it not clear what will happen if 100 items is exceeded. Unfortunately, it is not as simple as shoving over 100 items in there as it is populated based on a database. However, thankfully, we have a testing team! I will post results of testing in due course. A: The ComboBox can easily contain thousands of items. The 100 limit you are referring to is the visible portion which is displayed when the ComboBox drop down appears. Note that the performance is tied to what type of data is being populated within the ComboBox; a complex object versus a simple string value. Virtualization of items does not exist with WinForms as it does in WPF/SL. A: As pointed out by GvS the MaxDropDownItems property is the maximum number of visible items when the drop down portion is displayed. So displaying 700 items (although not great for your users) will be possible. You could use the AutoCompleteMode property like below to enable filtering: AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); for (int i = 0; i < 1000; i++) { string item = string.Format("Item {0}", i.ToString()); collection.Add(item); comboBox1.Items.Add(item); } comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; comboBox1.AutoCompleteCustomSource = collection; A: The UI of a combobox is not designed to let the user select from a list of 1000 elements. I personally think 20 items in a combobox is already too much. But if you want to add 700 items, there are no technical limitations. Your users will be happier if you choose something that will make it easier to select an item. (Hint: something with a search box).
{ "language": "en", "url": "https://stackoverflow.com/questions/7584082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Most efficient way of going about programming this in Java Okay lets say you have a simple program which took letter a-z, and if you typed in "c" it would do something, for example "e" might add 2 random numbers, "h" displayed the word "hello", "x" displayed the time etc. Now how i'm attempting to go around this by having 26 different methods, one for each letter and then a main body of code, which scans for the the users input then calls the appropriate method. Now theirs obviously 100's of ways of going around this but the main two I'm thinking off is you could have 26 if's or a switch statement(Example, if(userInput.equals("a")) then call method a etc). Or another way I'm thinking off is having the methods labeled a-z and then lets say the user enters "f" instead of checking which letter it is it instead trusts the user and calls exactly the letter they've typed in. for example: -> User enters Y userInput = y; userInput(); - (which would essentially be calling y() which is a method name). I believe there is a way to do this using "Reflection" from reading around here but I've heard to avoid premature optimization but in this case wouldn't it be the most logical thing to do? A: The ways I see: * *1) setup a big if/else if tree to check user input *2) setup some flaky, unstable and slow Reflection stuff *3) Use a Map where 'String' would be the letter and the CmdHandler would be a class that has a function to be called. (Command Pattern) the #3 is a bit more architecture for such a simple example, but it lends itself to scaling better. EDIT: Quick n Dirty Example public class Testing { public static void main(String[] args) { CmdHandler ch = null; /* Setup & populate our map */ HashMap<String, CmdHandler> cmdMap = new HashMap<String,CmdHandler>(); ch = new AKeyHandler(); cmdMap.put(ch.getCmd(), ch); ch = new BKeyHandler(); cmdMap.put(ch.getCmd(), ch); /* ..etc.. */ /* Actually use the system now! */ String input = ""; input = "a"; /* Get our input from... whereever */ /* Do any input validation/manipulation here */ CmdHandler handler = cmdMap.get(input.toUpperCase()); if (handler != null) handler.doWork(); else System.err.println("Egads! A null!"); } public static abstract class CmdHandler { private final String cmd; public CmdHandler(String cmd) { super(); this.cmd = cmd.toUpperCase(); } public String getCmd(){ return this.cmd; } public abstract void doWork(); } public static class AKeyHandler extends CmdHandler{ public AKeyHandler() { super("a"); } public void doWork() { System.out.println("Executing the A Key cmd doWork()"); } } public static class BKeyHandler extends CmdHandler{ public BKeyHandler() { super("b"); } public void doWork() { System.out.println("Executing the B Key cmd doWork()"); } } /* ...etc... */ } A: I would consider using an enum. enum Letter{ A("a"){ @Override void foo(){ // do stuff } }, B("b"){ @Override void foo(){ // do stuff } }, . . . Z("z"){ @Override void foo(){ // do stuff } }; private final String text; Letter(final String text){ this.text = text; } abstract void foo(); public static final Letter getInstance(final String s){ for(Letter l: Letter.values()){ if(s.equalsIgnoreCase(l.text)){ return l; } } return null; } } This way you can simply get the user input, invoke Letter.getInstance(...) and then get the appropriate Letter instance. And then from there, you simply invoke foo() on the Letter instance, which will do something specific to that letter. A: This is the Command Pattern (Edit: deleted all humor; thank goodness for the humor patrol). There are any number of ways to implement it, but the simplest is a map of command handlers. A: Okay, first off, reflection is actually pretty slow. It requires the program to examine it's own code (although that may not be the source of the slowness). Do you really need 26 different methods? that smells a bit odd to me. Is there any repeat code in those methods? if yes, you should find that commonality and have a switch or set of if statements to manage the letter-specific code. This actually would be more efficient, and will create a smaller footprint for your application. The main problem with worrying about switch vs. if efficiency, as I see it, is that unless you're writing mission-critical software, or extremely optimized something (which you probably won't be writing in java), and the code in question is called thousands of times a second, the difference is negligible. Assuming you actually need those 26 different methods, Dave Newton's answer is probably what you want. A: Reflection would be an option but you would be at the risk of a user entering a function suffix which does not exist. If using a database is not an option, your best bet would probably be to instantiate a Map with the letters as the keys and the display result as the value and call the get(Object key) method with the user input as the key. If the result is null (user did not enter a letter) you can handle it appropriately. If the values need to be calculated when the user enters a letter, you can fill the map with objects implementing some interface with a "process" method. When you pull the value out you will just need to call the process method. Notice the use of the anonymous class, as this would probably be best in this situation. map.put("a", new Processor(){ @Override public String process(){ return "someString"; } } where Processor is some interface you have created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inserting a new entry to android calendar I am trying to add a new event into the android calendar. Here is the code I am using Intent intent = new Intent(Intent.ACTION_EDIT); intent.setType("vnd.android.cursor.item/event"); intent.putExtra("title", event.getSummary()); intent.putExtra("description", event.getDescription()); intent.putExtra("eventLocation", event.getLocation()); intent.putExtra("dtstart", event.getStartDate()); if(event.getEndDate() == null) { intent.putExtra("allDay", true); } else { intent.putExtra("dtend", event.getEndDate()); } startActivity(intent); I am implementing this method in a separate class which is not an activity class. So I am extending the activity class here. When i execute last line startActivity(intent); I am getting java nullpointer exception. No idea how to proceed. How could I add a entry in to android calendar? Thanks A: Are you instantiating your activity class with new? You can not do that. Activity classes must be instantiated by OS in order to be functional. Solution: You have to have a reference to Context in order to call context.startActivity(..). Pass an instance of context to your class in constructor. Hint: all Activities are Contexts, so just do new MyClass(this) from within an Activity. Also, your class does not need to extend Activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to block inserts in SQL Server from the same user only - serializable isolation I have the following table CREATE TABLE [dbo].[Test]([Id] [int] NOT NULL,[Name] [varchar](50) NOT NULL, CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ( [Id] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY=OFF, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO CREATE NONCLUSTERED INDEX [IX_Test] ON [dbo].[Test] ( [Name] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO Now I want to prevent inserts from the same user (but different session) until the session in progress has completed. For example, if user John starts the session with insert, I want his other session (with insert, too) to be blocked until the first session completes. In other words, I need to block inserts that do not yet exists. So i created the following two scripts to run them in separate Management studio query windows: First (user John; waitfor is in first query only to be able to simulate the problem): begin tran select COUNT(*) from Test with(updlock,holdlock) where Name = 'John' waitfor delay '00:00:05' insert into Test(Id,Name) select isnull(MAX(Id) + 1,1),'John' from Test commit tran Second (user Peter): begin tran select COUNT(*) from Test with(updlock,holdlock) where Name = 'Peter' insert into Test(Id,Name) select isnull(MAX(Id) + 1,1),'Peter' from Test commit tran Now if I start first query from the first Management Studio query window and then start second query in the second query window before the first has completed, the second query is blocked until the first one completes. Well, maybe this is how this is supposed to work, but it is not something I want: I want second session to be blocked only if the same user wants to insert data. In my example, John starts to insert data, but Peter (second query) is blocked until John's insert completes. Is it possible to instruct sql server (with locking hints, I suppose) to block second query only if the same user tries to insert data? For example, if John starts to insert data to only block John's other sessions, but not Peter's sessions? A: In this case you probably need to set up a flag in the DB which is user specific (create table with user_id and is_writting flag). When you start to write in the table first check whether the flag is set -when not update the flag and write to the table. After the write finished unset the flag. This is how I would probably solve this. But I'm open to any other ways ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing the size of a standard About panel In my app I display a standard About window using the method orderFrontStandardAboutPanel:of NSApplication. The panel thus presented has a size of 285x335 pixels. Is there a way to make it bigger? Thank you. A: You should probably read this article and this technote. You'll want to pay attention to the custom NSView section in the technote because you can't just specify as size for the standard window. At the end of the day, probably the simplest thing is to just treat it like opening any other window and implement the behavior yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IE8 opacity chops off background image I have a small problem with IE8. I have the following fiddle: http://jsfiddle.net/H577j/ In this I have two div and a h3. The h3 has got a background image and is at the same time shifted negatively with margin. The div that the h3 tag is inside has an opacity, made with both filter, -ms-filter, and opacityin CSS. The opacity works fine in all browsers, however, in IE8 the background image of the h3 tag is hidden. Does IE8 chop off anything outside the box? Or is there something else wrong? A: Try removing the IE opacity filter. I noticed that when you apply a filter to a box in IE, it automatically chops everything inside the box that spans outside of the box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to load xml file in classic asp Possible Duplicate: How to parse xml with Classic asp? I want to load one XML file in classic ASP. I am using blnFileExists = objDom.Load(Server.MapPath("\a\abcfiles\admin\image_name.xml")) but when I write blnFileExists it gives me false. What should I do? A: Write the contents of objDOM.parseError.reason to the response to find out why it didn't load. A: Verify the file path is as you have it written. The way you have it written, the file image_name.xml should be in C:\Inetpub\wwwroot\a\abcfiles\admin. If that's not the case, then there's part of the problem. You may want to instead give Server.MapPath a virtual path, like "/a/abcfiles/admin/image_name.xml". This path will be resolve to http://www.yourWebSite.com/a/abcfiles/admin/image_name.xml. Again, if this is not the correct path, adjust it as necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get post meta from a wordpress page to another? I have an about page in wordpress, I wanted its content to appear in the home page, I managed to do that using this code that I found through searching <?php $my_id = 256; $post_id_256 = get_post($my_id); $content = $post_id_256->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?> That works perfect. Now the page also has a costume field with I nee to also get - I tried to manipulate the above code (specially lines 2 and 3) but I cant get the costume field Hope you can help Thanks A: You can get custom fileds with get_post_meta(), like so: <?php $custom_field = get_post_meta(256, 'name_of_your_custom_field'); echo $custom_field; ?> A: Use below function to get the post's custom field values: $meta_values = get_post_meta($post_id, $key);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to make code wait untill an animation ends in android? I have an EditText with android:maxLength="17" and used buttons with onClickListener to update text of this EditText the process here is that when the text length reaches to 16 the EditText animate's towards left with distance of approx one character using TranslateAnimation(0, -15, 0, 0); and then the first character of EditText is being removed. for this first i call the method to perform animation and then call method to remove the the first characer like shown below animate(); removeChar(); The problem here is that before the end of animation the character got removed, means while the animation is running the removeChar() completes its functionality while i want the removeChar() to perform its functionality after animation ends. when i googled for this i found answer to use animation listener but while writing code in Eclips i don't found any animation listener for the object the methods have no error and perform their functionality accurate as i want. the code for methods is show below public void animate() { //slide is declared at class level slide = new TranslateAnimation(0, -15, 0,0 ); slide.setDuration(1250); slide.setFillAfter(true); myEditText.startAnimation(slide); } public void removeChar() { String update=""; for(int i=1 ; i < myEditText.getText().toString().length() ; i++) { update=update+input.getText().toString().charAt(i); } myEditText.setText(update); } I have also tried to use the code below to wait for end of animation but it halts the application . animate(); //slide is declared at class level while(!(slide.hasEnded())) { // Just waste the time } removeChar(); i think the application halts because all processing goes for while loop and animation doe'nt gots ended and hence loop becomes an infinite loop and causes application to halt i searched a lot and found no proper answer plz help me and i will prefer a code snippet or a little example as I'm new to android plz really need help... A: Attach an AnimationListener to your animation and then execute removeChar() in the onAnimationEnd() method. Like this: slide.addAnimationListener(new AnimationListener(){ public void onAnimationStart(Animation a){} public void onAnimationRepeat(Animation a){} public void onAnimationEnd(Animation a){ NameOfParentClass.this.removeChar(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7584102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to set width for messagebox in GXT/GWT? how to set width for message box? or how can we format the message that we display in the message box into multiple lines? Thanks! A: Use the setMinWidth and setMaxWidth functions to set the minimum/maximum width for the MessageBox in pixels.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: displayDiv.fadeIn('3000'); does not fade slowly on this webpage Technically displayDiv.fadeIn('3000'); should fade in the image slowly but on this page it does not: Please see: http://jsfiddle.net/BpXbn/3/ (on hover of "ice white image") Is there a possible reason for this or a way to fix this so the fade in works instead please? Kind regards, Kelly A: There's no built-in DOM method called "fadeIn". Perhaps you've seen it used in some jQuery code, or code from some other framework. If you just get a DOM element from the browser via "getElementById()", however, what you get is a plain DOM element and that has no such function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save objects in list without unique ID (belongsTo, hasMany) When I have collection, where each object is unique but they belong to some parentId, how should I store it? My Idea is * *ArrayList <MyType> objects_list; // to store those objects *ArrayList <int[]> parents_list // to store parent_id vs int[] object_list.id's So connection would be * *object_list.item belongsTo parents_list.item *parents_list.item hasMany object_list.item Isn't there some more efficient, more Java, solution? Little more explain: I have collection of object, where every object has parent_id in some variable within. I need to store those objects, so that I could easily select all objects by their parent_id And I cannot use simple one ArrayList with parent_id as key, because key has to be unique. So how to store them, to fetch all objects by their parent_id like Collection.getByParentId(parent_id) ? A: Like Dave said before, store the parent ID in MyType. // all MyType objects List<MyType> objects; // This way you could track the relations // (you would have to update this on change) Map<Integer, List<MyType>> relations; A: Try using Guava's ListMultimap ListMultimap<Integer, MyType> map = ArrayListMultimap.<Integer, MyType>create(); Then you can do: List<MyType> children = map.get(parentId); A: Yes; keep parent_id in MyType, where it belongs, or don't store it anywhere, and use the parent object's ID when you need it (it's unclear as worded what you're actually trying to accomplish). A: HashMap<Integer, ArrayList<MyObject>> myObjects = new HashMap(); // Assuming parent_id is Integer You can access it like this: ArrayList<MyObject> myObjectsArray = myObjects.get(parent_id);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrolled-menu UIComponenet in ios i want to build a scrolled-menu uicomponent like the image given below.could u guys help me which is the best place to start.Am i supposed to use a toolbar with button embedded with scroll? any help is much appreciated.. A: I would use a UIScrollView with your buttons as subviews. Forget about using UIToolbar because that would make things very complicated (You can use an image to imitate the appearance of the toolbar). Just make a UIScrollView, add your buttons as subviews, and remember to set the contentSize according with the number of buttons you have (numButtons*buttonWidth). That's my approach, but maybe there's another good/elegant solution. Here you'll find a PSD that will help imitating the toolbar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rounding using regular expressions Is it possible to use a regular expression to perform rounding on a number? The problem is that I've got a lot of numbers to more than 2 decimal places in a file and I need to move them to 2 decimal places. It's in source file so ideally I'd like to use Visual Studio's find and replace, but I'm not against the idea of writing a script to run on the file (treating it as plain text) if regex doesn't have the answer. A: I don't think you can round the numbers, since regular expressions can't do addition. You could truncate them as follows (this will work in Notepad++): find (\d*\.\d\d)\d* replace with \1 A: Well... at least you can search for (\d+\.\d\d\d)\d* and replace it with round($1, 2). Yeah, perhaps this is not what you expected :) A: You can't do it with regexes alone, as Ryan pointed out, but you can use regexes to find decimals in your input and use a callback function on the replace operation. In Python: >>> import re >>> text = "1.234 and 99.999; .555 12.345" >>> simpledec = re.compile(r"\d*\.\d+") >>> def mround(match): ... return "{:.2f}".format(float(match.group())) ... >>> re.sub(simpledec, mround, text) '1.23 and 100.00; 0.56 12.35' The regex to match decimals is very simplistic; it doesn't match exponential notation, for example, but it should give you an idea. A: I just came up with a simple way to do this for rounding results in a set of Google BigQuery results -- their subset of SQL doesn't let you round to a specific decimal place a.f.a.i.k., but it does support regexes. Since, as someone mentioned above, regexes can't add, then as long you can add a constant to each value somehow, you can still get the rest of the way there: + 0.5 if you're rounding up to the nearest integer + 0.05 if you are rounding up to the nearest 0.1 + 0.005 if you are rounding up to the nearest 0.01 etc. ... etc. - basically add half of your smallest precision value to get the rounding effect. And then run a regex extract on the result. The above ones will probably work done for this. Here's the regex pattern I settled on -- which is not the most robust, but will work on a number that is already known to be in basic float format: + for 0.1 precision use (-?\d*\.?\d?) + for 0.01 precision use (-?\d*\.?\d?\d?) + for 0.001 precision use (-?\d*\.?\d?\d?\d?) Then it's both rounded and truncated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to force ASP.NET forms authentication to use absolute URL for ReturnUrl parameter? When you use ASP.NET forms authentication, and you want to surf to a secure page like securepage.aspx, you would be redirected to this URL: http://www.example.com/login.aspx?returnurl=securepage.aspx` Is there a way to get the absolute URL in login page, like: http://www.example.com/login.aspx?returnurl=http://www.example.com/securepage.aspx I need this feature, because I'm working on a rather complicated SSO project, and I need to always work with absolute URLs. A: try this <httpRuntime useFullyQualifiedRedirectUrl=”true”
{ "language": "en", "url": "https://stackoverflow.com/questions/7584114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unwanted dependency logging with log4j I'm using a project call JarClassLoader (JCL) which allows me to load a jar from an InputStream. This is very helpful, but I've found that the JarClassLoader leaves an log4j.xml file and loads that file at runtime. I'm using slf4j for my logging statements, and also using log4j for logging in my project. Here is a link to the JCL log4j.xml file: http://code.google.com/p/jcloader/source/browse/trunk/JCL2/src/main/resources/org/xeustechnologies/jcl/logging/log4j.xml?r=142 I would like to ignore this completely, as I have my own logging setup. Any ideas on how I can prevent this file from being loaded? Or how I can remove JCL logging after it's loaded. Or, if there is something else other than JCL that can read a InputSteam and grab the jar file out of the stream. Thanks in advance. A: Actually, it's a mistake to ship log4j.xml (or any other logging configuration file) with a library that is intended to be linked with other projects. It results with exactly the problem you have now. I'd issue a bug report for that and use a private copy of the jar file without log4j.xml, until it is fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: django - multiple queries into one I want to find the Records with a certain tag within 100 mile radius. I have two queries that work independently (see below) but I don't know how to put them together. Also Records model has a foreign key pointing to the GeoLocation model called geo_location. I want to be able to show fields from both models (Records and GeoLocation) in one shot. I tried with .select_related() on the GeoLocation query below but for some reason I only get it to show the GeoLocation model fields and not the additional Records model fields as I expected. tag_search = Records.objects.filter(tags__slug__in=[tag]) geo_search = GeoLocation.objects.select_related().filter(srid2163__distance_lte=(pnt, D(mi=100))).distance(pnt) Any ideas? These are my models: from taggit.managers import TaggableManager from django.contrib.gis.db import models class GeoLocation (models.Model): lat = models.FloatField(blank=True) long = models.FloatField(blank=True) srid2163 = models.PointField(blank=True,srid=2163) server_time = models.DateTimeField(auto_now_add=True) objects = models.GeoManager() def __unicode__(self): return u'%s %s %s' % (self.lat, self.long, self.server_time) class Records(models.Model): title = models.CharField(blank=True, max_length=50) message_body = models.TextField() server_time = models.DateTimeField(auto_now_add=True) geo_location = models.ForeignKey(GeoLocation, related_name='geoloc') tags = TaggableManager() def __unicode__(self): return u'%s %s %s' % (self.title, self.message_body, self.server_time) For the tags field in the Records model I'm using django-taggit. A: There are two things wrong here. Firstly, you've misunderstood what select_related() does. It doesn't bring the fields from the related model into the current one. Instead, it just pre-fetches the related instance, so that doing the model_instance.foreignkey_field.field_on_related_model doesn't cause another db hit. Secondly, your models contradict what you originally said about the foreignkey. You said it was from GeoLocation to Records, but the model definitions show that is the other way round. select_related does not work in that direction - there is no way, given your current models, to query GeoLocation and get the related Records in one go. However, you can query Records and get the related GeoLocations. (Thirdly, your answer to my comment about the use of the single-element in lookup is completely irrelevant. Use tags_slug=tag.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to set in a binary form of number at some position 1 or 0 Suppose I have an eight bit number, I want to set at each bit position number 1 or zero, it is dynamic situation. Suppose for example such situation, user enters two numbers which are equal or differs only by one, and I want that at each iteration from 0 position to seven, write these 0 and 1 in binary form of number, how can I implement it in cycle? Please help me. An example: int result = 0; for (int i = 0; i < 8; i++) { int x, y; cin >> x >> y; if (x == y) { // set at i position 0; } else if ((x-y) == 1) { // set at i position 1;(in result number) } } updated : it is what i want to implement : Adding two 8-bit two's complement binary numbers here is code for this #include <iostream> using namespace std; int main(){ int x,y; cin>>x>>y; int result=0; int carry=0; int sum=0; for (int i=0;i<8;i++){ sum=carry; sum+= (x&(1<<i)); sum+=(y&(1<<i)); if (sum>1){ sum-=2; carry=1; } else{ carry=0; } result|=sum; result<<=1; } cout<<result<<" "<<endl; return 0; } A: You can change individual bits with AND and OR binary operators. For example: //set first bit to 1 value |= 1; //set fourth bit to 0 value &= ~(1<<3); //set 6th bit to 1 value |= (1<<5); A: Consider bit shifting. To set the bit: result |= (1<<i); Un-setting the bit is left as an excercise to the reader. A: I don't know what happens if your inputs are different by two but you might want something like this: int result = 0; for (int i = 0; i < num_bits; ++i) { int a, b; std :: cin >> a >> b; result |= (a != b); result <<= 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to decrypt the text Thanks for previous replies I am doing encryption and decryption for my log in authentication. i used define('VECTOR', 'EXfPCW23'); //example, not the actual used VECTOR / KEY $key = 'lolwatlolwat'; $filter = new Zend_Filter_Encrypt(); $filter->setEncryption(array('key' => $key)); $filter->setVector(VECTOR); return $filter->filter($password); this codings to encrypt the data. whenever i tried to decrypt the data, the values never be decrypted. in the above coding i changed $filter=new Zend_Filter_Decrypt(); for the decryption. pls guide me to decrypt the encrypted value. i am new to this topic. A: You can try this $filter = new Zend_Filter_Decrypt('myencryptionkey'); // Set the vector with which the content was encrypted $filter->setVector('myvector'); $decrypted = $filter->filter($encrypted); print $decrypted; Please refer http://www.thomasweidner.com/flatpress/2009/01/14/how-to-encrypt-with-zf/
{ "language": "en", "url": "https://stackoverflow.com/questions/7584136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excluding an ID from a global styling I am setting the style of list items like so: ul.list li { background: #FFFFFF; padding: 0 5px 0 5px; height: 20px; } ul.list li:hover { background: #F7F7F7; } but I want to define a special list item for the title of the list only it inherits the previously defined style too. I know I could just give the above styling a class but that feels cumbersome. Do I have to manually "undo" everything just for the special list item or give the above styling a class? or is there a better way to do it? Maybe I shouldn't be using a list item for the title? ul.list li.header { font-size: 16px; font-weight: bold; } A: If you're at liberty to use advanced CSS3 selectors, you can use the :not() selector: ul.list li:not(.header) { background: #FFFFFF; padding: 0 5px 0 5px; height: 20px; } Otherwise, you'll just have to manually override them. A: If the title of the list must be inside the list, I'd probably just (as you mentioned) "manually undo" them: ul.list li.header { font-size: 16px; font-weight: bold; background: transparent; padding: 0; height: auto; } It's not so bad. If you only need to support modern browsers, you could do this: .list li:not(:first-child) { background: #FFFFFF; padding: 0 5px 0 5px; height: 20px; } .list li:first-child { font-size: 16px; font-weight: bold; } .list li:hover { background: #F7F7F7; } This eliminates the need for any classes (though you could replace :first-child with .header if you do want to keep that class).
{ "language": "en", "url": "https://stackoverflow.com/questions/7584137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I setup libxml in Eclipse Indigo CDT C++ This all is under Mac OS X 10.6 and the libxml libraries seem to be in /usr/local/libxml2/libxml, I added this to the GNU C++ support but still I get errors for the code that uses libxml. I couldn't find anything that explains what to do to get it working and my project to compile. edit: Example errors void printElementNames(xmlNode * a_node) { } This would give "Type xmlNode could not be resolved". A: I got this here: forum * *Right-click your CDT project and select Properties. *Expand C/C++ General and select Paths and Symbols. *Select GNU C++ under Languages *Click Add to define new element *Write in the Directory field /usr/local/libxml2/libxml *Re-build A: I'm working in the Cygwin environment, on Windows 7 (64bit), using Eclipse Kepler CDT for C++. In Eclipse, goto Project --> Properties --> C++ Builder --> Settings --> Tool Settings Tab Cygwin C++ Linker --> Libraries In the Libraries (-l) add the file: xml2.dll In the Library search path (-L) add the path: "C:\cygwin64\lib" Cygwin C++ Compiler --> Includes In the Include paths (-I) add the path: "C:\cygwin64\usr\include\libxml2"
{ "language": "en", "url": "https://stackoverflow.com/questions/7584139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIImageViews added to UIScollView never get deallocated, Memory Leak? This is my first post and you are my last hope. I have a list with images in my iPad app, if you select one, my class MyViewController which extends UIViewController is loaded and shown (by just setting window.rootViewController, by using UINavigationController, by presentModalViewController - tried everything, doesn't make any difference). It has a UIScrollView inside, which adds a big version of the image to the UIScrollView with this code: UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[[delegate getImageNames] objectAtIndex:(gameNr*2)]]]; tempImageView.frame = CGRectMake(0,0,tempImageView.frame.size.width/2,tempImageView.frame.size.height/2); [self setMyImage:tempImageView]; [tempImageView release]; myScrollView.contentSize = CGSizeMake(myImage.frame.size.width, myImage.frame.size.height); myScrollView.maximumZoomScale = 2.0; myScrollView.minimumZoomScale = 1.0; myScrollView.clipsToBounds = YES; myScrollView.bounces = NO; myScrollView.delegate = self; [myScrollView addSubview: myImage]; myImage is a (nonatomic, retain) property of the type UIImageView inside my MyViewController. After pressing a button and go back to the list of images, I release the reference to MyViewController and it's dealloc method is called like this: - (void)dealloc { CFShow(@"dealloc!"); for(UIImageView *subview in [myScrollView subviews]) { if(subview.frame.size.width > 20){ [subview removeFromSuperview]; [subview setImage:nil]; } } [myImage setImage:nil]; self.myScrollView = nil; self.myImage = nil; [myScrollView release]; [myImage release]; [super dealloc]; } It works so far, but the problem is, that the memory of the images is not really deallocated this way. After opening and closing about 12 images, the app crashes with memory warning. This is also confirmed by the report_memory method I got from here: iOS Low Memory Crash, but very low memory usage The dealloc method IS called, that's triple checked. I checked the variables myImage and myScrollViewvia breakpoint in the debugger, they are set to 0x0 by those commands in the dealloc method. Why is the memory not freed???????? Thanks for any suggestion, I am working on this since three whole days, it's driving me crazy. A: Replace this: self.myScrollView = nil; self.myImage = nil; [myScrollView release]; [myImage release]; with this: [myScrollView release]; self.myScrollView = nil; self.myImage = nil; And post code where you define property myScrollView and init it. And you don't need loop for(UIImageView *subview in [myScrollView subviews]). When you will release myScrollView object it will automatically release all its subviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select distinct values from 2 tables with sort in one query? I have * *table1 : country, theOrderColumn1 *table2 : country, theOrderColumn2 I want to join DISTINCT country from these two SELECT statements: SELECT DISTINCT `country` FROM `table1` ORDER BY `theOrderColumn1` and SELECT DISTINCT `country` FROM `table2` ORDER BY `theOrderColumn2` Example: table1 (country, theOrderColumn1): (uk, 1), (usa, 2) table2 (country, theOrderColumn2): (france, 1), (uk, 2) I want this result: france uk usa A: select distinct country from ( select country, theOrderColumn from table1 union all select country, theOrderColumn from table2 ) a order by theOrderColumn A: select country, theOrderColumn from ( select distinct t1.country as country, t1.theOrderColumn as theOrderColumn from table t1 union select distinct t2.country as country, t2.theOrderColumn as theOrderColumn from table t2) t3 order by theOrderColumn A: If you want to preserve order given by theOrderColumn1 and theOrderColumn2 at the same time, you can use the column index to specify the ORDER BY column. SELECT DISTINCT country FROM ( ( SELECT country AS c, theOrderColumn1 AS d FROM table1 UNION SELECT country AS c, theOrderColumn2 AS d FROM table2 ) ORDER BY 2) Take a look at the answers to this question: SQL Query - Using Order By in UNION A: select a.country,a.theOrderColumn ( select country,theOrderColumn from table1 union select country,theOrderColumn from table2 ) a order by a.theOrderColumn Though you will get duplicates if theOrderColumn is different in table 1 and table 2. A: It depends on what you are wanting and how you want to join the two tables together. If you are joining based on "theOrderColumn", then the query would be SELECT DISTINCT country FROM table1 JOIN table2 ON table1.theOrderColumn = table2.theOrderColumn ORDER BY theOrderColumn If you want to join across country (which wouldn't make sense as the country would be identical in both tables) then you could swap out "country" in the join clause. Also, depending on your SQL dialect spoken by your DBMS, your mileage may vary with the above query. Can you clarify more of what you are after?
{ "language": "en", "url": "https://stackoverflow.com/questions/7584144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: C Windows buffer size In windows lets say i'm using the recv function to receive data from a socket. I'm curious how big would an optimal buffer be? I could make it 1024 bytes or I could make it 51200 bytes, or bigger. I'm wondering which one would be better for performance. This doesn't only apply to the recv function, lets say im reading a large text file, do i want a very large buffer, or a smaller buffer? A: THe operating system performs its own buffering, so the size of your buffer does not really matter. the performance penalty lies in the function call: a 1 byte buffer will be inefficient because it will require too much calls to recv(). a buffer too big is just a waste of space. an optimal size will be something like twice the size of the data you expect to receive or are able to process in a single recv() call, with a lower limit of approximately 1 or 2 tcp frame. i personally use a 4KB buffer, but that's my own preference, and it depends largely on the application i am writing. A: The operating system buffers it already, so you might as well just read one byte at the time. A: This would depend on the kind of data you are expecting and the protocol you expecting. UDP for example would give you a whole packet in one go so an optimal buffer size could be 1500. The real performance impediment would be the function call (recv in this case) that you will make. To improve performance, you could start with a default large value and then analyze the packet sizes being received. Based on the analysis, you could pass an (almost) "ideal" buffer size. A: If you have a server-type situation where you don't know what services are to be run on it, you could use an array of buffer pools of varying sizes, eg [128,1024,4096,16384,65536]. When something connects, use a 128 size and, if all 128 come in, use 1024 next time.. and so on. On clients or servers with a known protocol/loading, just sorta guess at it, (much as suggested by the other posters :) Rgds, Martin
{ "language": "en", "url": "https://stackoverflow.com/questions/7584147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: session time out I use asp.net and set the session timeout using Session.Timeout = 1440; but the session timed out, is there anything shall I fix or adjust in iis 7 and 6 Best regards A: This may work <configuration> <sessionstate mode="inproc" cookieless="false" timeout="1440" /> </configuration> A: If the sessionstate timeout in the web config is not working check for memory leaks in your application. I had the same problem in a legacy application I inherited. After a lot if digging I found some custom server controls with static variables and static objects referenced by multiple pages and other objects. This caused the application to never release resources. Eventually IIS recycles the pool when it runs out of memory. When the pool is recycled all sessions will be unloaded from memory also.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to check sql version in wix Is there any way to find the sql server is 64 bit or 32 bit in machine using wix. I am building the wix in visual studio 2010.Based on configuration the installer will install. At install time it will check sql is 64 or 32. If OS is 64bit but 32 sql is installed my installer will install. Thanks, Rajeev Kumar. A: To detect if the target machine is 32-bit or 64-bit you can use VersionNT64 property. This property can be used as a launch condition to stop the 32-bit package from installing on a 64-bit machine. A 64-bit package cannot run on a 32-bit machine and is stopped automatically. For detecting SQL Server there are multiple approaches. For example you can search for registry values or use a custom action. Perhaps this article will help: http://blogs.msdn.com/b/sqlexpress/archive/2006/07/29/682254.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7584150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: How to correctly loop through multi-dimen post arrays If I have a form with fields like this. THERE WILL BE MULTIPLE ROWS OF THESE FIELDS HENCE THE SQUARE BRACKETS <input type="text" name="txt-receipt-number[]" value="" /> <input type="text" name="txt-stock-number[]" value="" /> <input type="text" name="txt-repair-code[]" value="" /> How do I loop through the $_POST variable to get the values because its getting the field names but not the values, what am I doing wrong please? $fields = array(); $values = array(); foreach($_POST as $field => $value) { $fields[] = $field; echo $value; } Output: ArrayArrayArrayArrayArrayArrayArrayArrayArray Update: Sorry, quick edit for correct output... Further Update: Lets ignore the insert, how do I get the values please? A: Remove the [] of your text input, or you will get $value of array type. <input type="text" name="txt-receipt-number" value="" /> <input type="text" name="txt-stock-number" value="" /> <input type="text" name="txt-repair-code" value="" /> And don't forget to quote your values. A: You will have some other problems though, with column names like sales_receipt-number, etc. You should enclose those in backquotes, and you must also escape them since they are going directly into your SQL statement. They are just as vulnerable to SQL injection as the VALUES(). $fields[] = "`" . mysql_real_escape_string($field) . "`"; Update 2 To get the values and do the insert in a loop, the SQL needs to be reconstructed each time in the loop, using one set of array values. // Find the number of loops necessary // Unless all fields are always required, this will need to be the $_POST key with the most values $numLoops = count($_POST['txt-receipt-number']); fields = array(); $values = array(); for ($i = 0; $i < count($_POST); $i++) { foreach($_POST as $field => $value) { $fields[] = "`" . mysql_real_escape_string($field) . "`"; $values[] = mysql_real_escape_string($_POST[$field][$i]); // Now build the SQL for this loop iteration. $sql = 'insert into table(' . join(',', $fields) . ') values(' . join(',', $values) . ')'; } } A: This is a little bit strange but try it : <?php foreach($_POST['txt-receipt-number'] as $k=>$v){ $array[$k]['txt-receipt-number'] = $_POST['txt-receipt-number'][$k]; $array[$k]['txt-stock-number'] = $_POST['txt-stock-number'][$k]; $array[$k]['txt-repair-code'] = $_POST['txt-repair-code'][$k]; } $fields = array(); $values = array(); foreach($array as $row) { foreach($row as $field => $value) { $values[] = $value; $fields[] = $field; } } var_dump($fields); var_dump($values); ?> <form method='post' action=''> <input type="text" name="txt-receipt-number[]" value="" /><br> <input type="text" name="txt-stock-number[]" value="" /><br> <input type="text" name="txt-repair-code[]" value="" /><br> ---- <input type="text" name="txt-receipt-number[]" value="" /><br> <input type="text" name="txt-stock-number[]" value="" /><br> <input type="text" name="txt-repair-code[]" value="" /><br> <input type="submit" value="go"> </form> A: To be honest, I see many problems in this code... * *Using foreach to build dynamic list of fields that need to be inserted. Don't you have, for example, anything like <input type='submit' name='add_data'/>? It's common to have submit buttons, and, with your code, you would try to edit DB table's field named add_data. This is also unsafe, as it (a) reveals table structure and (b) gives possibility to make SQL errors by manually changing field names, which may lead to another security/stability issues. *Lack of escaping field names. May lead to SQL injections. *Using - sign in field names. insert into table(sales_receipt-number, ... just won't work. As for handling posted arrays... <form method='post' action=''> <table border='1'> <tr> <td><input type='text' name='receipt_number[]'/></td> <td><input type='text' name='stock_number[]'/></td> <td><input type='text' name='repair_code[]'/></td> </tr> <tr> <td><input type='text' name='receipt_number[]'/></td> <td><input type='text' name='stock_number[]'/></td> <td><input type='text' name='repair_code[]'/></td> </tr> <tr> <td><input type='text' name='receipt_number[]'/></td> <td><input type='text' name='stock_number[]'/></td> <td><input type='text' name='repair_code[]'/></td> </tr> <tr> <td colspan='3'> <input type='submit' name='add_items'/> </td> </tr> </table> </form> <pre> <?php function handleAddingItem() { if ( !isset($_POST['receipt_number'], $_POST['stock_number'], $_POST['repair_code']) ) { trigger_error("Some field is undefined"); return false; } if ( !is_array($_POST['receipt_number']) || !is_array($_POST['stock_number']) || !is_array($_POST['repair_code']) ) { trigger_error("Some field is not an array"); return false; } $keys = array_keys($_POST['receipt_number']); if ( array_keys($_POST['stock_number']) !== $keys || array_keys($_POST['repair_code']) !== $keys ) { trigger_error("Posted arrays have different keys"); return false; } foreach ( $keys as $key ) { if ( empty($_POST['receipt_number'][$key]) && empty($_POST['stock_number'][$key]) && empty($_POST['repair_code'][$key]) ) { continue; } $receiptNumber = mysql_real_escape_string($_POST['receipt_number'][$key]); $stockNumber = mysql_real_escape_string($_POST['stock_number'][$key]); $repairCode = mysql_real_escape_string($_POST['repair_code'][$key]); $sql = " insert into table_name set receipt_number = '{$receiptNumber}', stock_number = '{$stockNumber}', repair_code = '{$repairCode}' "; echo $sql; } return true; } function handlePost() { print_r($_POST); if ( isset($_POST['add_items']) ) { handleAddingItem(); } } if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { handlePost(); } ?> Output: Array ( [receipt_number] => Array ( [0] => 123 [1] => [2] => ) [stock_number] => Array ( [0] => [1] => [2] => ) [repair_code] => Array ( [0] => [1] => [2] => ) [add_items] => Submit Query ) insert into table_name set receipt_number = '123', stock_number = '', repair_code = '' Common practice might be to pass additional field - row's ID. If it has a value, then action is "edit", if it is empty, action is "create". A: foreach($_POST as $field => $value) { if(is_array($value)) { foreach($value as $k => $val) { echo $val; } } else { echo $value; } } Works for regular fields and one-dimensional _POST fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting background color for Spinner Item on selection I am using the Spinner control in my code. I want the item to get highlighted (i.e., background color changed for that item) on selection. How can this be achieved? A: create a xml: for ex:mybg.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false" android:drawable="@color/anyColor" /> <item android:drawable="@android:color/transparent" /> </selector> and in your activity xml do <Spinner............... android:drawSelectorOnTop="true" android:background="@drawable/mybg"/> A: * *Create custom View layout (e.g. from TextView) *Create Selector and set it as a background of that view *Set Spinner with custom view Selector: custom_selector.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@color/light_grey" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/light_grey" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@color/light_grey" /> <item android:state_selected="true" android:drawable="@color/light_grey"/> <item android:drawable="@color/white" /> </selector> Custom View layout: my_simple_item <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:lines="1" android:padding="5dip" android:background="@drawable/custom_selector"/> Initialise Spinner: String[] items = new String[] {"One", "Two", "Three"}; Spinner spinner = (Spinner) findViewById(R.id.mySpinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_simple_item, items); Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7584158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Security concerns regarding username / password vs secret URL I have a simple site with a sign-up form. Currently the user can complement their registration with (non-critical, "low security") information not available at the time of the sign-up, through a personal (secret) URL. I.e., once they click submit, they get a message like: Thanks for signing up. You can complement your registration by adding information through this personal URL:       http://www.example.com/extra_info/cwm8iue2gi Now, my client asks me to extend the application to allow users to change their registration completely, including more sensitive information such as billing address etc. My question: Are there any security issues with having a secret URL instead of a full username / password system? The only concern I can come up with is that URLs are stored in the browser history. This doesn't worry me much though. Am I missing something? It's not the end of the world if someone changes some other users registration info. (It would just involve some extra manual labor.) I will not go through the extent of setting up https for this application. A: This approach is not appropriate for sensitive information because it's part of the HTTP request URL, which is not encrypted and shows up in many places such as proxy and other server logs. Even using HTTPS, you can't encrypt this part of the payload, so it's not an appropriate way to pass the token. BTW, another problem with this scheme is if you send the URL to the user via email. That opens up several more avenues for attack. A better scheme would require some small secret that is not in the email. But it can be challenging to decide what that secret should be. Usually the answer is: password. A: Another potential problem lies with the users themselves. Most folks realize that a password is something they should try to protect. However, how many users are likely to recognize that they ought to be making some sort of effort to protect your secret URL? A: The problem here is that although it is hard to guess the URL for any specific user, given enough users it becomes relatively easy to guess a correct url for SOME user. This would be a classic example of a birthday attack. ETA: Missed the part about the size of the secret, so this doesn't really apply in your case, but will leave the answer here since it might apply in the more general case. A: The "secret URL" is often referred to as security by obscurity. The issue is that it is super simple to write a script that will attempt various combinations of letters, symbols, and numbers to brute force hack this scheme. So if any sensitive information is stored you should definitely use at least a username and password to secure it. A: can complement their registration with (non-critical, "low security") information It's hard to imagine what user-supplied information really is "low-security"; even if you are asking for a password and a username from your customers you are potenitally violating a duty of care to your customers; a large propertion of users will use the same username/password on multiple sites. Any information about your users and potentially a lot of information about transactions can be used by a third party to compromise the identity of that user. Any information about the user should be supplied in an enctypted format (e.g. via https). And you should take appropriate measures to protect the data you store (e.g. hashing passwords). Your idea of using a secret URL, means that only you, the user, anyone on the same network as the user, in the vicinity of a user on wifi, connected to any network between you and the user, or whom has access to the users hardware will know the URL. Of course that's not considering the possibility of someone trying a brute force attack against the URLs. C. A: The secret URL means nothing if you're not using SSL. If you're still having the end-user transmit their identifying information across the Internet in the clear, then it doesn't matter how you're letting them in: They are still exposed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: deleting nested categories from a table I have a table called categories which looks like this +-------------+--------------+---------------+ | id | catName | parentId | +-------------+--------------+---------------+ | 1 | Category 1 | 0 | | 2 | Category 2 | 0 | | 3 | Sub Cat 1 | 1 | | 4 | Sub Cat 2 | 1 | | 5 | Sub sub cat 1| 4 | | 6 | Sub sub cat 2| 4 | | 7 | Category 2 | 0 | +-------------+--------------+---------------+ It would be easy to delete a category and its direct child: mysql_query("DELETE FROM `categories` WHERE `id`='$id'"); mysql_query("DELETE FROM `categories` WHERE `parentId`='$id'"); However I need to be able to delete ALL children of a category. For example if Category 1 was deleted Sub Cat 1, Sub Cat 2, Sub sub cat 1, Sub sub cat 2 will be deleted Any help appreciated. A: You could use foreign keys, a very nice feature of mysql. This is a kind of integrity check for referencing different relations. If you create a foreign key, mysql ensures that referenced entries exist, for example. During the creation of a foreign key, you can define what mysql should do if the "parent element" is deleted. You can specify "SET NULL", "UPDATE" or "DELETE CASCADE". This means, if you delete a category, every connected sub category is deleted as well. And because of the fact that every sub category is the parent category of a sub sub category, those are deleted as well. A: Here is a simple recursive script for deleting your category and all the nested categories nested inside. try { $db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); }catch( PDOException $e ) { echo $e->getMessage(); } class Category { function delete_category($parrent){ global $db; $stmt = $db->prepare("SELECT `id` FROM `categories` WHERE `parrentId`=:parrentId"); $stmt->execute(array('parrentId'=>$parrent)); while($category = $stmt->fetchObject('Category')){ $category->delete_category($category->id); } $stmt = $db->prepare("DELETE FROM `category` WHERE `id` = :id"); $stmt->execute(array('id'=>$parrent)); } function __construct(array $data = NULL) { if( empty($data) ) return; foreach( $data as $field => $value ) { $this->$field = $value; } }} Where $db is your PDO object for connecting with the database. It may have some bugs, as i just modified mine to suit your problem. Hope this helps. PS: for calling your function you just do: $category=new Category(); $category->delete_category($_GET['id']) A: Quoted my original answer for clarity. UPDATE 1: The problem with the table splitting is that it isn't clear that there is a fixed number of sub, sub, categories. For this to work, you would need to split into as many tables as there are subcategories, each with foreign keys back to their parent ids. Not practical if the number of sub (or sub sub) categories is dynamic. This is a situation where I think you would benefit in changing your table design. If you split the two tables into categories and subcategories you could take advantage of the foreign key functionality as described by strauberry. For example (these don't look like tables, but hopefully this makes sense) Stuff in parentheses is explanation: categories * *id (primary key) *catName subcategories * *sub_id (primary key) *id (foreign key referencing primary key of categories table) *subCatName Then when you create the categories table, you can use the ON DELETE CASCADE option. This will mean that whenever you delete a category from the categories table, all related subcategories in the subcategories table will be deleted automatically for you by MySQL. Powerful, and reduces your code, and you don't have to make sure all deletions happen in the right tables manually. Hope that clarifies a little. UPDATE 2: The problem with this option is, well, it won't work :) MySQL will not allow you to subquery on the same table that you are doing the DELETE on. So what appeared at first to be a simple problem... isn't. If you can't change the table design then you could do the following (substitute the id you actually want to delete for category_id_to_delete): DELETE FROM categories WHERE id = category_id_to_delete OR id IN ( SELECT id FROM categories WHERE parentID = category_id_to_delete ) So, I did some more checking, and came across this similar question on SO MySQL: How to find all IDs of children recursively?, and the highest rated answer points to this article Managing Hierarchical Data in MySQL. That article points out the type of queries with LEFT JOINS that you need to use to select data, but doesn't explicitly cover how to delete that data. The recommended solution would be to use the queries related to adjacent sets from the article to select all the id information you need, and then in your code (php I think?) loop over those ids and construct a new query to delete them. For example, if you are trying to delete Category 1 (id=1), your goal by looping over the ids from the LEFT JOIN query from the article would be to create another query that looks like: DELETE FROM categories WHERE id IN (1,3,4,5,6); The code in this forum post also may help you as a means of doing it recursively in php: Adjacency List Model recursive deletion I know that isn't a neat and tidy answer, but perhaps this will point you in the right direction. A: demonstration of the mysql "cascade on delete" feature. if you run this in your console, then you can just run all the queries at once, and the output will make sense. if you run it in some graphical tool, then i suppose you'll have to run the queries one by one. CREATE DATABASE `recursivedemo`; USE `recursivedemo`; CREATE TABLE `categories` ( `id` INT AUTO_INCREMENT, `catName` VARCHAR(50), `parentId` INT, PRIMARY KEY (`id`), KEY `parentId` (`parentId`), CONSTRAINT `categories_fk_self` FOREIGN KEY (`parentId`) REFERENCES `categories`(`id`) ON DELETE CASCADE ) Engine=InnoDB; SELECT * FROM `categories`; INSERT INTO `categories`(`catName`, `parentId`) VALUES('Category 1', NULL); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Category 2', NULL); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Sub Cat 1.1', 1); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Sub Cat 1.2', 1); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Sub sub cat 1.2.1', 4); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Sub sub cat 1.2.2', 4); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Sub Cat 2.1', 2); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Sub Cat 2.2', 2); INSERT INTO `categories`(`catName`, `parentId`) VALUES('Category 3', NULL); SELECT * FROM `categories`; DELETE FROM `categories` WHERE `id`=1; SELECT * FROM `categories`; DROP DATABASE `recursivedemo`; A: You can use following Function in model for deleted nested categories: public function delete_by_id($cat_id) { $this->db->delete('Categories', ['cat_id' => $cat_id]); $q = $this->db->where('parent_id', $cat_id)->get('Categories'); foreach( $q->result() as $Child ) { $this->delete_by_id($Child->cat_id); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is Collections.syncronizedList effectively a vector? Does Collections.syncronizedList(new ArrayList()) effectively makes the arrayList a vector? If no then what extra does it do? If yes then why was it introduced in the first place? Thanks. A: It provides a synchronized view (a wrapper) of any list. The differences: * *you can make a synchronized view of any list implementation. A synchronized LinkedList is not a Vector. *the original list is not synchronized - only the view is. A: * *It doesn't make a list something else, but wraps a List with something that looks like a list also, but contains no data except the wrapped list. *See 1. A: Collections.synchronizedList(...) wraps synchronized access to the underlying list, but still retains the underlying list's characteristics in other ways. So for example, if you wrap a LinkedList, the iterator() remove() will be an efficient operation. (The same operation on a Vector is O(n).) So the wrapper is absolutely not the same as a Vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Tabs and document.ready fn I used jQuery tabs to implement different versions of the same page in 3 tabs... I found out that if I load the first page then second and third tabs dont implement $.ready and whts inside it. If I load the third tab then all tabs have proper jquery job done. The case is when I proceed forward I have the problem. Is there any way to work around this?! A: I don't know if this will work, but you could try to attach your $.ready code to a custom event on, say.. your pages <body> tag. That way, from within the parent page (the one with the tabs) you can trigger that custom event, something like: $("#custom_body_id").trigger("event_name"); You can trigger that event on the load event triggered by the tabs plugin. I'd recommend checking out the plugin's doc Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7584171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a problem with a Zend framework site and windows web hosting? Is there a problem with a Zend framework site and windows web hosting? The web hosting guy at the company I work for said that there is a problem and the site will only work on a linux based hosting. He gave me the credentials and told me to try. PHP5 using Zend framework and with some modifications on the index.php in the wamp server. (I programmed it on the wamp server 2 on my pc). Zend Studio if it is important. A: ZF will run just fine on Windows. You don't even have to have your index.php file in the "public" directory. If your project structure looks like the following and their Windows hosting uses Apache you can just rename your public folder to htdocs (common apache public folder): -- application/ -- library/ -- public/ ---- index.php Your host may not be willing to alter certain settings for public folders because they have an automated script that does it for them and makes it difficult to modify it per account, but you can also edit the index.php file to fit any structure. The stock index.php file looks like this: <?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), get_include_path(), ))); /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap() ->run(); If you just change the defines for APPLICATION_PATH and the library folder in the set_include_path, then you should have no problem using ZF with your host's stock settings. The default path assumes your public directory sits in the same folder as your application and library folders, but this is changed easily by editing the paths above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Dynamically create more than one instance of class and reference it I want to dynamically create more than one instance of the BindingSource class to be public throughout my Form. If I use Dim o As Object = Activator.CreateInstance(GetType(BindingSource)) it will only create one instance of this class. How can I create multiple instances of this class and reference them uniquely. The number of instances needed is not known at design time, so I cannot do Dim o1 As Object = Activator.CreateInstance(GetType(BindingSource)) Dim o2 As Object = Activator.CreateInstance(GetType(BindingSource)) Dim o3 As Object = Activator.CreateInstance(GetType(BindingSource)) It's in vb.net I hope I make sense... Regards Marius A: Your design doesn't make any sense. But, I'll answer your question, and you can ask a new question to puzzle out the flaws in your design. Make a dynamic collection, such as List<BindingSource> that you can add to as needed. Then, in a loop, you can instantiate as many BindingSource as you need, and add them to the List<BindingSource> as needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is a document/NoSQL database a good candidate for storing a balance sheet? If I were to create a basic personal accounting system (because I'm like that - it's a hobby project about a domain I'm familiar enough with to avoid getting bogged-down in requirements), would a NoSQL/document database like RavenDB be a good candidate for storing the accounts and more importantly, transactions against those accounts? How do I choose which entity is the "document"? I suspect this is one of those cases were actually a SQL database is the right fit and trying to go NoSQL is the mistake, but then when I think of what little I know of CQRS and event sourcing, I wonder if the entity/document is actually the Account, and the transactions are Events stored against it, and that when these "events" occur, maybe my application also then writes out to a easily queryable read store like a SQL database. Many thanks in advance. A: Personally think it is a good idea, but I am a little biased because my full time job is building an accounting system which is based on CQRS, Event Sourcing, and a document database. Here is why: Event Sourcing and Accounting are based on the same principle. You don't delete anything, you only modify. If you add a transaction that is wrong, you don't delete it. You create an offset transaction. Same thing with events, you don't delete them, you just create an event that cancels out the first one. This means you are publishing a lot of TransactionAddedEvent. Next, if you are doing double entry accounting, recording a transaction is different than the way your view it on a screen (especially in a balance sheet). Hence, my liking for cqrs again. We can store the data using correct accounting principles but our read model can be optimized to show the data the way you want to view it. In a balance sheet, you want to view all entries for a given account. You don't want to see the transaction because the transaction has two sides. You only want to see the entry that affects that account. So in your document db you would have an entries collection. This makes querying very easy. If you want to see all of the entries for an account you just say SELECT * FROM Entries WHERE AccountId = 1. I know that is SQL but everyone understands the simplicity of this query. It just as easy in a document db. Plus, it will be lightning fast. You can then create a balance sheet with a query grouping by accountid, and setting a restriction on the date. Notice no joins are needed at all, which makes a document db a great choice. A: Theory and Architecture If you dig around in accounting theory and history a while, you'll see that the "documents" ought to be the source documents -- purchase order, invoice, check, and so on. Accounting records are standardized summaries of those usually-human-readable source documents. An accounting transaction is two or more records that hit two or more accounts, tied together, with debits and credits balancing. Account balances, reports like a balance sheet or P&L, and so on are just summaries of those transactions. Think of it as a layered architecture -- the bottom layer, the foundation, is the source documents. If the source is electronic, then it goes into the accounting system's document storage layer -- this is where a nosql db might be useful. If the source is a piece of paper, then image it and/or file it with an index number that is then stored in the accounting system's document layer. The next layer up is digital records summarizing those documents; each document is summarized by one or more unbalanced transaction legs. The next layer up is balanced transactions; each transaction is composed of two or more of those unbalanced legs. The top layer is the financial statements that summarize those balanced transactions. Source Documents and External Applications The source documents are the "single source of truth" -- not the records that describe them. You should always be able to rebuild the entire db from the source documents. In a way, the db is just an index into the source documents in the first place. Way too many people forget this, and write accounting software in which the transactions themselves are considered the source of truth. This causes a need for a whole 'nother storage and workflow system for the source documents themselves, and you wind up with a typical modern corporate mess. This all implies that any applications that write to the accounting system should only create source documents, adding them to that bottom layer. In practice though, this gets bypassed all the time, with applications directly creating transactions. This means that the source document, rather than being in the accounting system, is now way over there in the application that created the transaction; that is fragile. Events, Workflow, and Digitizing If you're working with some sort of event model, then the right place to use an event is to attach a source document to it. The event then triggers that document getting parsed into the right accounting records. That parsing can be done programatically if the source document is already digital, or manually if the source is a piece of paper or an unformatted message -- sounds like the beginnings of a workflow system, right? You still want to keep that original source document around somewhere though. A document db does seem like a good idea for that, particularly if it supports a schema where you can tie the source documents to their resulting parsed and balanced records and vice versa. A: You can certainly create such a system. In that scenario, you have the Account Aggregate, and you also have the TimePeriod Aggregate. The time period is usually a Month, a Quarter or a Year. Inside each TimePeriod, you have the Transactions for that period. That means that loading the current state is very fast, and you have the full log in which you can go backward. The reason for TimePeriod is that this is usually the boundary in which you actually think about such things. A: In this case, a relational database is the most appropriate, since you have relational data (eg. rows and columns) Since this is just a personal system, you are highly unlikely to have any scale or performance issues. That being said, it would be an interesting exercise for personal growth and learning to use a document-based DB like RavenDB. Traditionally, finance has always been a very formal thing, and relational databases are typically considered more formal and rigorous than document databases. But, like you said, the domain for this application is under your control, and is fairly straight forward, so complexity and requirements would not get in the way of designing the system. If it was my own personal pet project, and I wanted to learn more about a new-ish technology and see if it worked in a particular domain, I would go with whatever I found interesting and if it didn't work very well, then I learned something. But, your mileage may vary. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to apply DRM on a .mp3/.wav file Can anyone help me to apply DRM on .mp3 or .wav. I know about DRM, but i have no idea about it's implementation process. If anyone has any idea on DRM's implementation(for .mp3/.wav) pleae help me. It would be great if this is for C#. It would be nice if any of you give me some Source/link. Thanks Pranab A: To DRM any sort of file, all you are really doing is encrypting it in such a way that only authorized clients (programs) can retrieve the content from the file. Typically, this requires special client software. Depending on your requirements, it may also require a central server for these clients to call back to. In general, you cannot simple "DRM an .mp3", because a generic MP3 player cannot read the data then. (if it could, it wouldn't be a DRMed file then, now would it?) A: Possible, yes. Easy, not so much: * *The "easiest" way is to drop the MP3 or WAV requirement and go with WMA (Windows Media Audio). In that case, you could use the Microsoft PlayReady Server SDK (expensive - several tens of thousand $) to do Windows Media DRM-compatible encryption. The resulting encrypted WMA can then be played by Windows Media Player and by a very large number of portable devices, after having received a "license" (essentially, decryption key + usage rights). *If you decide to go with WMA and you can't do large upfront investments, perhaps a hosted (SaaS) solution such as BuyDRM is for you. *Another possibility, which requires an even larger investment, if you want to stick with MP3 or WAV, is to use PlayReady itself with the "Envelope" format, or OMA 2 DRM with the "DCF" format, or Marlin DRM, or several other ones, which in addition to investing on the server side would also require you to write a custom media player.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Purpose of MySQL support for "where col = 1 = 0"? I recently discovered a statement in my code where I built up a MySQL statement that looks like the following: select * from atable where col = 1 = 0 I was surprised that this actually is valid syntax - treated like "col = 0". I would like to understand why this is valid syntax and why the statement like this is not rejected. It certainly appears to be confusing, yet I just stumbled over it in logging execution, so I would never have known it was being generated otherwise. Is there a specific purpose in this format that I am missing? A: It is same as col != 1. It checks that col = 1 is false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stretch an iOS UISlider I want to use the standard iOS slider in my application, but wanted it to be a bit stretched so it doesn't "disappear" under my finger... neither google or the books informed me about this.. Is is possible? thks! A: Set a custom thumb image then, using setThumbImage:forState:
{ "language": "en", "url": "https://stackoverflow.com/questions/7584192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple jquery script not working in safari This script works in firefox, IE, and chrome, but not safari. Any ideas? The really strange thing is that when I put an alert() at the end of the .get() callback, it executes (even in safari). So the code isn't crashing, it's just not modifying the DOM. <html> <head> <title>Title for this webpage</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script> <!- CSS styling --------------------------------------------------------------> <style type="text/css"/> body{ margin:0px; padding:0px; font-family:verdana, arial, helvetica, sans-serif; font-size:14px; text-align:left; width:900px; margin-left:auto; margin-right:auto; position:relative; background-color:#fff; } #mainBox{ width:700px; margin:30px; border:2px solid #ddd; margin-left:auto; margin-right:auto; } #mainHeader, #mainFooter, #mainContent{ margin: 5px; padding:10px; border: 2px dashed #ddd; text-align:center; } .shuffleMe{ margin: 5px; padding:10px; border: 2px solid #ddd; text-align:left; } </style> <!- Jquery/javascript --------------------------------------------------------> <script type="text/javascript"> //Code modified from: http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery $(document).ready(function(){ var my_list = $('.shuffleMe').get(); my_list.sort(function(){return( Math.random() >.5 );}); $.each(my_list, function(index, item) { $('#mainContent').append(item); }); }); </script> </head> <!- HTML body content --------------------------------------------------------> <body> <div id="mainBox"> <div id="mainHeader"> --- HEADER --- </div> <div id="mainContent"> <div class="shuffleMe">AAA</div> <div class="shuffleMe">BBB</div> <div class="shuffleMe">CCC</div> <div class="shuffleMe">DDD</div> </div> <div id="mainFooter"> --- FOOTER --- </div> </div> </body> </html> A: This is an issue with your sort function. The sort function should return -1 (less), 0 (equals), or 1 (more); it shouldn't return a boolean. The fact that it works in other browsers is a fluke in this case I think. my_list.sort(function(){return( Math.random() - .5 );}); A: You need to change your sorting function. See this jsFiddle. This code is working: var my_list = $('.shuffleMe').get(); my_list.sort(function(){ return 0.5 - Math.random(); }); $.each(my_list, function(index, item) {$('#mainContent').append(item); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7584194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sharer link with parameter in URL I have a popup window with a Facebook custom share link. http://www.facebook.com/sharer.php?u=<url to share>&t=<title of content> How can I use a url u with a parameter like http://google.com/?q=bla? It looks like facebook always cut of the parameter. A: You should URL encode the parameters. var facebook_url = 'http://www.facebook.com/sharer.php?'+ 'u='+encodeURIComponent('http://google.com/?q=bla')+ '&amp;t='+encodeURIComponent('Some Page Title');
{ "language": "en", "url": "https://stackoverflow.com/questions/7584197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I obtain the hostname or address of my .js script from inside the .js script? I have a web site which downloads the same script from any number of different servers: <script type="text/javascript" src="http://server1.example.com/hello.js"></script> <script type="text/javascript" src="http://server2.example.com/hello.js"></script> <script type="text/javascript" src="http://server3.example.com/hello.js"></script> <script type="text/javascript" src="http://server4.example.com/hello.js"></script> Each script has a locally-scoped variable which has to be the hostname of the server that script was downloaded from: so when I download the script from server1.example.com that variable's value has to be server1.example.com. Can this be done with absolutely no server-side programming? (AJAX requests can be sent, but the solution cannot include any server-side code) Please note that I am looking for the host which the script is hosted on, not the host of the current browser page; that means I am not looking for window.location. A: I think the below code can help: var scripts = document.getElementsByTagName('script'); for(var a = 0; a < scripts.length; a++){ if(scripts[a].src.indexOf('<<<--###-->>>') > 0 ) var ThisScriptPath = scripts[a].src.substr( 0, scripts[a].src.lastIndexOf('/')); } You will need to replace the <<<--###-->>> with your script's name, and you will have the path stored in ThisScriptPath (remember to use the final slash) Tip: Use an alert to check the results before getting into production A: You can extract from window.location.host the first part of the domain name with regex. You can use that in order to extract the first part var host = window.location.host; host = host.match(/^[\d\w]+/);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect a realm authentication failure reason in Tomcat I wrote a custom Realm for Tomcat 7. I wrap it in the lockout Realm provided by the default installation of Tomcat. The lockout feature works fine, but in my web.xml, I have <error-page> <error-code>403</error-code> <location>/forbidden.html</location> </error-page> which will direct any users that do not authenticate to the page. However, it also redirects correctly authenticated users to the page if they are locked out. Is there someway I can detect the difference when a user incorrectly authenticates and is locked out? A: It does not look easy. My first idea was subclassing the LockOutRealm and adding something to the request context if the user is locked out which you can print to the user interface later. Unfortunately it will not work because the authenticate methods of the LockOutRealm just got the login and password and there is no request or context objects there. Another problem is that the authenticate methods returns null when the authentication failed and LockOutRealm also does that. There is no difference between the behavior of the LockOutRealm and the behavior of any other realm when the authentication failed. A workaround: If you are using Servlet 3.0 use the login method of the HttpServletRequest interface, implement the lockout logic yourself and check the count of failed login attempts before your servlets call the HttpServletRequest.login() . If it's higher than the limit don't call the login() and print a custom error message. A: Have same question. There might be something in the request scope. Have experience with another lockout realm that I used with Tomcat 5.5 and it would put into the request scope "com.ofc.tomcat.LOGIN_FAILURE_MESSAGE" and if that was not present then the user must have been locked out. A: This thread is very old and my answer most certainly is very delayed. However, I shall enumerate one way of doing the above. Custom messages after authentication providing the reason for failure is slightly complicated in Tomcat, however, it can be achieved. To achieve this, one of the methods is to construct a custom Tomcat Valve and add it at an appropriate level (Host, Engine or Context). Tomcat automatically inserts the FormAuthentication Valve to the processing pipeline, if any web application uses FORM authentication. The idea is to intercept the 'j_security_check' action from the browser and do some pre-validations before it lands with the FormAuthentication Valve. In the 'invoke' method, both the user name ('j_username') and password ('j_password') are available as clear text from the request object. With these it can be checked whether an account is locked out or user needs to change password etc. by directly going into the realm (Database or LDAP etc.). From this valve, a response.redirect() can be sent to appropriate error pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get relative path to image in another project in same solution I have a Silverlight project with several projects in my solution. I want to get a relative path to an image in project A from project B inside my helper C# class. solution -Project A -Helper.cs -Project B -image.jpg Helper.cs need a reference to image.jpg I can't add a reference to prj A from prj B. Can I do something like: Uri uri = new Uri("/project.name.projectA;image.jpg", UriKind.Relative); Thank you A: pack://application:,,,/ReferencedAssembly;component/ResourceFile.xaml Replace ReferencedAssembly with the name of the referenced assembly and ResourceFile.xaml with the name of the file in it which has build type resource. Resource File Pack URIs Referenced Assembly
{ "language": "en", "url": "https://stackoverflow.com/questions/7584212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ios 4.3 uploading file to wcf json web service I've been killing myself over this bug/problem for a few days now, and I am going insane. I have no idea why it is break. I was wondering if you guys and gals can lend me a hand and rid of my insanity. So thank you in advance. What I am trying to do: upload a .wav file to a wcf json web service (.net 4.0) from an iphone app (ios 4.3). I have verified that the service does work from a different client. The problem: the problem is the same code on the iphone app worked 5 days ago. Yesterday and today the code decided to not work. Nothing had changed on the service side and the iphone app. I'll post as little code as I can to keep things relevant and simple to the topic. If there is a need to post more code to make it easier for you all, I will. I am consistently getting status code 400 back from the response in the didReceiveResponse method. I've check the url which i post to many times, and the url seem valid to me. The size of the file which I am posting to the json web service is 1KB < fileSize < 450KB. here is a sample url that i post to: http://random-ec2-id-east-1.elb.amazonaws.com/sampleApp/?key=ee404d54-ea45-421a-9633-1ea35c0c211e&token=zJSRqiZgmU6nOW44CeAzhWYxasdD0158yysNDCiASMk.eyJpdiI6IlU3Y2UwbWNXVGN6WVVBLU42SDVieGcifQ.kLbcRPOJ_QnrrtsBe-zF2-2IIbAffArvqeyAmwp_OpOWAoADMugHYjTPcnjkjQvzxEIMcm2k3933i3GqF2YFhAFDtItwvqre5fIGlixbuwsYhrVCm9FBoue4dCQ_pPX-yjUtq_898FGWa5INl0RG0A&type=c&platform=i // ################################ - (id)init { self = [super init]; if (self) { self.sampleAppInstance = [sampleAppInstance sharedSampleAppInstance]; self.sampleAppUrl = @"http://random-ec2-id.us-east-1.elb.amazonaws.com/sampleApp/"; self.key = @"ee404d54-ea45-421a-9633-1ea35c0c211e"; self.token = self.sampleAppInstance.facebook.accessToken; // facebook access token self.type = @"c"; self.platform = @"i"; } return self; } // ################################# - (BOOL) save:(NSString *)_fileName { NSString *url = [NSString stringWithFormat:@"%@?key=%@&token=%@&type=%@&platform=%@", self.sampleAppUrl, self.key, self.token, self.type, self.platform]; NSData *voiceData = [NSData dataWithContentsOfFile:_fileName]; //NSLog(@"%@", url); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]] autorelease]; [request setValue:@"text/plain" forHTTPHeaderField:@"content-type"]; [request setHTTPMethod:@"POST"]; [request setValue:[NSString stringWithFormat:@"%d", [voiceData length]] forHTTPHeaderField:@"content-length"]; [request setHTTPBody:voiceData]; [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; return FALSE; } // ################################# - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //NSLog(@"did failed"); [self.delegate responseDidFailWithError:error]; } // ################################# - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //NSLog(@"did receive data"); //NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); [self.delegate responseDidReceive:data]; } // ################################# - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; int statusCode = [httpResponse statusCode]; // if get 400, then malform syntax //NSLog(@"%d", statusCode); if (statusCode != 200) [self.delegate responseDidFailWithStatusCode:statusCode]; } A: it turns out that my service only accept file size < 65k by default. the fix was to configure my service to accept file > 65k.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which event of repeater control fires at the time of page_init or page_load? I have a scenario like facebook wall where I need to display image of user in repeater control who posted. I have tried myrepeater_ItemCommand1 or myrepeater_ItemDataBound but not working. Code behind protected void myrepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { try { LinkButton lblPostedBy = (LinkButton)e.Item.FindControl("lblPostedBy"); con.Open(); cmd.CommandText = "select image from " + lblPostedBy.Text + " where id=1"; cmd.Connection = con; string imageurl = (string)cmd.ExecuteScalar(); con.Close(); Image Image1 = (Image)e.Item.FindControl("Image1"); Image1.ImageUrl = imageurl; } catch (Exception a) { lblMsg.Text = a.Message; msgbox.Visible = true; } } and same in myrepeater_ItemCommand1 which is working if I click button inside Repeater. I wanted to know that which event of Repeater control fires at the time of Page_Load or Page_Init. Or, kindly suggest me other way to accomplish my task. BTW, my project is in C# ASP.NET 4. A: After the post has been saved, you should rebind the repeater. After rebinding the repeater, your updates should display. //update some stuff in the database Repeater1.DataSource = RepeaterDataSource(); Repeater1.DataBind(); EDIT <asp:Repeater ID="Repeater1" runat="server" ...> <ItemTemplate> <asp:Image ID="imgProfilePic" runat="server" ImageUrl='<%#Eval("ProfileImageUrl")%>' ... /> <%#Eval("PostMessage")%> </ItemTemplate> </asp:Repeater> And in the code behind: protected void BindDataToRepeater() { Repeater1.DataSource = GetUserPosts(); Repeater1.DataBind(); } After an update: protected void Button1_Click(object sender, EventArgs e) { //save post to database SavePost(); //rebind the repeater to display the post that was just added BindDataToRepeater(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to convert date in d-m-y format to Ymd within query I need to compare dates within a query, the date is stored in the database like d-m-y (24-Mar-11) and I need to convert it to Ymd (20110324). This is what my query looks like, I need to convert the C.SP_COMMENTS_ACTIVITY_DATE to Ymd Is it possible to do this at run time or do I need a separate function to capture that value then convert it before running this query? return $this->db ->distinct() ->select('*') ->from('SP_COMMENTS C') ->where('C.SP_COMMENTS_USERNAME', $user) ->where('C.SP_COMMENTS_YEAR_CODE', $year_code) ->where('C.SP_COMMENTS_ACTIVITY_DATE >=', date("Ymd", strtotime($this->input->post('user_begin_date')))) ->where('C.SP_COMMENTS_ACTIVITY_DATE <=', date("Ymd", strtotime($this->input->post('user_end_date')))) ->get() ->result_object(); A: ->where('DATE(C.SP_COMMENTS_ACTIVITY_DATE, "%Y%m%d") >=', date("Ymd", strtotime($this->input->post('user_begin_date'))))
{ "language": "en", "url": "https://stackoverflow.com/questions/7584223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Styling form in jQuery-Dialog On my jQuery - Dialog I have a form with multiple form fields. There I have a link to add "Attributes". Now I want to have this on the left side of the dialog and on the same line like the submit button. The div "somediv" must be an inline-element. How can I achieve that? jsFiddle - http://jsfiddle.net/Auzx6/ (Please expand the "Result" frame a lot.) Thank you very much! A: Adding a <br clear="all" /> before the div actions (<div class="actions">) should make the trick. The clear="all" will clean all the previous floats. Then if you want it on the left side just add this css rule "text-align: left" on that div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC 3 Architectural Direction I am converting a classic ASP website to .NET. The application already has a back-end database with stored procedures for communicating with the DB. I want to use MVC3 and EF for this project. My question is where is a good moderate example of these working in this environment? I understand how the Model View Controller pattern works on basic examples. I went through the MVC Music Store demo and deployed it. However, I'm struggling with where I put certain code. I'm looking for examples of how to tie into the existing DB with EF using the stored procedures and how the models should look. I'm also looking for where do I put code which is traditionally object methods. If I have a Contact model, where does the code go to interact with that contact? And I'm not talking about the code that brings back the data you want to push to the View. Is that where Repositories come in? If so, where is a good tutorial on using repositories? I appreciate the help. I realize this is a bunch of questions in one, but I don't think I'm the only one struggling with this either. A: I'm sure there are plenty of tutorials available, which should help you get started. The 'Nerd dinner' example helped me getting started, as it gave good explanations of the repository pattern, and how to separate the project. You can find the current project here: http://nerddinner.codeplex.com/ A: A good example of a client-side complex web application is Project Silk from Microsoft. It contains a lot of design guidelines / documentation on MSDN website and a sample app with full source code you can download and play with. I would recommend taking a look at it, especially if you have a complex UI to implement (jQuery, jQuery UI, client-side rendering, AJAX) A: I would definitely put the DAL in a separate project and I would definitely create an abstraction layer between the data access layer and the business logic layer of my application. The Repository and Unit of Work Patterns are great for this purpose. You can take a look at following articles. They are great for starting to create your data access layer : Creating an Entity Framework Data Model for an ASP.NET MVC Application http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application These are from Getting Started with EF using MVC series on http://asp.net. You can find more useful articles there from the navigation panel on the left hand site there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find a specific char in an array of chars I am doing an application where I want to find a specific char in an array of chars. In other words, I have the following char array: char[] charArray= new char[] {'\uE001', '\uE002', '\uE003', '\uE004', '\uE005', '\uE006', '\uE007', '\uE008', '\uE009'}; At some point, I want to check if the character '\uE002' exists in the charArray. My method was to make a loop on every character in the charArray and find if it exists. for (int z = 0 ; z < charArray; z ++) { if (charArray[z] == myChar) { //Do the work } } Is there any other solution than making a char array and finding the character by looping every single char? A: One option is to pre-sort charArray and use Arrays.binarySearch(charArray, myChar). A non-negative return value will indicate that myChar is present in charArray. char[] charArray = new char[] {'\uE001', '\uE002', '\uE003', '\uE004', '\uE005', '\uE006', '\uE007', '\uE008', '\uE009'}; Arrays.sort(charArray); // can be omitted if you know that the values are already sorted ... if (Arrays.binarySearch(charArray, myChar) >= 0) { // Do the work } edit An alternative that avoids using the Arrays module is to put the characters into a string (at initialization time) and then use String.indexOf(): String chars = "\uE001..."; ... if (chars.indexOf(myChar) >= 0) { // Do the work } This is not hugely different to what you're doing already, except that it requires less code. If n is the size of charArray, the first solution is O(log n) whereas the second one is O(n). A: You can use hash/map to check existance of the characer. This approach has better time of O(log n) or O(1) depending on hash/map inner structure. A: If you don't have access to Arrays, since you are working in JavaME, then you should try to: * *Or implement a sorted array and the binary search youself *Or just use a O(n) solution, wich is a good solution anyways. Your solution is O(n), along with the one stated by aix. You could try to use a Map, but it would depends on how much elements you are in your array. If you think there won't be more than 1000 elements in the array, just use a O(n) solution. But if you think you could have an unkown number of elements, a Map would be a reasoable choice, providing a better solution. A: You can use net.rim.device.api.util.Arrays.getIndex(char[] array, char element) A: It depends on what Java ME configuration / profile you are using. If you're on CDC then check for what parts of Java SE 1.3 Collections framework are supported (just find javadocs targeted for your device and look in java.util package). Another thing worth checking is whether your device has some blackberry-specific API extensions to work with collections. If you are limited to bare minimum of CLDC/MIDP then other solution than you mentioned would be to add chars to Vector and use Vector.contains(Object) A: If you don't want to implement it yourself you could use ArrayUtils in apache commons project: ArrayUtils apache-commons
{ "language": "en", "url": "https://stackoverflow.com/questions/7584245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: tfs 2010 best practice we have a very tricky situation which am sure can be avoided if dealt with properly. There were 5 different branches of a specific application in our TFS 2010. All the branches were merged into 1 branch and since the merging was done by a system administrator who wasn't part of the development team, we ended up cleaning the code (adding the missed changes from 3 separate places where ever they were conflicts) This amounted to almost 2 weeks of extra effort to get the code branch stabilised and tested before proceeding further. What should be the best practice to be followed to avoid such frustrations in future as we have multiple code branches for different development projects running on same applications. A: See the Visual Studio ALM Rangers Team Foundation Server 2010 Branching Guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: refresh page after 3 seconds using c# I want my code to refresh the page once its shown the success label for 3 seconds. How can i do this in c# code? i have this following: using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; using System.IO; public partial class CAPTCHA_Contact : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //ImageVerification if (!IsPostBack) { SetVerificationText(); } imCaptcha.ImageUrl = "captcha.ashx?d=" + DateTime.Now.Ticks; } public void SetVerificationText() { Random ran = new Random(); int no = ran.Next(); Session["Captcha"] = no.ToString(); } protected void CAPTCHAValidate(object source, ServerValidateEventArgs args) { if (Session["Captcha"] != null) { if (txtVerify.Text != Session["Captcha"].ToString()) { SetVerificationText(); args.IsValid = false; return; } } else { SetVerificationText(); args.IsValid = false; return; } } protected void btnSave_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } SetVerificationText(); //Save the content MailMessage mail = new MailMessage(); mail.From = new MailAddress(EmailTB.Text); mail.To.Add("name@company.co.uk"); mail.Bcc.Add("test@test.co.uk"); mail.Subject = "Web Quote"; mail.IsBodyHtml = true; mail.Body = "First Name: " + FNameTB.Text + "<br />"; mail.Body += "Email: " + EmailTB.Text + "<br />"; mail.Body += "Telephone: " + TelephoneTB.Text + "<br />"; mail.Body += "Query: " + QueryDD.Text + "<br />"; mail.Body += "Comments: " + CommentsTB.Text + "<br />"; SmtpClient smtp = new SmtpClient(); smtp.Host = "localhost"; smtp.Send(mail); sucessPH.Visible = true; } protected void Reset(object s, EventArgs e) { FNameTB.Text = ""; QueryDD.Text = ""; EmailTB.Text = ""; TelephoneTB.Text = ""; CommentsTB.Text = ""; txtVerify.Text = ""; } } So after sucessPH.Visible = true; i need to count 3 seconds and then refresh the page. This will then clear the form data and the user will also get 3 seconds to see the message to say the message was successfull. Any ideas? A: Since this is a client-side concern and not a server-side concern, you'll want to do this with JavaScript. Keep in mind that by the time the page is sent to the client all of the server-side code has completed and disposed. Trying to do this with server-side code will result in a lot of unnecessary complexity in this case. In JavaScript you can reload the page with a delay with something like this: setTimeout("window.location.reload()", 3000); A: Well, if you're using webforms, you could use an update panel, and then use the timer component, just like this guy've done Tutorial: How to refresh an UpdatePanel control at a timed interval A: Well.. you are in a web.. So your server can count 3, but you need the client to count 3 and then postback it to the server... If your server only counts, then the user will not view anything.. Just make your application ajax enable, and use a timer ;) This is the code for the page <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Timer ID="Timer1" runat="server" Interval="3000" ontick="Timer1_Tick"> </asp:Timer> </div> </form> </body> </html> and in the code behind you have this: protected void Timer1_Tick(object sender, EventArgs e) { //do your thing when reach this tick } This page will refresh exactly every 3 seconds. This is .net 4. A: Right after sucessPH.Visible = true; add following line: ClientScript.RegisterClientScriptBlock(this.GetType(), "refresh", "setTimeout('window.location.href=window.location.href', 3000);", true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I perform GET method in android? I want to get this data ---->"#1$Egypt$مصر@" from this link --> "http://184.173.7.132/mobile.aspx?action=4" I used this code but the response is NULL public HttpResponse doGet(String url) throws Exception { HttpResponse response = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); response = httpclient.execute(httpget); } catch (IOException e) { e.printStackTrace(); } return response; } A: Use this code it is worked for your url. add internet permission in manifest String page; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://184.173.7.132/mobile.aspx?action=4"); // httpGet.addHeader("Content-type","application/json"); ResponseHandler<String> resHandler = new BasicResponseHandler(); try { page = httpClient.execute(httpGet, resHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block } Log.e("response",page);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iphone Drawing gradient inside a polygon I want to draw a gradient inside a polygon using core graphics. I am able to draw a hexagon using the code below but i don't know how to fill this hexagon with a gradient color. Any help will be really appreciated. - (void)drawRect:(CGRect)rect { // Drawing code. CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0); CGContextSetLineWidth(context, 2.0); CGPoint center; center = CGPointMake(210.0, 90.0); CGContextMoveToPoint(context, center.x, center.y + 60.0); for(int i = 1; i < 6; ++i) { CGFloat x = 60.0 * sinf(i * 2.0 * M_PI / 6.0); CGFloat y = 60.0 * cosf(i * 2.0 * M_PI / 6.0); CGContextAddLineToPoint(context, center.x + x, center.y + y); } CGContextClosePath(context); CGContextDrawPath(context, kCGPathFillStroke); } A: Use following code for Gradient fill CGContextRef context = UIGraphicsGetCurrentContext(); CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB(); CGFloat colors[] = { 0.62890625, 0.859375, 10.9921875, 1.00, 0.65625, 0.8046875, 0.9453125, 1.00, }; CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4)); CGColorSpaceRelease(rgb); // now we can actually create the shape and fill it CGPoint start, end; CGContextSetRGBFillColor(context, 0, 0, 0.6, 0.1); CGContextFillEllipseInRect(context, CGRectMake(0.0, 0.0, 100.0, 100.0)); CGContextStrokeEllipseInRect(context, CGRectMake(0.0, 0.0, 100.0, 100.0)); // Gradient CGRect myrect = CGRectMake(0.0, 0.0, rect.size.width, rect.size.height); CGContextSaveGState(context); CGContextClipToRect(context, myrect); start = CGPointMake(myrect.origin.x, myrect.origin.y + myrect.size.height * 0.25); end = CGPointMake(myrect.origin.x, myrect.origin.y + myrect.size.height * 1.0); CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation); CGContextRestoreGState(context);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Solr schema and boosting by keywords/tags for item When users searches and clicks a result, we store this search keyword in the DB. What we get is a list of keywords for every item with the number of times item was clicked for that keyword. In solr schema I have multivalued field "keywords". How can I add that number of clicks for every keyword on every item and than boost so the most clicked items are on/near the top of results for that keyword ? I use dismax and for the moment the query for "apple" looks someting like this: q=apple qf=title^0.4 keywords:"apple"^0.5 bf=hits^0.4 rating^0.3 So as you can see I boost by "keywords" but the problem is that I don't know which item was most clicked for "apple". I've tried adding boost parameter to every keyword on initial index import. It didn't help and I'm out of ideas. A: How are you maintaining the clicked data ? How about also maintaining the cumulative clicked data as a single field with the document. You can easily use this field to boost the documents overall using the dismax boost functions. A large set of mathematical functions can be used @ http://wiki.apache.org/solr/FunctionQuery#What_is_a_Function.3F
{ "language": "en", "url": "https://stackoverflow.com/questions/7584267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python (OpenCV) Median filter trouble I need to do a (fast) median filter of some images from Python, and after some time on Google it seems like OpenCV is the way to go for speed (even in Python). I got OpenCV up and running, and filters like Erode and Dilate works fine: cv.Erode(cv_im,cv_im,None,6) cv.Dilate(cv_im,cv_im,None,6) The Median filter, however, does not seem to work: cv.Smooth(cv_im,cv_im,CV_MEDIAN) "NameError: global name 'CV_MEDIAN' is not defined" I can't seem to figure out what I'm doing wrong, according to the documentation http://opencv.willowgarage.com/documentation/python/image_filtering.html#smooth it looks like I do it the correct way. Any ideas? Many thanks in advance! A: Looks like you imported pyopencv as "cv". So you editting CV_MEDIAN to cv.CV_MEDIAN should help
{ "language": "en", "url": "https://stackoverflow.com/questions/7584268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DeepLink in Facebook Fanpage i'm looking for a solution to proceced deeplinks to a facebook fanpage like: http://www.facebook.com/myfanpage?sk=app_MYAPPID&parameter=2 I need to get the value of parameter in my Fanpage app. A: Use the app_data parameter in your link, and the value of this will be passed to your app in the signed_request which is sent on page load. Many developers use JSON encoded data as the value for app_data as they want to store multiple values This is documented here: https://developers.facebook.com/docs/appsonfacebook/pagetabs/#integrating A: I don't understand clearly but what you want is getting parameters from url in facebook is not possible in pagetabs i tried it many times but it won't work. The only way getting parameters from url in facebook is creating canvas app. Because canvas apps act like domain so you can use whole parameters and urls. If i missunderstood sorry for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is CodeIgniter suitable for large intranet applications that do not use MySQL? I don't really plan on using active record or any of the built in database constructs native to CodeIgniter for database access. I have Oracle, SQL Server, and others. I want to use PHP PDO (unless anyone thinks that's bad) because of the universal aspect of it. I mainly want CI because of some of the built in libraries and MVC. I also like that it is small and easy to work with. 2.x if it matters. I did see other questions but none exactly about databases. Thanks. edit: It's not that I don't think CI and PHP can take it with large websites. This is solely about using multiple databases of varying companies. I have mostly seen MySQL used with it. I know I can use other databases but again, I don't know if it is more trouble than worth or what. A: MySQL is the default just because of how widely-adopted it is, especially in the PHP world. Almost everyone has a *AMP stack to work on so it ends up being the main driver used in almost every example out there. If you're not planning on using the database class, then it really doesn't matter what type of database you are using, just don't load the class. You can still use routing, helpers, libraries, and other CI features. So yes, I do think it is suitable for your purposes. A: CodeIgniter was built with the idea of being the framework closest to native PHP that doesn't tell you what to do. The entire framework is modular and you are not required to use any single component. Yes, it is absolutely suited to what you are doing. You can plug and play whatever DB driver you want and CI will not complain one bit. I think CI is more suited for this role than any other of the 'big' frameworks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XML Schema regex for integer range, excluding 0 I'm developing an XML schema and I need to restrict an integer to being within a ranger of -20 to 20, but not 0. I was going to use minInclusive and maxInclusive for the -20 to 20. I tried to add the regex "="^(?!0).+", but that does not appear to be a valid XML regex. What value can I put in for xs:pattern that will prevent an integer from being 0? A: Have you tried enumerating the legal values. Workable since the range is quite small. A: Simple lack of escape character. The pattern value should have read "^(\?!0).+".
{ "language": "en", "url": "https://stackoverflow.com/questions/7584276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL distinct values across columns I have the following table: id lb rb ls rs ch bk ot 1 10000 10001 10001 10001 10001 10001 10000 2 0 10000 0 10001 0 10000 0 3 0 0 10000 10001 10000 0 0 4 0 0 0 10000 0 0 0 5 0 0 0 10000 0 0 0 I want to be able to get the total distinct values across all columns (excluding 0) so the result is as such: Code Qty 10000 8 10001 7 What's the easiest/best way to do this? Thanks, Stu A: You can do SELECT col1, COUNT(*) FROM ( SELECT lb AS col1 FROM table UNION ALL SELECT rb FROM table UNION ALL ... etc ) a WHERE col1 != 0 GROUP BY col1 Instead of WHERE col1 != 0 you can add WHERE field_name !=0 to each SELECT in UNION A: SELECT code AS Code , SUM(cnt) AS Qty FROM ( SELECT lb AS code , COUNT(*) AS cnt FROM TableX GROUP BY lb UNION ALL SELECT rb AS code , COUNT(*) AS cnt FROM TableX GROUP BY rb UNION ALL ... UNION ALL SELECT ot AS code , COUNT(*) AS cnt FROM TableX GROUP BY ot ) AS tmp GROUP BY code
{ "language": "en", "url": "https://stackoverflow.com/questions/7584280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Object reference error I have this piece of code:- What I want is that in button click i want put some value in user control. I get Object reference error. if (Page.FindControl("pr1") is Control) { Control previewControl = Page.FindControl("pr1"); Label titleLabelPreview = (Label)previewControl.FindControl("titleLabel"); titleLabelPreview.Text = emptxt.Text; However, if i used it through master page it can not intialized but if i use parent page it work properly. But here, one more problem persisted, suppose the scenario use a tab container where is 3 tab panel in first panel i used a button when i click that button i want to change the tab panel view means 2nd panel but without refresh the page. and one important thing i don't want to use update panel on tab container. I do not wish to use ajax or javascript. any insight on this. Also, would be really great if someone gives me a deep idea how to resolve object reference errors. I read a few blogs like:_ http://www.mikesdotnetting.com/Article/62/Object-reference-not-set-to-an-instance-of-an-object-and-INamingContainer http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.passwordrecovery.usernametemplate.aspx however, was not fully satisfied.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Composition/Delegation in C# Okay, I need to use some third party library and the resulting code is hard to unit test, because the classes don't implement interfaces (i.e. I can't isolate my code from the dependencies it has on theirs, which in turn relies on databases and who knows what else). My solution - wrap the third party classes in my own classes which have the same interface and contain an instance of the third party class. Easy enough, so far. Question: is there any way to automagically extract those interfaces from the existing (third party) classes? It seems like I am going to be writing a lot of boiler plate code if I do it manually. A: I don't know of a tool that does that exactly. But, the way I would do it is this. Take Reflector and reverse engineer the third party component. Take the code and "smash it down" to just method signatures. Then, with a small amount of tweaking, you have an interface. Not completely "no boilerplate", but it does remove a lot of the rote work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Not Null contraint on entire table I was wondering if there is any way to make a single Not Null constraint that could apply to all the attributes in my table. I know I could add one to each line, but I am just trying to learn to be more efficient. I tried searching online and I didn't find anything on this topic. Thanks! MORE INFO: I guess my question could be generalized to ask "Is there any way to define table-wide or database-wide constraints?". For this entire database, I need to the default value of every varchar to '' (the empty string) but right now I am doing that manually for every varchar. Again, I already did most of it, but it seems like there should be a way to avoid this repetition. A: No, there isn't any way to do this. You have to speciy this at the column level but this is something you only do once. Perhaps is a couple of keystrokes more or one click per column. No inefficiency there. A: From http://dev.mysql.com/doc/refman/5.1/en/create-table.html - the only place you can put a null/not null is on a column. column_definition: data_type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string'] [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}] [STORAGE {DISK|MEMORY|DEFAULT}] [reference_definition] There's really no reason to have a table constraint, IMO. The DDL specifies constrains on the data in each column, not the column definition itself. While one might want to put this in as syntactic sugar, it seems like there could be disadvantages - 1) to add a new column you might have to alter the table constraint 2) MySQL defaults to NULL and this might lead to confusion A: Have you think in triggers or stored procedures? It totally depends on your DBMS. But it also adds a over work in the DB. Forget about the CHECK clause because mySql ignores it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Perl: SSH Tail as File Handler I am creating a log parser that has the ability to "stream" a log as it is written. The log resides on a remote host, so I am creating a file handler using a combination of SSH and tail. The following works quite well, but I do have some questions regarding error handling. * *If the user doesn't enter the password for the SSH connection prior to the alarm delay expiring, the alarm will start triggering. This leads to the console being cleared so it is not clear that the password needs to be entered. *If i enter the wrong password, i still enable the alarm leading to screen clears, ect... Password: Password: Password: Permission denied (publickey,keyboard-interactive). *If i provide a log filename that doesn't exist, the code continues.... tail: cannot open `/path_to_log/mylog.logXXXX' for reading: No such file or directory tail: no files remaining So, my question is what is the best way add some additional error handling. Alternatively, can the File::Tail module be used in combination with SSH, telnet, rlogin, etc to provide the same functionality? Thanks! my $stopMsg = "Use CTRL+C to stop streaming at any time...\n"; my $SSH = sprintf "ssh %s@%s tail -f %s | ", $user, $host, $log; printf "Log: %s\n", $log; printf "Handle: %s\n", $SSH; my $errMsg = sprintf "Couldn't establish SSH connection to \"%s\":", $host; open my $pipe, $SSH or error( $errMsg ); my $loadTime = time; printf $stopMsg; setSignalHandler( 'INT', sub{ stopAlarm( TRUE ); } ); startAlarm( $delay, $interval, sub { system "clear"; $handler->( \@sysLogArr ); printf $stopMsg; } ); while ( alarmHandlerSet() ) { my $data = <$pipe>; next unless defined $data; mapSysLog( line => $data, arrRef => $logRef, varRef => \%sysLogVars, dbRef => $dbRef ); } clearSignalHandler( 'INT' ); sub error(@) { my $color = "BOLD"; $color = $CONFIG{errorPrinter} if ( $CONFIG{colorEnable} && defined $CONFIG{errorPrinter} ); color2PrinterRef( $color )->( "\nERROR: " ); printf "%s\n", shift; printf " %s\n", $_ foreach ( @_ ); printf "Called From: %s::%d\n", (caller)[1], (caller)[2]; printf "\n"; exit EXIT_FAILURE; } A: See the sftp_tail.pl sample included with Net::SFTP::Foreign.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aptana Studio 3 / Eclipse : strange different widths for tabs/spaces in PHP editor? Somehow in a PHP editor in Aptana Studio 3 I get very strange behaviour of spaces before indented lines. The spaces seem to change in width (!) after you type them. Even with a monospace font the text columns are not aligned. For example : Both lines in this example have 8 spaces before the text, but they are aligned differently ! What could cause this? I tried every setting in Aptana to fix this, but I can't solve the problem. A: Found the solution: I was using the Aptana Studio 2.x theme. Changed it to Eclipse theme and the editor works like it should... A: Here's the solution I found: Go to Preferences > Aptana Studio > Themes. In the element list, find "punctuation", then deselect "B"(bold). That should fix the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript - Flash Sound Recording I would like to capture sound from a browser and send it to a server. I decided to use red5 for the reasons listed on this interesting page that claims to do exactly what I need. It requires the following: * *A running red5 server *A flash object that can capture the microphone input *A JavaScript controller I tried to implement this example localy (I pretty much simply copied all the files). At page load from my server console I can see that the supplied flash object audioRecorder1.swf creates a connection. [INFO] [NioProcessor-1] org.red5.server.net.rtmp.codec.RTMPProtocolDecoder - Action connect [INFO] [NioProcessor-1] org.red5.server.net.rtmp.RTMPHandler - Connecting to: [WebScope@4799a84f Depth = 1, Path = '/default', Name = 'oflaDemo'] But when I hit any button (record/play/stop) of the controller, I'm having this javascript error from which I can't figure out the origin thisMovie("denRecorder").jsRecord is not a function denRecorder is the id of the flash object in the page (created with the swfobject.js library) <object width="1" height="1" type="application/x-shockwave-flash" id="denRecorder" name="denRecorder" data="/static/flash/audioRecorder.swf"> <param name="menu" value="false"> <param name="flashvars" value="myServer=rtmp://localhost/oflaDemo&amp;mySound=snd_88188160112&amp;myDuration=0"> </object> I have created a package that can be tested localy. Do you have any idea of what is my problem ? edit OS: Ubuntu, Browser: Chromium & Firefox A: I started a project (OSS) with someone which will help us for this question
{ "language": "en", "url": "https://stackoverflow.com/questions/7584302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Oracle PLSQL function throws PL/SQL: numeric or value error: character string buffer too small ,for returning large data I have the following PLSQL functions that returns following error when returning a large data. ORA-06502: PL/SQL: numeric or value error: character string buffer too small MODIFIED PLSQL FUNCTION CREATE OR REPLACE FUNCTION FRDUSER.FRD_TELECOP_DYN_REP_SELECT_OPT (p_select IN VARCHAR2) RETURN CLOB AS -- v_temp CLOB; v_out CLOB; TYPE RefCurTyp IS REF CURSOR; -- len BINARY_INTEGER; v_cursor RefCurTyp; c_key VARCHAR2 (1000); c_value VARCHAR2 (1000); separator VARCHAR2(3); BEGIN OPEN v_cursor FOR p_select; -- Fetch rows from result set one at a time: separator := ''; LOOP FETCH v_cursor INTO c_key,c_value; EXIT WHEN v_cursor%NOTFOUND; -- dbms_lob.createtemporary(v_out, TRUE); -- dbms_lob.open(v_out, dbms_lob.lob_readwrite); v_out := v_out || separator || c_key || ',' || c_value; -- dbms_lob.append(v_out, v_temp); separator := ':'; END LOOP; -- Close cursor: CLOSE v_cursor; RETURN (v_out); END; / I am executing the function as below, SELECT CASE WHEN OPTIONS_TYPE = 'S' THEN OPTIONS_VALUES WHEN OPTIONS_TYPE = 'D' THEN TO_CLOB(FRD_TELECOP_DYN_REP_SELECT_OPT (OPTIONS_VALUES)) END FROM FRD_REP_FW_REP_TEMPLATES A, FRD_REP_FW_TEMPLATES B WHERE A.REP_ID=1123 AND A.TEMP_ID=B.TEMP_ID ORDER BY A.REP_TEMP_ID ASC When i ran the above sql query it throw following error ORA-00932: inconsistent datatypes: expected CHAR got CLOB The parameter to the sql function(options_values) contains sql query. A: I suspect you're overcomplicating your logic a bit. You probably just need something like this (assuming that you actually need to dynamically pass the query in to the function) SQL> create table clob_test ( 2 key varchar2(100), 3 val varchar2(100) 4 ); Table created. SQL> insert into clob_test 2 select level, dbms_random.string( 'A', 100 ) 3 from dual 4 connect by level <= 10000; 10000 rows created. SQL> ed Wrote file afiedt.buf 1 create or replace function return_clob 2 return clob 3 as 4 v_out clob; 5 v_sql varchar2(1000) := 'select key, val from clob_test'; 6 v_key varchar2(100); 7 v_val varchar2(100); 8 v_rc sys_refcursor; 9 begin 10 open v_rc for v_sql; 11 loop 12 fetch v_rc into v_key, v_val; 13 exit when v_rc%notfound; 14 v_out := v_out || v_key || ', ' || v_val; 15 end loop; 16 return v_out; 17* end; SQL> / Function created. SQL> select return_clob from dual; RETURN_CLOB -------------------------------------------------------------------------------- 1, tzGWFXwKLgrRTGzTGbWMYMjVniIVMmCuGYGYydcrArHPRLExoFAJsZVhhPrRKyERExqRkbLGSebqX << more lob data removed>> A: Per Oracle: Decode: If expr and search are character data, then Oracle compares them using nonpadded comparison semantics. expr, search, and result can be any of the datatypes CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The string returned is of VARCHAR2 datatype and is in the same character set as the first result parameter. So you're trying to force result of decode to be a clob, which it won't be. Have you tried a case statement instead of decode? (I haven't but worth a shot ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: User control resize Possible Duplicate: “ResizeEnd” equivalent for usercontrols I feel stupid, but I can't find a solution to a problem that I think it's easy. I have a user control that (basically) shows an image drawing it during onPaint stage: protected override void OnPaint(PaintEventArgs e) { if (img != null) e.Graphics.DrawImage(img, ...); } When user control is resized, it must perform many actions and one is (given a particular condition) resize image to fit width or height, etc... Image showed can be "heavy", so when user start resizing and moves mouse, the result is a sort of slow movement that's not good for end user. So I'm wondering if there are windows messages reporting me that the resize operation is starting or completed: if so I can stop redrawing when resize starts and repaint image when resize ends. Thanks to everybody EDITED: I tried this: protected override void WndProc(ref Message m) { const int WM_ENTERSIZEMOVE = 0x0231; const int WM_EXITSIZEMOVE = 0x0232; switch (m.Msg) { case WM_ENTERSIZEMOVE: resizing = true; break; case WM_EXITSIZEMOVE: resizing = false; break; } } but those messages are never called :( A: You might be interested by the Form.ResizeBegin and Form.ResizeEnd events. If you're using WPF, this thread on MSDN might interest you. WPF requires hackery to know when the resize begins/ends EDIT Didn't noticed it was an UserControl ! This question seems to address your problem: "ResizeEnd" equivalent for usercontrols A: In the Load event of your UserControl, hook event handlers to the control's form's events. Apologies, I have a VB project open, I'll convert it in the answer when I get a moment. Private Sub UserControl1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load AddHandler Me.FindForm.ResizeBegin, AddressOf MyFormsResizeBegin AddHandler Me.FindForm.ResizeEnd, AddressOf MyFormsResizeEnd End Sub Private Sub MyFormsResizeBegin(sender As Object, e As EventArgs) 'tell your control to wait. End Sub Private Sub MyFormsResizeEnd(sender As Object, e As EventArgs) 'say everything is ok to continue End Sub A: You really want to do that (windows messages)? :D First, you cant do that like overriding PreProcessMessage or WndProc because I'm guessing the containing form will trap the resizing start/end message (or any other messages) so your control will not get any. The way to do that is to implement IMessageFilter interface on your control. Then you will get this method in your control in which you can switch through the received message m: public bool PreFilterMessage(ref Message m) Then at the control constructor add: Application.AddMessageFilter(this); and there you go, now Application thread is calling PreFilterMessage method and passing it the received message. Another idea: If you let the users change the controls size with their mouse, you can trap MouseDown and set bool MouseIsDown flag Then in OnResize you can check if(MouseIsDown && Resizing == false) { Resizing = true; //Start Resizing only once } And on MouseUp: if(Resizing == true && MouseIsDown == true) { Resizing = MouseIsDown = false; //End the resizing once } A: I post an answer after a long investigation. First of all I want to thank everybody for your contribution, because your suggestions led me to the right way. Thanks to @Hans Passant too, because his solution on this post is an important piece. THE PROBLEM: * *assume we have a usercontrol named innCnt (inner control) contained in another usercontrol named outCnt (outer control), which in turn should be placed in a form we don't develop (so we can't edit its source) *assume we have to catch the EndResize event in innCnt CONTRIBUTES: * *Using PreProcessMessage or overriding WndProc (thanks to @Cipi): I tried these solutions, but I don't receive WM_ENTERSIZEMOVE and WM_EXITSIZEMOVE messages from Windows *Trap MouseDown and OnResize events (thanks to @Cipi): It could be ok, but that logic should be moved on outCnt because innCnt could not receive MouseDown if user is resizing out control or form. Anyway I don't like too much this solution *In the Load event of innCnt, hook event handlers to the control's form's events (thanks to @hometoast and @pikzen): I tried this solution (and the one provided by @Hans here) but this doesn't work because when innCnt is loaded, even in if not in DesignMode, his parent is a part of outCnt, whose parent is null because not ready set!! SOLUTION: Basicly I had to move @Hans logic inside outCnt but not in Load event, because even here parent is still null! public class OuterControl { protected override void OnParentChanged(EventArgs e) { if (!this.DesignMode) { Form form = this.FindForm(); if (form != null) { form.ResizeBegin += (s, ea) =>innerCnt.Resizing = true; form.ResizeEnd += (s, ea) => innerCnt.Resizing = false; } } base.OnParentChanged(e); } } public class InnerControl { private bool resizing = false; public bool Resizing { get { return resizing; }; set { resizing = value; if (!resizing) { // Resizing is just finished: // let's do what we need } } } protected override void OnResize(EventArgs e) { if (Resizing) { base.OnResize(e); return; } else { // Perform resizing actions } } } KNOWN PROBLEMS: I'm quite sure that if outCnt is placed inside another usercontrol, solution provided won't work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7584307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to remove handler at control I have a control which has in a constructor _myWebService.ForwardMessageCompleted += new EventHandler(OnForwardMessageCompleted); private void OnForwardMessageCompleted(object sender, AsyncCompletedEventArgs e) { activity.IsActive = false; if (e.Error == null) { RadWindow.Alert("The message has been forwarded"); } } Control has list of messages, and user can forward its to other users. The problem is, that user opens this control many times, and each time which it is created handler is being added to _myWebService.ForwardMessageCompleted How can I remove handling to this event? A: Because you are connecting an external event handler in the constructor of a control, that event listener is also acting as a pointer to the control (so it is not being destroyed and the code gets called for every instance of the control). You want to catch the Unloaded event of your control and add the following to that handler (to disconnect the event listener): _myWebService.ForwardMessageCompleted -= OnForwardMessageCompleted;
{ "language": "en", "url": "https://stackoverflow.com/questions/7584308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firefox Sync issues I want to read the bookmarks and history from Firefox Sync accounts in one of my iOS Apps and I got it working for all "new" accounts (those with an email as login name), but it fails for old accounts (those where the user could still create their own login name). And I'm not sure what's the problem. I had many difficulties to find all the relevant details in the Firefox Sync API documentation, I often had to search elsewhere for the information, So I guess I'm still missing some important information. What I do is the following: I have the login name, password and sync-key. The first step is to get the "weave node", the server where the users data is stored. We get this information from https://auth.services.mozilla.com/user/1.0/[loginname]/node/weave" and using the loginname and password for basic authentication for this request. The first problem here was that the "[loginname]" was never accepted. I found out that when the loginname is an email address, it must be SHA1 and base32 encoded. I didn't find this information in the API documentation, I did find it in a blog elsewhere. For older accounts where the login name is not an email address, it seems that it must not be encoded via SHA1 and base32. So my first question is, when exactly is the SHA1-base32 encoding necessary? Only when the login name is an email address, or also when the old-style login name contains certain characters (in case one could use any special characters in the first place)? This first step works well. I do get the "weave node" for old and new accounts just fine, so loginname and password is accepted and seems to be encoded correctly (at least in my test cases with SHA1/base32 for new accounts and "raw" data for old accounts). The next step would be to retrieve the keys for decrypting the bookmarks data. I get this data from https://[Weave node]/1.1/[login name]/storage/crypto/keys again with basic authentication. I do get the JSON response just fine which includes the "ciphertext", "iv" and "hmac" from which I should be able to create the AES keys to decrypt the data. But decrypting the keys does only work for new accounts (login name is an email address) and fails for old accounts. And this is my second question: What do I need to do exactly to reliably be able to get the keys for all accounts? AFAIK what I supposed to do is to use the sync-key and the login name and create an encryption key which can be used to decrypt the ciphertext from above. So this would be in pseudo code look like this: encryptionkey = HMAC-SHA256(sync_key, "Sync-AES_256_CBC-HMAC256" + loginname + "\x01") Where the sync-key is the base32 decoded value from the string that was entered by the user and the loginname is either the raw login name (old accounts) or the SHA1/Base32 encoded string from the loginname (new accounts). And to decode the "ciphertext" I'm doing this (Objective C): NSString *decryptedPayload = nil; NSData *encryptionkey = ... // See above, just encapsuled as NSData object. NSData *cipherdata = [cyphertext base64DecodedData]; NSData *ivdata = [iv base64DecodedData]; size_t bufferSize = ([cipherdata length] + kCCBlockSizeAES128); void *buffer = calloc(bufferSize, sizeof(uint8_t)); size_t numBytesDecrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, [encryptionkey bytes], [encryptionkey length], [ivdata bytes], [cipherdata bytes], [cipherdata length], buffer, bufferSize, &numBytesDecrypted); if (cryptStatus == kCCSuccess) { NSData *decryptedData = [NSData dataWithBytes:buffer length:numBytesDecrypted]; decryptedPayload = [NSString stringWithData:resData]; } free(buffer); Now "decryptedPayload" contains the decrypted information about the AES keys. This works fine for new accounts, but decrypting fails for old accounts (CCCrypt returns kCCDecodeError). What do I miss? What am I doing wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7584310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Event on data changing in bindingsource I have DataGridView and BindingSource with DataSet. When I filled dataset using datatable adapter I would like some event triggered when each row has added to dataset. A: The RowsAdded event is fired everytime a row is added to the DataGridView. Check http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded%28v=vs.80%29.aspx Edit: Sorry, I misunderstood your question. I thought you meant you wanted an event fired when rows where added to the dgv.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NHibernate - LAZY LOADING PROBLEM -Initializing[]-Could not initialize proxy - no Session."} Hi I use Fluent NHibernate and I am little confusing with Lazy Loading. * *I queried object in database *modified object properties *update database with this object Here is code: public class Credentials { public virtual int Id { get; set; } public virtual string Nick { get; set; } public virtual string Password { get; set; } } public class CredentialsMap : ClassMap<Credentials> { public CredentialsMap() { Id(x => x.Id); Map(x => x.Nick).Column("NICK"); Map(x => x.Password).Column("PASSWORD"); Table("R_CREDENTAILS"); } } public class Status { public virtual int Id { get; set; } public virtual string Msg { get; set; } public virtual DateTime AddTime { get; set; } } public class StatusMap : ClassMap<Status> { public StatusMap() { Id(x => x.Id); Map(x => x.Msg).Column("MESSAGE"); Map(x => x.AddTime).Column("ADD_TIME"); Table("R_STATUS"); } } public class Account { public virtual int Id { get; set; } public virtual string SelfNick { get; set; } public virtual Credentials Credentials { get; set; } public virtual Status Status { get; set; } } public class AccountMap : ClassMap<Account> { public AccountMap() { Id(x => x.Id); Map(x => x.SelfNick).Column("SELF_NICK"); References(x => x.Credentials) .Column("CREDENTIALS_ID") .ForeignKey(); References(x => x.Status) .Column("STATUS_ID") .ForeignKey(); Table("R_ACCOUNTS"); } } NHibernate configuration class: public class NHiberanteHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) InitializeSessionFactory(); return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString( @"Server=TEST\SQLEXPRESS;Database=SimpleNHibernate;Trusted_Connection=True;"). ShowSql() ) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Account>().Conventions.Add( DefaultCascade.All())) .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true)) .BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } Here is usage: public class LoginDbHelper { public static Account GetAccount(string nick) { using (var session = NHiberanteHelper.OpenSession()) { var account = (session.QueryOver<Account>() .JoinQueryOver<Credentials>(a => a.Credentials) .Where(c => c.Nick == nick)); if (account != null) return account.SingleOrDefault(); return null; } } public static void SaveOrUpdateAccount(Account account) { using (var session = NHiberanteHelper.OpenSession()) { using (var trans = session.BeginTransaction()) { session.SaveOrUpdate(account); trans.Commit(); } } } } Problem code: var actualAccount = LoginDbHelper.GetAccount(nick); //modify actualAccount.Status.Msg = "New status 2"; actualAccount.Status.AddTime = DateTime.Now; LoginDbHelper.SaveOrUpdateAccount(account); I get this error: {"Initializing[NHibernateSample1.Status#1]-Could not initialize proxy - no Session."} StackTrace: at NHibernate.Proxy.AbstractLazyInitializer.Initialize() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Proxy\AbstractLazyInitializer.cs:line 113 at NHibernate.Proxy.AbstractLazyInitializer.GetImplementation() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Proxy\AbstractLazyInitializer.cs:line 191 at NHibernate.ByteCode.Castle.LazyInitializer.Intercept(IInvocation invocation) in d:\CSharp\NH\NH\nhibernate\src\NHibernate.ByteCode.Castle\LazyInitializer.cs:line 61 at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.StatusProxy.set_Msg(String value) at NHibernateSample1.Program.Main(String[] args) in E:\C# PROJECTS\Samples\SimpleNHibernateClient\NHibernateSample1\Program.cs:line 215 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() I google it and I think It cause by Lazy Loading because in method GetAccount I close SESSION. It is my first attempt with NHibernate so HOW CAN SOLVE THIS PROBLEM CORRECTLY? It is possible disable LAZY LOADING if YES how to do it? A: I find the easiest way to turn off lazy loading is to add a DefaultLazy convention, i.e.: .Conventions.Add( DefaultCascade.All(), DefaultLazy.Never() ) Note that turning lazy loading on (DefaultLazy.Always()) can really increase performance, depending on your application. The downside is, you always have to have a session open before you can lazy load the rest of the data in an entity. Session management to support lazy loading is one of the big pain points with NHibernate, in my experience. A: You are correct. Because the NHibernate Session is closed in your GetAccount method (it is only open in the scope of the using statement), you cannot load additional objects outside of this method. There are 2 potential fixes: * *Create the session at the operation level (i.e. in the method containing the problem code), then use this session in the get & save methods. You can use the session by passing it in as a parameter to the methods. *Change the object to not use lazy loading. You can do this by adding .Not.LazyLoad() to the Status object in your fluent mapping. A: You open and close session in LoginDbHelper.GetAccount(...) method. Try to create and open session outside of method and pass it as method param, for example: // method public static Account GetAccount(string nick, ISession session) { var account = (session.QueryOver<Account>().JoinQueryOver<Credentials>(a => a.Credentials).Where(c => c.Nick == nick)); if (account != null) return account.SingleOrDefault(); return null; } // usage var actualAccount = LoginDbHelper.GetAccount(nick); actualAccount.Status.AddTime = DateTime.Now; using (var session = NHiberanteHelper.OpenSession()) LoginDbHelper.SaveOrUpdateAccount(account, session); A: As a workaround you can replace this code: if (account != null) return account.SingleOrDefault(); With this code: if (account != null) { var returnValue = account.SingleOrDefault(); if (returnValue != null) { returnValue.Status.Msg = returnValue.Status.Msg;//Cause to load the lazy object now } return returnValue; } A: This can also happen if your session is perfectly open but you have called Session.Clear(). Don't do that. A: If you are using this in combination with ASP.Net MVC or ASPCORE, the issue might be because the Json serializer is trying to retrieve the data from an IEnumerable that you are getting via your session. Because the serializer executes after you exit your action method and your controller is disposed of (along with the NH session), it cannot access the lazy-loaded navigation properties. The simple solution is to add .ToList() or .ToArray() to your LINQ query within the action method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Better and a Faster way to read a string from a URL I am using this code to read content from a given URL. Is there and faster and better way to do it? private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } } A: Use StringBuilder instead of StringBuffer A: Is this an HTTP URL? If yes, then you * *must look at the Content-Type header and ensure that you're applying a correct encoding to the stream. As it is, you're applying the default encoding of your particular JVM installation, which may not correspond to what the server is sending *should look at the Content-Length header to pre-size your buffer. Other than those two changes, there's not much opportunity to speed up bytes across the network. Edit: you could also use Jakarta Commmons IOUtils.toString() to read the stream. This will reduce the amount of code that you have to write (and may be presumed fully debugged). However, it will have to resize buffers along the way. A: Well there are libs / source available online that will do this for you: http://json.org/java/ A: You can also use "BufferedReader.readLine()"
{ "language": "en", "url": "https://stackoverflow.com/questions/7584316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with slow updating of html 5 canvas after mousemove / mouseclick event I have recently been experimenting for the first time with html 5 and specifically the canvas object. I seem to be having some issue with mouse events. The program is a grid of faces with different coloured backgrounds randomly changed. There is a cloud shape on top that I am using as a clipping region to be able to see only the parts of the grid under the cloud. (Think oddly shaped torch beam) The issue is that I am trying to move the cloud region with the mouse and it does not update smoothly with either mousemove or mouseclick events. Seems to take a frame or two to catch up while the cycling colours appear to carry on. I have tried: * *Removing the random colours for speedup. *Using only a simple shape for clipping. *Setting the setInterval function to update every 1ms Can be seen running here - http://jsfiddle.net/mXrNk/14/ Any help would be appreciated. Probably missing something obvious. <script> const FPS = 60; var myimg = new Image(); window.addEventListener('click', clicked, true); var mouseX = 170; var mouseY = 80; window.onload = init; function init() { canvas = document.getElementById('myCanvas'); context = canvas.getContext('2d'); myimg.src = "smile.png"; setInterval(draw, 1000/FPS); } function draw() { context.clearRect(0,0,canvas.width,canvas.height); // draw cloud context.beginPath(); // begin custom shape context.moveTo(mouseX, mouseY); context.bezierCurveTo(mouseX-40, mouseY+20, mouseX-40, mouseY+70, mouseX+60, mouseY+70); context.bezierCurveTo(mouseX+80, mouseY+100, mouseX+150, mouseY+100, mouseX+170, mouseY+70); context.bezierCurveTo(mouseX+250, mouseY+70, mouseX+250, mouseY+40, mouseX+220, mouseY+20); context.bezierCurveTo(mouseX+260, mouseY-40, mouseX+200, mouseY-50, mouseX+170, mouseY-30); context.bezierCurveTo(mouseX+150, mouseY-75, mouseX+80, mouseY-60, mouseX+80, mouseY-30); context.bezierCurveTo(mouseX+30, mouseY-75, mouseX-20, mouseY-60, mouseX, mouseY); context.closePath(); // complete custom shape context.lineWidth = 5; context.strokeStyle = "#0000ff"; context.stroke(); context.save(); context.clip(); for (i = 0; i<7; i++) { for (j = 0; j < 13; j++) { context.strokeRect(j*myimg.width, i*myimg.height, myimg.width, myimg.height); context.fillStyle = rndColor(); context.fillRect(j*myimg.width, i*myimg.height, myimg.width, myimg.height); context.drawImage(myimg, j*myimg.width, i*myimg.height); context.fillStyle = "black"; context.font = "italic 10pt Arial "; context.fillText((i*13)+j, j*myimg.width+5,i*myimg.width+15); } } context.restore(); } function rndColor() { return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6); } function clicked(e) { mouseX = e.pageX; mouseY = e.pageY; } </script> A: Live Demo I used setTimeout rather than setInterval. When using an interval if it tries to run the function before its finished the events will build up and still continue to try and run while the calls are still building up. A timeout however will only call the function once, then you can just set another timeout at the bottom of the function to call itself again. Doing it that way ensures the function has completed, and doesn't cause a buildup of calls waiting to be processed. Also take a look at this article, https://simonsarris.com/increasing-performance-by-caching-paths-on-canvas/ Its about caching your paths. Its actually by Simon Sarris who I bet will pop in and see this question as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sorting the EdgeList in boost::graph I would like to to sort the edge List of boost::graph defined as followed: struct Vertex{ int index; }; struct Edge{ double weight; }; boost::adjacency_list<boost::listS, boost::listS, boost::undirectedS, Vertex, Edge> Graph; After adding the vertices and edges, how to I sort the edge list. Getting the edge with the highest weight first? I know one can use std::sort(edgeIt_begin,edgeIt_end,compare); for vectors, but it doesn't work for std::list. A: You could write your own EdgeList or OutEdgeList class which sorts the Elements automatically. I give an example because it's imho not that obvious how to do that. #include <iostream> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> using namespace boost; template<class T> struct Sorted_list { std::list<T> v; public: typedef T value_type; typedef typename std::list<T>::size_type size_type; typedef typename std::list<T>::iterator iterator; iterator insert(const T& x) { Sorted_list<T>::iterator i = v.begin(); while(i != v.end() && x > *i) { i++; } return v.insert(i, x); } iterator begin() { return v.begin(); } iterator end() { return v.end(); } size_type size() const { return v.size(); } }; struct SlistS {}; namespace boost { template <class ValueType> struct container_gen<SlistS, ValueType> { typedef Sorted_list<ValueType> type; }; struct sorted_list_tag {}; template<class T> sorted_list_tag container_category(Sorted_list<T>&) { return sorted_list_tag(); } template<class T> std::pair<typename Sorted_list<T>::iterator, bool> push_dispatch(Sorted_list<T>& v, const T& x, sorted_list_tag) { return std::make_pair(v.insert(x), true); } template <> struct parallel_edge_traits<SlistS> { typedef allow_parallel_edge_tag type; }; } int main() { typedef adjacency_list<SlistS> Graph; Graph g(10); add_edge(1, 2, g); add_edge(1, 5, g); add_edge(1, 3, g); add_edge(1, 7, g); add_edge(1, 1, g); graph_traits<Graph>::edge_iterator i, end; for (tie(i, end) = edges(g); i != end; ++i) { std::cout << source(*i, g) << " -> " << target(*i, g) << std::endl; } return 0; } Output: 1 -> 1 1 -> 2 1 -> 3 1 -> 5 1 -> 7 A: Sorting the edges is not idiomatic boost::graph. Look at the BGL implementation of Kruskal's algorithm for spanning trees. The algorithm needs to look at each edge in increasing order of weight. std::priority_queue<Edge, std::vector<Edge>, weight_greater> Q(wl); /*push all edge into Q*/ typename graph_traits<Graph>::edge_iterator ei, eiend; for (boost::tie(ei, eiend) = edges(G); ei != eiend; ++ei) Q.push(*ei); It uses a separate data structure to sort the edges and later iterates through the edges in that order. In your case, you want the highest weighted edges first, so you would look change the comparator operator. A: I don't know about any interactions with the Boost Graph representation, but IIRC you can use std::list::sort(Cmp) std::list<int> l = { 1, 3, -1, 9, 2 }; l.sort(); A: Previous answer, though very useful, manages bgl tags in a bit incorrect manner, that results in redundant push_dispatch definition and may lead to build problems if other *_dispatch functions being called (in case of erase operations, e.g.). Second confusing circumstance is that per-node edge list is substituted in adj_list template, but the unaffected whole-edge list is printed. There are some code that presumably corrects these flaws: // ... template<class T> struct Sorted_vector : public std::vector<T> { public: iterator insert(const T& x) { iterator where = std::upper_bound(begin(), end(), x, std::less<T>()); return std::vector<T>::insert(where, x); } }; struct vecSS{}; namespace boost{ template <class ValueType> struct container_gen<vecSS, ValueType> { typedef Sorted_vector<ValueType> type; }; template <> struct parallel_edge_traits<vecSS> { typedef allow_parallel_edge_tag type; }; template<class T> graph_detail::vector_tag container_category(const Sorted_vector<T>&) { return graph_detail::vector_tag(); } template <class T> graph_detail::unstable_tag iterator_stability(const Sorted_vector<T>&) { return graph_detail::unstable_tag(); } } typedef adjacency_list<vecSS, ...> Graph; // .... graph_traits<Graph>::vertex_iterator ii, ee; for(boost::tie(ii,ee) = vertices(g);ii!=ee;++ii){ std::cout << *ii << std::endl; graph_traits<Graph>::adjacency_iterator jj, ff; for(boost::tie(jj,ff)=adjacent_vertices(*ii, g);jj != ff; ++jj){ std::cout << "\t -> " << *jj<<std::endl; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Improve this insert class function php I hate to type the INSERT query, you always miss out with some stuff, and get syntax error. Therefor, I want to create my own function, to let me do this. This is what I got so far: $data['test'] = array('username' => 'john', 'password' => 'hello', 'userlevel' => '__d'); $table = 'users'; $numItems = count($data['test']); $i = 0; $sql = "INSERT INTO " . $table . "(". implode(", ", array_keys($data['test'])) .")"; $sql .= " VALUES ("; foreach ($data['test'] as $value) { if ($i+1 == $numItems and $value == '__d') { $sql .= "" . 'NOW()' . ")"; } else if ($i+1 == $numItems) { $sql .= "'" . $value . "')"; } else if ($value == '__d') { $sql .= "" . 'NOW()' . ", "; } else { $sql .= "'" . $value . "', "; } $i++; } echo $sql; Umm, yeah. Any tips on how I can improve this code? A: sprintf can makes things a lot more readable $columns = array('username'=>'john', 'password'=>'hello', 'userlevel'=>1, 'date'=>$date); $table = 'users'; $sql = sprintf( "insert into %s(%s) values(%s)", $table, implode( ',', array_keys( $columns ) ), implode( ',', array_map( function($v){ return ':'.$v; }, array_keys( $columns ) ) ) ); $stmnt = $pdo->prepare( $sql ); foreach( $columns as $column => $value ) { $stmnt->bindValue( ':'.$column, $value ); } $stmnt->execute(); A: <?php //test data $columns = array( 'username'=>'john', 'password'=>'hello', 'userlevel'=>1, 'date'=>'__d' ); $table = 'users'; // replace keys and values with SQL delimeters foreach($columns as $k=>$v) { unset($columns[$k]); if ($v != '__d' && !is_int($v)) $v = "'$v'"; if ($v == '__d') $v = 'NOW()'; $columns["`$k`"] = $v; } // create the query $sql = sprintf('INSERT INTO %s (%s) VALUES (%s)', $table, implode(",", array_keys($columns)), implode(",", $columns) ); echo $sql; ?> Output: INSERT INTO users (`username`,`password`,`userlevel`,`date`) VALUES ('john','hello',1,NOW()) A: $columns = array('username'=>'john', 'password'=>'hello', 'userlevel'=>1, 'date'=>$date); $table = 'users'; //function here $sql = "INSERT INTO " . $table . "(". implode(",", array_keys($columns)) .") VALUES ('". implode(",", $columns) ."')"; mysql_query($sql);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MATLAB/Octave: cut a lot of circles from a image I have an matrix (image) and information about interesting part within circles (center corrdinates and radii given). I want to cut for all the circles the parts of the matrix in order to do some more calculations for each circle. Or at least I want to have a bitmask with all the circle. I use Octave (but could also use MATLAB but it would be difficult because of licence iusses) and have the following script with some hints from stackoverflow. I have information of 20 circles and it takes about 0.7 s on my Core i5 using Octave: % image dim_x = 1000; dim_y = 1000; A=rand(dim_x,dim_y); % center positions and ... c = [222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112]; %... radii of the circles r = [10 33 55 2 22 10 33 55 2 22 10 33 55 2 22 10 33 55 2 22]; tic; for i=1:size(c,1) % create a bitmask ... mask = bsxfun(@plus, ((1:dim_y) - c(i,1)).^2, (transpose(1:dim_x) - c(i,2)).^2) < r(i)^2; % ... cut the circles out of the image B=A.*mask; end; toc; Do you know a more performant solution since I want to have about 600 circles. Thanks in advance A: Try mask = bsxfun(@lt, ((1:dim_y) - c(i,1)).^2, r(i)^2 - ((1:dim_x).' - c(i,2)).^2); According to my MATLAB profiler, this is about 4 times faster than your version. Also, the B = A.*mask line takes about the same amount of time as the original mask = ... line. Not sure there's much you can do about that. A: There's several things you can do to make your code more efficient, though some of them depend on exactly what you want in the end, and on what assumptions you can make about the circles (e.g. can they overlap? Are there many similar radii?). Below is a solution that assumes that there is very little repetition among radii, and center coordinates are always integer pixel values. %# image dim_x = 1000; dim_y = 1000; A=rand(dim_x,dim_y); %# center positions and ... c = [222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112]; %#... radii of the circles r = [10 33 55 2 22 10 33 55 2 22 10 33 55 2 22 10 33 55 2 22]; %# find the largest circle... rMax = max(r); %#... and create a distance array distFromCenterSquared = bsxfun(@plus,(-rMax:rMax).^2,transpose(-rMax:rMax).^2); %# now we can loop over the radii to create the logical mask for all circles mask = false(dim_x,dim_y); %# initialize inside the loop if you want one circle at a time for i=1:length(r) %# create logical mini-circle mask miniMask = distFromCenterSquared(rMax-r(i)+1:end-(rMax-r(i)),rMax-r(i)+1:end-(rMax-r(i)))... < r(i)^2; %# add to the mask. The ranges need to be fixed, obviously, if %# circles can be only partially inside the image %# also, the "or" is only necessary if you're adding to %# a mask, instead of recreating it each iteration mask(c(i,1)-r(i):c(i,1)+r(i),c(i,2)-r(i):c(i,2)+r(i)) = ... mask(c(i,1)-r(i):c(i,1)+r(i),c(i,2)-r(i):c(i,2)+r(i)) | ... miniMask; end By the way: If you have non-overlapping circles, you can use bwlabel after the loop (or use find and sub2ind to write i into the individual circles), so that you can process all circles in one go using accumarray. A: You may want to look into Matlab's strel (not sure about Octave availability, in Matlab it is part of the image processing toolbox). radius = 10; center = [320 240]; nn = 0; se = strel('disk', radius, nn); px = se.getneighbors; px = px + repmat(center, [length(px) 1]); The nn parameter effects performance. Making it 4, 6, or 8 will improve performance at the cost of your mask not being precisely a circle. You can also squeeze some performance out of it by rewriting the repmat bit using a bsxfun. A: I am going to suggest using POLY2MASK function from the MATLAB Image Processing Toolbox (also available in the Image package for Octave). Check the "algorithm" section to see how it handles the discrete pixels. Here is an example to test performance: %# image dim_x = 1000; dim_y = 1000; A = rand(dim_x,dim_y); %# center positions and radii of the circles c = [222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112; 222 111; 878 112; 81 718; 89 112]; r = [10 33 55 2 22 10 33 55 2 22 10 33 55 2 22 10 33 55 2 22]; %# lets make them 600 circles c = repmat(c,30,1); r = repmat(r,1,30); %# zero-centered unit circle t = linspace(0,2*pi,50); ct = cos(t); st = sin(t); %# compute binary mask for each circle tic for i=1:numel(r) %# scale and shift scale circle, and use to get mask BW = poly2mask(r(i).*ct + c(i,1), r(i).*st + c(i,2), dim_x, dim_y); %# use the mask ... end toc On my laptop, this finishes in: Elapsed time is 4.864494 seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Permission denied for SplFileObject I'm running php 5.3.8, on xampp (the newest version, 1.7.7 I believe), on Windows7 64bit. When I try to construct a SplFileObject giving it a directory path I get following message (both in read, or write mode): failed to open stream: Permission denied The folder exists, and I set proper rights (remember I'm on the Windows, not Linux). Can it be a problem with xampp - for example windows don't allow apache process to write anywhere on disk?
{ "language": "en", "url": "https://stackoverflow.com/questions/7584331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SIGPIPE when echoing variable inside bash script I have a cronjob running on a debian box. At certain points through the script, I set variables via HOSTNAME=$( hostname -s | tr A-Z a-z ) then later, I log that value to syslog (so I can see that everything is running properly) function log { # just echo it echo -n `date -u "+%s"` echo -n " " echo $1 /usr/bin/logger -t $0 -- $1 } log "Hostname: ${HOSTNAME}" However, on this box, I receive a SIGPIPE. This happens many times throughout the script. I've trapped the SIGPIPE to confirm that this is the case, but would like to actually fix the problem instead. Can someone tell me what might be causing the SIGPIPE, and how to fix it? I've tried creating a smaller test-script, but that script doesn't react the same way. A: My guess: within the cron environment, the PATH is limited, which means the shell might not be able to find hostname and/or tr. First, find out where hostname and tr are located and use absolute path instead, for example: HOSTNAME=$( /bin/hostname -s | /usr/bin/tr A-Z a-z )
{ "language": "en", "url": "https://stackoverflow.com/questions/7584332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you sort and throw all the `nil` results in the back? I would like to start sorting all my results by a new field. Unfortunately, a lot of my older fields have a nil for a timestamp. How can I perform this method and put all the nils in the back? .sort{|a,b| b.offering_referral_timestamp <=> a.offering_referral_timestamp} Thanks A: a <=> b returns -1 if a < b returns 0 if a == b returns 1 if a > b so I think this should work (if you want all nil at the end, they should be bigger than other elements): .sort{|a,b| a.offering_referral_timestamp.nil? ? 1 : (b.offering_referral_timestamp.nil? ? -1 : a.offering_referral_timestamp <=> b.offering_referral_timestamp)}
{ "language": "en", "url": "https://stackoverflow.com/questions/7584335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }