text
stringlengths
8
267k
meta
dict
Q: android:capitalize not working I have a TextView. I'm trying to capitalize the first letter in every word. Here's the TextView: <TextView android:text="TextView" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentRight="true" android:textSize="30dip" android:textStyle="bold" android:layout_marginRight="5dip" android:ellipsize="end" android:capitalize="words"> </TextView> Here's how I'm adding the text: TextView titleView = (TextView) findViewById(R.id.textView1); titleView.setText( section.replace("_", " ") ); Can I not add text dynamically and expect it to capitalize the words? Is another trait interfering with android:capitalize? Is android:capitalize broken? Thanks for your replies. A: android:capitalize is now deprecated. Instead of using android:capitalize="words", you should consider using android:inputType="textCapWords". Depending on your needs, you can also use multiple values, such as android:inputType="textCapWords|textPersonName". A: If you're targeting API Level 14 and above, you should use android:textAllCaps="true" Otherwise, you'll have to implement this behavior yourself. A: capitalize is basically just a KeyListener that you can set in XML, so it only applies to text input by the user. As the documentation states (emphasis mine): If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. There is a related question on how to capitalize the first letter of every word in Java which has some helpful answers. A: This is a late answer but I think might help someone... If you are comfortable with capitilizing the dynamic text in the java code then you can use: textView.setText(text.toUpperCase()); A: @Shine's answer is correct I don't know why it was down voted. android:capitalize was deprecated in API 3. Unfortunately the TextView docs fail to indicate this, the proof is burried in R.attr: R.attr Android studio also fails to inform you that this attribute is deprecated. Another 30 mins I'll never get back, thanks google! A: In kotlin gives private val replacementTransformationMethod: ReplacementTransformationMethod = object : ReplacementTransformationMethod() { override fun getOriginal(): CharArray { return charArrayOf( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ) } override fun getReplacement(): CharArray { return charArrayOf( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ) } } then in the block override fun onActivityCreated(savedInstanceState: Bundle?) set this.textUserCode.transformationMethod = replacementTransformationMethod A: android:capitalize is deprecated on ICS, so I guess it should be better to do it in code (i.e. with String.toUpperCase()) Another try could be android:inputType="textCapWords" but I guess it would require an EditText to work. I don't know if this is the reason for your code, what version are you targeting?
{ "language": "en", "url": "https://stackoverflow.com/questions/7573095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Equivalent of "shift" for a hash to create a $class->next() method I almost feel like saying "it's me again!". Anyway, here we go. I like using while $object->next() style constructs. They appeal to me and seem "neat". Now, when the thing I'm iterating over is an array, it's straightforward ("shift @ary or return undef") sub next { my ( $self, $args ) = @_; my $next = shift @{ $self->{list_of_things} } or return undef; my ( $car, $engine_size, $color ) = split( /\Q$opts->{fieldsep}/, $next ); $self->car = $host; $self->engine_size = $engine_size; $self->color = $color; } In this example I use AUTOLOAD to create the getters and setters and then have those instance variables available in my object during the while loop. I'd like to do something similar but with the "list_of_things" being a %hash. Here's a non-OO example that doesn't make it into the first iteration. Any ideas why? (The total "list_of_things" is not that big - maybe 100 entries - so to do a keys(%{$hash}) every time doesn't seem too wasteful to me). use strict; use warnings; use Data::Dumper; my $list_of_things = { volvo => { color => "red", engine_size => 2000, }, bmw => { color => "black", engine_size => 2500, }, mini => { color => "british racing green", engine_size => 1200, } }; sub next { my $args = $_; my @list = keys( %{$list_of_things} ); return undef if scalar @list == "0"; my $next = $list_of_things->{ $list[0] }; delete $list_of_things->{ $list[0] }; return $next; } while ( next()) { print Dumper $_; print scalar keys %{ $list_of_things } } Is there a better way of doing this? Am I doing something crazy? EDIT: I tried Ikegami's suggestion. Of course, Ikegami's example works flawlessly. When I try and abstract a little, so that all that is exposed to the object is a next->() method, I get the same "perl-going-to-100%-cpu" problem as in my original example. Here's a non-OO example: use Data::Dumper qw( Dumper ); sub make_list_iter { my @list = @_; return sub { @list ? shift(@list) : () }; } sub next { make_list_iter( keys %$hash ); } my $hash = { ... }; while ( my ($k) = next->() ) { print Dumper $hash->{$k}; } It does not seem to get past the first step of the while() loop. I am obviously missing something here... A: The each operator is a builtin that iterates over hashes. It returns undef when it runs out of elements to return. So you could so something like package SomeObject; # creates new object instance sub new { my $class = shift; return bless { hash_of_things => { @_ } }, $class } sub next { my $self = shift; my ($key,$value) = each %{ $self->{hash_of_things} }; return $key; # or return $value } Calling keys on the hash will reset the each iterator. It's good to know this so you can reset it on purpose: sub reset { my $self = shift; keys %{ $self->{hash_of_things} } } and so you can avoid resetting it on accident. The section on tie'ing hashes in perltie also has an example like this. A: If you don't want to rely on the hash's builtin iterator (used by each, keys and values), there's nothing stopping you from making your own. use Data::Dumper qw( Dumper ); sub make_list_iter { my @list = @_; return sub { @list ? shift(@list) : () }; } my $list_of_things = { ... }; my $i = make_list_iter(keys %$list_of_things); while (my ($k) = $i->()) { local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; say "$k: " . Dumper($list_of_things->{$k}); } A: Here's how List::Gen could be used to create an iterator from a list: use strict; use warnings; use List::Gen 'makegen'; my @list_of_things = ( # This structure is more suitable IMO { make => 'volvo', color => 'red', engine_size => 2000, }, { make => 'bmw', color => 'black', engine_size => 2500, }, { make => 'mini', color => 'british racing green', engine_size => 1200, } ); my $cars = makegen @list_of_things; print $_->{make}, "\n" while $cars->next; A: Well, if you don't need $list_of_things for later, you can always do something like while(keys %$list_of_things) { my $temp=(sort keys %$list_of_things)[0]; print "key: $temp, value array: " . join(",",@{$list_of_things->{$temp}}) . "\n"; delete $list_of_things->{$temp}; } And if you do need it, you can always assign it to a temporary hash reference and perform the same while loop on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where does the limitation of 10^15 in D.J. Bernstein's 'primegen' program come from? At http://cr.yp.to/primegen.html you can find sources of program that uses Atkin's sieve to generate primes. As the author says that it may take few months to answer an e-mail sent to him (I understand that, he sure is an occupied man!) I'm posting this question. The page states that 'primegen can generate primes up to 1000000000000000'. I am trying to understand why it is so. There is of course a limitation up to 2^64 ~ 2 * 10^19 (size of long unsigned int) because this is how the numbers are represented. I know for sure that if there would be a huge prime gap (> 2^31) then printing of numbers would fail. However in this range I think there is no such prime gap. Either the author overestimated the bound (and really it is around 10^19) or there is a place in the source code where the arithmetic operation can overflow or something like that. The funny thing is that you actually MAY run it for numbers > 10^15: ./primes 10000000000000000 10000000000000100 10000000000000061 10000000000000069 10000000000000079 10000000000000099 and if you believe Wolfram Alpha, it is correct. Some facts I had "reverse-engineered": * *numbers are sifted in batches of 1,920 * PRIMEGEN_WORDS = 3,932,160 numbers (see primegen_fill function in primegen_next.c) *PRIMEGEN_WORDS controls how big a single sifting is - you can adjust it in primegen_impl.h to fit your CPU cache, *the implementation of the sieve itself is in primegen.c file - I assume it is correct; what you get is a bitmask of primes in pg->buf (see primegen_fill function) *The bitmask is analyzed and primes are stored in pg->p array. I see no point where the overflow may happen. A: I wish I was on my computer to look, but I suspect you would have different success if you started at 1 as your lower bound. A: Just from the algorithm, I would conclude that the upper bound comes from the 32 bit numbers. The page mentiones Pentium-III as CPU so my guess it is very old and does not use 64 bit. 2^32 are approx 10^9. Sieve of Atkins (which the algorithm uses) requires N^(1/2) bits (it uses a big bitfield). Which means in 2^32 big memory you can make (conservativ) N approx 10^15. As this number is a rough conservative upper bound (you have system and other programs occupying memory, reserving address ranges for IO,...) the real upper bound is/might be higher.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: What is mutation in cassandra? What is mutation in cassandra? What is it doing? i didnt find any full information about it... Can you answer or share the link with manual or description Thanks A: Mutation is a thrift-generated class defined in the cassandra.thrift file. You can find this file in the interface folder under your cassandra folder: /** A Mutation is either an insert (represented by filling column_or_supercolumn) or a deletion (represented by filling the deletion attribute). @param column_or_supercolumn. An insert to a column or supercolumn (possibly counter column or supercolumn) @param deletion. A deletion of a column or supercolumn */ struct Mutation { 1: optional ColumnOrSuperColumn column_or_supercolumn, 2: optional Deletion deletion, } where ColumnOrSuperColumn and Deletion are also thrift objects, defined in the same file. A: From http://wiki.apache.org/cassandra/API: Mutation A Mutation encapsulates either a column to insert, or a deletion to execute for a key. Like ColumnOrSuperColumn, the two properties are mutually exclusive - you may only set one on a Mutation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android kernel source code I downloaded Android 2.2 source code a long time ago but it didn't have the kernel source code. I looked online and it seems like there is a separate Android kernel source I should download. Someone gave me this address git clone https://android.googlesource.com/kernel/common but I think I should specify the version and branch. So what is the full command to download Android 2.2 froyo kernel source code? A: For other kernels you could use any of these: git clone https://android.googlesource.com/kernel/common.git git clone https://android.googlesource.com/kernel/goldfish.git git clone https://android.googlesource.com/kernel/msm.git git clone https://android.googlesource.com/kernel/omap.git git clone https://android.googlesource.com/kernel/samsung.git git clone https://android.googlesource.com/kernel/tegra.git A: git clone https://android.googlesource.com/kernel/common.git is not enough ! cd common List all the branches: git branch -a Checkout one of them: git checkout android-2.6.39 A: Get tools: $ sudo apt-get install git-core gnupg sun-java5-jdk flex bison gperf libsdl-dev libesd0-dev libwxgtk2.6-dev build-essential zip curl libncurses5-dev zlib1g-dev Get repo tool: $ curl https://storage.googleapis.com/git-repo-downloads/repo > ~/bin/repo $ chmod a+x ~/bin/repo Get source code: $ repo init -u https://android.googlesource.com/platform/manifest OR $ repo init -u https://android.googlesource.com/platform/manifest -b release-1.0 OR $ repo init -u https://android.googlesource.com/platform/manifest -b android-sdk-1.5_r2 $ repo sync` Sync single project: $ repo sync {project_name} Get common kernel: $ git clone https://android.googlesource.com/kernel/common A: To add to @Aloongs answer -> Get the source using Git: git checkout -b android-2.6.35 origin/android-2.6.35 where -b = branch name and start point is android-2.6.35 To list the remote branches use the following command: git branch -r
{ "language": "en", "url": "https://stackoverflow.com/questions/7573110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete item from list in Python while iterating over it I'm writing a round robin algorithm for a tournament app. When the number of players is odd, I add 'DELETE' to the list of players, but later, when I want to delete all items from schedule list that contain 'DELETE', I can't -- one is always left. Please take a look at the code -- the problem is simple and I suppose it's about lists; I just i can't see it. """ Round-robin tournament: 1, 2, 3, 4, | 5, 6, 7, 8 => 1, 2, 3, 4 => rotate all but 1 => 1, 5, 2, 3 => repeat => 1, 6, 5, 2 ... 5, 6, 7, 8 6, 7, 8, 4 7, 8, 4, 3 in every round pick l1[0] and l2[0] as first couple, after that l1[1] and l2[1]... """ import math lst = [] schedule = [] delLater = False for i in range(3): #make list of numbers lst.append(i+1) if len(lst) % 2 != 0: #if num of items is odd, add 'DELETE' lst.append('DELETE') delLater = True while len(schedule) < math.factorial(len(lst))/(2*math.factorial(len(lst) - 2)): #!(n)/!(n-k) mid = len(lst)/2 l1 = lst[:mid] l2 = lst[mid:] for i in range(len(l1)): schedule.append((l1[i], l2[i])) #add lst items in schedule l1.insert(1, l2[0]) #rotate lst l2.append(l1[-1]) lst = l1[:-1] + l2[1:] if delLater == True: #PROBLEM!!! One DELETE always left in list for x in schedule: if 'DELETE' in x: schedule.remove(x) i = 1 for x in schedule: print i, x i+=1 A: schedule[:] = [x for x in schedule if 'DELETE' not in x] See the other questions about deleting from a list while iterating over it. A: To remove elements from a list while iterating over it, you need to go backwards: if delLater == True: for x in schedule[-1::-1]): if 'DELETE' in x: schedule.remove(x) A better option is to use a list-comprehension: schedule[:] = [item for item in schedule if item != 'DELETE'] Now, you could just do schedule = instead of schedule[:] = -- what's the difference? One example is this: schedule = [some list stuff here] # first time creating modify_schedule(schedule, new_players='...') # does validation, etc. def modify_schedule(sched, new_players): # validate, validate, hallucinate, illustrate... sched = [changes here] At this point, all the changes that modify_schedule made have been lost. Why? Because instead of modifying the list object in place, it re-bound the name sched to a new list, leaving the original list still bound to the name schedule in the caller. So whether or not you use list_object[:] = depends on if you want any other names bound to your list to see the changes. A: You shouldn't modify the list while iterating over it: for x in schedule: if 'DELETE' in x: schedule.remove(x) Instead, try: schedule[:] = [x for x in schedule if 'DELETE' not in x] For more info, see How to remove items from a list while iterating? A: Don't modify a sequence being iterated over. schedule[:] = [x for x in schedule if 'DELETE' not in x]
{ "language": "en", "url": "https://stackoverflow.com/questions/7573115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to compare two objects using asp.net mvc these are two same object but my condition is going into else block. how to compare two objects values same or not? baObject b = new baObject(); baObject b1 = new baObject(); if (object.Equals(b, b1)) { // Equal } else { // not equal } what about this kind of behaviour. var t1 = repo.Model_Test_ViewAllBenefitCodes(2) .OrderBy(p => p.ba_Object_id) .ToArray();//.FirstOrDefault(); var t2 = x.ViewAllBenefitCodes .OrderBy(p => p.ba_Object_id) .ToArray();//.FirstOrDefault(); here t1 and t2 are same objects but getting from two different methods or functions. A: You're dealing with reference equality here by default. So with reference equality it's going to check if you actually have the same object - meaning that b and b1 are the same object in memory, not just equivalent, whatever that means for a baObject. See this MSDN Reference You can see near the bottom of that MSDN reference that you can define your own implementation of operator== so that you can do something like: if (a1 == a2) where a1 and a2 are objects of some type you've created. Whatever makes them equivalent is up to you - e.g., if they had certain properties that you could compare. Back to reference equality - if you'd done something like this: baObject b = new baObject(); baObject b1 = b; if (object.Equals(b, b1)) it would evaluate as true because b and b1 are, in fact, the same object. But since that's probably not what you're after, you could define operator== for the baObject class and then compare them to see if they are equivalent. You could do something like: public static bool operator ==(baObject b1, baObject b2) { return b1.foo == b2.foo && b1.bar == b2.bar; } to define what equivalence means for your baObject. A: You could probably override Equals() or == to compare the objects in whatever way you'd like (i.e. has the same ID property). This way you control when two objects should be considered equal. A: I doubt that they are the same objects. object.equals() would have returned true otherwise. The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation. Note that a derived type might override the Equals method to implement value equality. Value equality means the compared objects have the same value even though they have different binary representations. For example, consider two Decimal objects that represent the numbers 1.10 and 1.1000. The Decimal objects do not have bitwise equality because they have different binary representations to account for the different number of trailing zeroes. However, the objects have value equality because the numbers 1.10 and 1.1000 are considered equal for comparison purposes since the trailing zeroes are insignificant. To achieve what you are explaining us, you are better left with overriding the Equals method, also to make use of the == and != operators we'll need to overload those.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linq to entities in asp.net and generic delete method I am having trouble creating generic delete method, not even sure if this possible. I have a delete method which will delete record from db based on entity type and row id value (pk), that works ok but it needs to know the type in advance. In some cases I can only get object type using Object.GetType() at runtime (like from viewstate) and that is when trouble starts. Here is my method that works when type is known, is there a way to modify it so that it will use Object.GetType() instead of T ? public void Delete<T>(long Id) where T : class,new() { #region PerformaneMonitor IDbEntities Db=null; T item=null; try { Db = this.GetDatabase(); item = new T(); Type itemType = item.GetType(); EntityContainer entityContainer = Db.MetadataWorkspace.GetEntityContainer(Db.DefaultContainerName, DataSpace.CSpace); var entity = entityContainer.BaseEntitySets.First(b => b.ElementType.Name == itemType.Name); if (entity.ElementType.KeyMembers.Count == 0) { throw new Exception("Unable to delete a record witout unique id"); } string PrimaryKeyName = entity.ElementType.KeyMembers[0].Name; itemType.GetProperty(PrimaryKeyName).SetValue(item, Id, null); } catch (Exception ex) { Close(Db); throw(ex); } this.Delete<T>(item, Db); Close(Db); #region PerformaneMonitor } so I am trying to convert it to Delete(object EntityType,long Id ) but no luck. Here what it looks like : public void Delete(object target,long Id) { #region PerformaneMonitor IDbEntities Db = null; try { Db = this.GetDatabase(); Type itemType = (Type)target; EntityContainer entityContainer = Db.MetadataWorkspace.GetEntityContainer(Db.DefaultContainerName, DataSpace.CSpace); var entity= entityContainer.BaseEntitySets.First(b => b.ElementType.Name == itemType.Name); if (entity.ElementType.KeyMembers.Count == 0) { throw new Exception("Unable to delete a record witout unique id"); } string PrimaryKeyName = entity.ElementType.KeyMembers[0].Name; itemType.GetProperty(PrimaryKeyName).SetValue(target, Id, null); } catch (Exception ex) { Close(Db); throw (ex); } this.Delete(target, Db); Close(Db); //_method_tag_end_ #region PerformaneMonitor } I am getting 'Object does not match target type' on this line: itemType.GetProperty(PrimaryKeyName).SetValue(target, pkey, null); the object target is actaul instance of specific type which I do in the calling method from Type of object and using reflection and pass to this function but still I have no idea what type it is at run time. If someone can help it will be greatly appreciated. A: It sounds like you should do something along these lines: (Sorry, can't test to make sure it works as written.) object o = itemType.GetProperty(PrimaryKeyName); MethodInfo mi = o.GetType().GetMethod("SetValue"); mi.Invoke(o, new object [] { Id, null });
{ "language": "en", "url": "https://stackoverflow.com/questions/7573117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Form Layout funny I have a weird problem. I have a ASP.Net MVC 3 site, containing a user registration page with the following markup: <div> <fieldset> <legend>Personal Information</legend> <div class="editor-label"> First Name </div> <div class="editor-field"> @Html.TextBox("Firstname") </div> <div class="editor-label"> Last Name </div> <div class="editor-field"> @Html.TextBox("Lastname") </div> <div class="editor-label"> Employee Number </div> <div class="editor-field"> @Html.TextBox("EmployeeNo") </div> <div class="editor-label"> Id Number </div> <div class="editor-field"> @Html.TextBox("Idnumber") </div> <div class="editor-label"> Date of birth </div> <div class="editor-field"> @Html.TextBox("Dob") </div> <div class="editor-label"> Cell Number </div> <div class="editor-field"> @Html.TextBox("CellNumber") </div> </fieldset> <fieldset> <legend>Site Preferences</legend> <div class="editor-label"> Username </div> <div class="editor-field"> @Html.TextBox("Username") </div> <div class="editor-label"> Password </div> <div class="editor-field"> @Html.Password("Password") </div> <div class="editor-label"> Confirm Password </div> <div class="editor-field"> @Html.Password("Confirm") </div> <div class="editor-label"> E-mail </div> <div class="editor-field"> @Html.TextBox("Email") </div> <p> <input type="submit" value="Register" /> </p> </fieldset> </div> Everything looks fine and their alignment is 100% except for the Id Number and E-mail text inputs which looks like its right aligned. The css is use looks like: form { margin: 0; padding: 0; } fieldset { margin: 1em 0; border: none; border-top: 1px solid #ccc; } legend { margin: 1em 0; padding: 0 .5em; color: #036; background: transparent; font-size: 1.3em; font-weight: bold; } label, .editor-label { float: left; width: 100px; padding: 0 1em; text-align: right; } fieldset div { margin-bottom: .5em; padding: 0; display: block; } fieldset div input, fieldset div textarea { width: 150px; border-top: 1px solid #555; border-left: 1px solid #555; border-bottom: 1px solid #ccc; border-right: 1px solid #ccc; padding: 1px; color: #333; } fieldset div select { padding: 1px; } div.fm-multi div { margin: 5px 0; } div.fm-multi input { width: 1em; } div.fm-multi label { display: block; width: 200px; padding-left: 5em; text-align: left; } #fm-submit { clear: both; padding-top: 1em; text-align: center; } #fm-submit input { border: 1px solid #333; padding: 2px 1em; background: #555; color: #fff; font-size: 100%; } input:focus, textarea:focus { background: #efefef; color: #000; } fieldset div.fm-req { font-weight: bold; } fieldset div.fm-req label:before { content: "* "; } #container { margin: 0 auto; padding: 1em; width: 350px; text-align: left; } p#fm-intro { margin: 0; } What am I missing, why is it just the two fields thats all wrong? Thanks! A: The width of the div with class .editor-label is not large enough. Currently it is set to 100px. But if you expand that to fit the full contents of Confirm Password then it should align itself. Below is a demo of your code with a .editor-label width set to 200px. http://jsfiddle.net/LuBUb/
{ "language": "en", "url": "https://stackoverflow.com/questions/7573118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPad/iPhone double click problem I'm having a very similar problem to iPad/iPhone hover problem causes the user to double click a link where a user tapping a link has to tap twice to actually go to it. I implemented the solution in that question, but I have a new problem now. The redirection happens when the user taps a link, but it happens no matter what. So even if the user is trying to scroll the page, and they start the scroll on a link, the page redirects when they let go of the scroll. Is there a way to keep the links so that they only need one tap, but if they're scrolling, don't redirect the page? A: Here's what I ended up doing: The problem is that touchstart and touchend only know about touch events, not scroll events, so they only react to starting the touch and ending the touch. What we have to do is distinguish between scrolling and not scrolling. Here's what I did: $('a') .live('touchstart', function(){ isScrolling = false; }) .live('touchmove', function(e){ isScrolling = true; }) .live('touchend', function(e){ if( !isScrolling ) { window.location = $(this).attr('href'); } }); This does these things in order: * *When touch is first recorded, set isScrolling to false. *When touch is moved, set isScrolling to true. This will not happen if the touch doesn't move. *When touch is stopped, if scrolling has not happened, redirect the page to the link's href. Edit: A while after this, I discovered the problem was being caused by SuperFish. Disabling superfish when the page was under a certain width solved the problem. A: My advice is to: * *Add hover effects on touchstart and mouseenter. *Remove hover effects on mouseleave, touchmove and click. This is similar to Jake's answer, but removes the need to emulate the click event. Background In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com): * *touchstart *touchmove *touchend *300ms delay, where the browser makes sure this is a single tap, not a double tap *mouseover *mouseenter * *Note: If a mouseover, mouseenter or mousemove event changes the page content, the following events are never fired. *mousemove *mousedown *mouseup *click It does not seem possible to simply tell the webbrowser to skip the mouse events. What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change. Solution Explained To recap: * *Add hover effects on touchstart and mouseenter. *Remove hover effects on mouseleave, touchmove and click. Note that there is no action on touchend! This clearly works for mouse events: mouseenter and mouseleave (slightly improved versions of mouseover and mouseout) are fired, and add and remove the hover. If the user actually clicks a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser. This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter, and since this causes no content changes (it was already added), the click event is also fired, and the link is followed without the need for the user to click again! The 300ms delay that a browser has between a touchstart event and click is actually put in good use because the hover effect will be shown during this short time. If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove. That's it! Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question. Alternative Solutions I've found the following problems with the following alternatives: * *browser detection: Extremely prone to errors. Assumes that a device has either mouse or touch, while a combination of both will become more and more common when touch displays prolifirate. *CSS media detection: The only CSS-only solution I'm aware of. Still prone to errors, and still assumes that a device has either mouse or touch, while both are possible. *Emulate the click event in touchend: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link. *Use a variable to suppress mouse events: This set a variable in touchend that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface). Further Reading * *http://jsfiddle.net/macfreek/24Z5M/. Test the above solution for yourself in this sandbox. *http://www.macfreek.nl/memory/Touch_and_mouse_with_hover_effects_in_a_web_browser. This same answer, with a bit more background. *http://www.html5rocks.com/en/mobile/touchandmouse/. Great background article on html5rocks.com about touch and mouse in general. *https://developer.apple.com/library/ios/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html. Safari Web Content Guide - Handling Events. See in particular figure 6.4, which explains that no further events are fired after a content change during a mouseover or mousemove event. See also Disable hover effects on mobile browsers. A: If your content is in a UIScrollView, you can (or may already have) implemented the UIScrollViewDelegate; which contains the following method: -(void)scrollViewDidScroll: (UIScrollView*)scrollView If you use this, and get the following: float offset = scrollView.contentOffset.y; if (offset > 0) // then we have started to scroll If you use this condition in conjunction with detecting the number of taps/presses currently on the screen, (ie, just one in your case) then ignore any fired calls (if >1 taps) that may occur when a link is tapped. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: javascript validation two fields comparation I have two fields in a form <div class="form"> <label class="title">{'webmasterSubmitWebsite_rss_feed_title'|lang}</label> <div class="infos"><input type="text" class="input_text_large" name="rssTitle" value="" /> <img src="{"/templates/$templateName/images/icone_info.gif"|resurl}" alt="" class="aide" title="{'webmasterSubmitWebsite_rss_feed_title_tooltip'|lang}" /></div> </div> <div class="form"> <label class="title">{'webmasterSubmitWebsite_rss_feed_url'|lang}</label> <div class="infos"><input type="text" class="input_text_large" name="rssFeedOfSite" value="" /> <img src="{"/templates/$templateName/images/icone_info.gif"|resurl}" alt="" class="aide" title="{'webmasterSubmitWebsite_rss_feed_url_tooltip'|lang}" /></div> </div> and I want a javascript or jquery or similar function to validate this two fields in this mode: If rss title (first field) is not blank (is filled) then rss URL (second field) must be filled also with a valid URL else a error message appear and this message appear also if only the rss field URL is filled and not the rss title field ie if a user fill first field then must compile second field and vice versa. Any solution? Thanks. A: Give the input tags an ID attribute instead of name and with jquery you can do this: function checkInput(){ var f1 = $('#rssTitle').value; var f2 = $('#rssFeedOfSite').value; if(f1 == '' && f2 != '') { alert('Please enter an rss Title'); return false; } if(f1 != '' && f2 == '') { alert('Please enter a url'); return false; } //check for valid url if(f2.substring(0,7) != 'http://') { alert('Please enter a valid url'); return false; } $('#form1').submit(); } Also have your button call this function in its onclick event. edit: if you want to keep name attribute instead of ID, select them using jquery like so: var f1 = $('input[name="rssTitle"]').value;
{ "language": "en", "url": "https://stackoverflow.com/questions/7573127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling ViewExpiredException depending on the current view I am using JSF 2.0 and Primefaces in my project. I have two xhtml pages namely Cars.xhtml and Bikes.xhtml. I am using ViewScoped backing beans. Currently If get view expired exception from any of the two pages,im handling it in the web.xml. through the error-page tag and directing to welcome.xhtml. Now If i get a viewexpired exception from Bikes.xhtml I need to direct to another page which is BikesHome.xhtml instead of welcome.xhtml. If the exception is from Cars.xhtml, welcome.xhtml should be shown. Please help me how to do. A: I not 100% sure about this (because I haven't tried it myself) but here is my suggestion for - Check this out Dealing Gracefully with ViewExpiredException in JSF2. if (t instanceof ViewExpiredException) { ViewExpiredException vee = (ViewExpiredException) t; At this point you can get the view id as follows - vee.getViewId(); And then based on the view id do the desired navigation. NavigationHandler nh = facesContext.getApplication().getNavigationHandler(); //check condition, set view nv.handleNavigation(facesContext, null, "/view-id?faces-redirect=true"); facesContext.renderResponse(); Or, I think you could also do - FacesContext.getExternalContext().redirect(url); FacesContext.responseComplete(); to redirect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Specializing STL algorithms so they automatically call efficient container member functions when available The STL has global algorithms that can operate on arbitrary containers as long as they support the basic requirements of that algorithm. For example, some algorithms may require a container to have random access iterators like a vector rather than a list. When a container has a faster way of doing something than the generic algorithm would, it provides a member function with the same name to achieve the same goal - like a list providing its own remove_if() since it can remove elements by just doing pointer operations in constant time. My question is - is it possible/advisable to specialize the generic algorithms so they automatically call the member function version for containers where it's more efficient? E.g. have std::remove_if call list::remove_if internally for lists. Is this already done in the STL? A: Not in the case of remove_if, since the semantics are different. std::remove_if doesn't actually erase anything from the container, whereas list::remove_if does, so you definitely don't want the former calling the latter. Neither you nor the implementation can literally specialize the generic algorithms for containers because the algorithms are function templates that take iterators, and the containers are themselves class templates, whose iterator type depends on the template parameter. So in order to specialize std::remove_if generically for list<T>::iterator you would need a partial specialization of remove_if, and there ain't no such thing as a partial specialization of a function template. I can't remember whether implementations are allowed to overload algorithms for particular iterator types, but even if not the "official" algorithm can call a function that could be overloaded, or it can use a class that could be partially specialized. Unfortunately none of these techniques help you if you've written your own container, and have spotted a way to make a standard algorithm especially efficient for it. Suppose for example you have a container with a random-access iterator, but where you have an especially efficient sort technique that works with the standard ordering: a bucket sort, perhaps. Then you might think of putting a free function template <typename T> void sort(MyContainer<T>::iterator first, MyContainer<T>::iterator last) in the same namespace as the class, and allow people to call it with using std::sort; sort(it1, it2); instead std::sort(it1, it2);. The problem is that if they do that in generic code, they risk that someone else writing some other container type will have a function named sort that doesn't even sort the range (the English word "sort" has more than one meaning, after all). So basically you cannot generically sort an iterator range in a way that picks up on efficiencies for user-defined containers. When the difference in the code depends only on the category of the iterator (for example std::distance which is fast for random access iterators and slow otherwise), this is done using something called "iterator tag dispatch", and that's the most common case where there's a clear efficiency difference between different containers. If there are any remaining cases that apply to standard containers (discounting ones where the result is different or where the efficiency only requires a particular iterator category), let's have them. A: It is not possible - the algorithms work with iterators, and iterators have no knowledge of the container object they refer to. Even if they did, there would be no way to determine at compile time whether a given iterator range refers to the whole of a container, so it could not be done by specialisation alone; there would need to be an extra runtime check. A: The only way to do this would be to create your own wrapper templates for each of the algorithms, taking a container rather than a pair of iterators. Then you could specialize your wrapper for each container type that could be optimized. Unfortunately this removes a lot of the flexibility of the standard algorithms, and litters your programs with a bunch of non-standard calls. A: What you are looking for isn't specialization, but overloading. You could provide alternative versions of the algorithms (not, legally, in namespace std, though) that take containers as arguments, rather than iterator pairs, and either call the STL pendants calling begin() and end() on the container, or do something else. Such an approach of course does require the code to call your functions instead of the STL functions, though. This has certainly been done before, so you might actually find a set of headers out there saving you the work to write all this boilerplate code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use ddply to add a column to a data frame? I have a data frame that looks like this: site date var dil 1 A 7.4 2 2 A 6.5 2 1 A 7.3 3 2 A 7.3 3 1 B 7.1 1 2 B 7.7 2 1 B 7.7 3 2 B 7.4 3 I need add a column called wt to this dataframe that contains the weighting factor needed to calculate the weighted mean. This weighting factor has to be derived for each combination of site and date. The approach I'm using is to first built a function that calculate the weigthing factor: > weight <- function(dil){ dil/sum(dil) } then apply the function for each combination of site and date > df$wt <- ddply(df,.(date,site),.fun=weight) but I get this error message: Error in FUN(X[[1L]], ...) : only defined on a data frame with all numeric variables A: You are almost there. Modify your code to use the transform function. This allows you to add columns to the data.frame inside ddply: weight <- function(x) x/sum(x) ddply(df, .(date,site), transform, weight=weight(dil)) site date var dil weight 1 1 A 7.4 2 0.40 2 1 A 7.3 3 0.60 3 2 A 6.5 2 0.40 4 2 A 7.3 3 0.60 5 1 B 7.1 1 0.25 6 1 B 7.7 3 0.75 7 2 B 7.7 2 0.40 8 2 B 7.4 3 0.60
{ "language": "en", "url": "https://stackoverflow.com/questions/7573144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to trigger a new view when MPMoviePlayer stops playing? I'm new to iOS programming, and although I understand ObjC, It seems to me there is a lack of fundamental iOS programming knowledge. I'm doing the project for iPad where I need to show videos in fullscreen and some additional information on separate views (so information is partially in video format and partially in text/image). I ended up being able to only show video. That's pretty much it so far. So I will appreciate any advice. I don't need a tutorial. Just a hint on where and what to read to grasp a concept. Thank you A: You just need to register for MPMoviePlayer notifications. See "Movie Player Notifications" in the documentation for MPMoviePlayerController. For displaying a new view either use UINavigationController (you can just use the navigation app template to start) or use presentModalViewController, or just fade in a new view with the supplemental info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stop a WCF service on IIS from becoming idle .NET 4.0/IIS 7 What is the best way to ensure that a WCF is always available on IIS? Currently if a service is not used it goes to sleep and takes approximately 10 seconds to wake up. Should I change the idle time-out from the default of 20 to 0? Also, would the new auto-start feature be of good use for this? Is there anything else that I could use? Thanks, Richard. A: Read this thread. And, yes, autostart in IIS 7.5 can be used to keep the service awake.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: error_reporting(0) throws 500 error So - strange situation I got here. The statement error_reporting(0); has been giving me a server 500 error. However, error_reporting(1); works just fine.. And its killing me, too many warnings for some of my URL validators. What's up with this? Any idea on how this can be fixed? A: try error_reporting(E_ALL); and ini_set("display_errors","On"); and check the errors that occur. After you fix those, there shouldn't be any problem. Good luck Shai. P.S. i would be guessing for almost 100% that you use Chrome, because for some reason chrome would sometimes just show its own error screen instead of showing error messages. So also try another browser just to check the errors. A: First of all, I'm sorry if I behave "smartass", but I have to tell you that if there are warnings, you should consider to fix them instead of just reduce them to silence... :) Junk PHP code let bad things happen, and you won't like it. I understand 80% of the PHP code around is junk, but really try to fix that library, if it's not huge. We can however try to solve the problem if you just make a simple .php file, with only one line: <?php error_reporting(0); ?> and test if it fires the error. If it doesn't, the problem is not caused by error_reporting, but just triggered by it, and there's some sick stuff going on elsewhere. :) A: error_reporting()'s value is defined with constants, so don't use direct value to set it. If you had used the constants, you would have noticed that none of them have 0 as value. If you want to report all errors, there is an exception to the rule : use the value -1 : error_reporting(-1); Source : http://us.php.net/manual/en/function.error-reporting.php And consider fixing all warnings! (and even notices if possible) Note : the -1 value is used to be sure that even if more error code are added, they are all included.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add banner to corner of wordpress with css How can I add a banner to the corner of a wordpress post using css or within the post itself. I've attacked a screen of what I'd like it to look like, but I don't know how to get it done. A: Add a background image to your post class and set the background-position property to top right .post {background:url('your-image.jpg') top right no-repeat} A: Ensure the parent div has position: relative (or position: absolute) set, then set your banner to position: absolute; right: 0; top: 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7573158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Conditionally delete XML elements in XML field in SQL Server using T-SQL I would like to conditionally remove elements in an XML field on SQL Server 2005. For example, I have the following data: <stats> <stat date="2011-09-25 00:00:00" val="1"/> <stat date="2011-09-26 00:00:00" val="5"/> <stat date="2011-09-27 00:00:00" val="3"/> </stats> Using T-SQL, how can I remove the stat elements that have a date value older than, say, one day? Theoretically, I guess the ideal solution can be expressed as: UPDATE XML_TEST SET XML_DATA_FIELD.modify('delete (/stats/stat)') WHERE XML_DATA_FIELD.nodes('/stats/stat').value('@date', 'datetime') < DATEADD(day, -1, GETDATE()) Which of course, does not work. A: This should achieve what you're looking for: declare @testXml xml = '<stats> <stat date="2011-09-25 00:00:00" val="1"/> <stat date="2011-09-26 00:00:00" val="5"/> <stat date="2011-09-27 00:00:00" val="3"/> </stats>' ,@yesterday varchar(20) = convert(varchar, dateadd(day, -1, getdate()), 120) set @testXml.modify('delete //stat[@date < sql:variable("@yesterday")]') Ew, string comparison...
{ "language": "en", "url": "https://stackoverflow.com/questions/7573160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: javascript: object property is array, but append isn't working var objs = { 'prop': [] } objs['prop'].append('q'); Error: TypeError: objs.prop.append is not a function Why this code is not working ? Why console.log(typeof(objs['prop'])); is object not array ? A: Because there are no associative arrays in JavaScript, an associative array is actually an Object. Nothing more nothing less. A: Array.push: var objs = { 'prop': [] } objs['prop'].append('q'); should be: var objs = { 'prop': [] } objs['prop'].push('q');
{ "language": "en", "url": "https://stackoverflow.com/questions/7573161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to train Rhinomocks for arbitrary input? I am trying to set up a unit test for a piece of code that uses a spelling corrector. I have the code properly dependency injected, so setting up the stub in Rhinomocks is not a problem, but the block of text I've created for the test is a good 50 words long and I would really rather not have 50 lines of code that look something like this: spellingCorrector.Stub(x => x.CorrectWord("the")).Return("the"); spellingCorrector.Stub(x => x.CorrectWord("boy")).Return("boy"); spellingCorrector.Stub(x => x.CorrectWord("ran")).Return("ran"); For the purposes of my unit tests I think assuming that the words are spelled right is okay. Is there a way to get Rhinomocks to simply follow a rule about returning, something to the effect of: spellingCorrector.Stub(x => x.CorrectWord(y)).Return(y); A: You could use the IgnoreArguments() method: spellingCorrector .Stub(x => x.CorrectWord(null)) .IgnoreArguments() .Return(y); This way no matter what value is passed to the CorrectWord method, it will return y. UPDATE: After your comment it is more clear: Func<string, string> captureArg = arg => arg; spellingCorrector.Stub(x => x.CorrectWord(null)).IgnoreArguments().Do(captureArg); This will use whatever value is passed as argument as return value. Adapt the captureArg delegate if you need to perform some transformations on this return value. A: For anything complex like this, instead of using RhinoMocks, write your own little stub class. I'd back it with a Dictionary of all the words that should be corrected, and return the word if it isn't in the Dictionary. Mocks were only created to make this kind of thing easier. If it isn't easier (or more importantly, more readable) to use mocks, just write the code. A: If you're not particularly attached to Rhinomock, you can use Moq: spellingCorrector.Setup(x => x.CorrectWord(It.IsAny<string>())) .Returns(x => x);
{ "language": "en", "url": "https://stackoverflow.com/questions/7573162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating A C# & XNA 'Monster Dash' Like Game I decided that my last year C# project would be a 'Monster Dash' like game, I would develop it using C# and XNA, and it would be targeted for PCs, I am using Microsoft Visual Studio 2010, and XNA Game Studio 4.0. The game would be a 2D game, not 3D. Thinking on the development process, a few problems rise up: First, I need to create a 'sort-of-platforms' which the player will run on and will have holes and gaps between them (which will appear randomly) and I have no idea how to do that! The only close thing I've found that might explain that is an sample code called 'Platformer' from microsoft, which I did not understand (it would be nice of someone could explain the method they use there, or a better / more simple way). Second, I would need the player to jump (in order to avoid the gaps and holes and continue running) and I have no idea how to approach the physics part of that feature, I would be really happy if someone could suggest a way to handle that, or point to a useful piece of code. Thanks ahead, iLyrical. A: Make no mistake, just because it is 2D, a platformer is not an easy task. So i would suggest you use any third party library help you can get, using XNA and C# is already a good starting point. Next thing is, and this is where your questions come in, how to solve the physics? You could write it on your own, which is a nice learning experience but if time is crucial it can be difficult and frustrating. So i would suggest using a third party lib for that, like Farseer. Maybe this little tutorial comes in handy aswell. But again, this is definitely not an easy task. Depending on your Skill, which i of course don't know, i would suggest an easier game, if it must be a game at all. Games are propably the most difficult programming task you can imagine. Dealing with multiple subsystems simultaneously (Graphics, AI, Sound, Input, Physics); making them work together is already a huge task, but having the content (Sprites, Wavs, Music, Menu gfx, etc.) is another beast on its own. A final advise is, if you don't understand the Platformer code; read it again, and again; if you don't understand certain parts read about them until you understand them. If you have problems with c# first learn it and never stop to learn it. Also read as many tutorials and code about games you can find. It is important to see how and why are other people solving problems the way they do. A: The platformer example on the Microsoft website is a good place to start. I made something similar a while back somewhat based on that example. Its a tiled based approach where you have a 2 dimensional list of "Tiles" (A list of lists of tiles List>) You set a static size for the tiles (say 16x16 pixels), then it's just a matter of looping through the list to draw/do collision detection, etc. Just something to think about, if I think about it I can post some code later if you wanted, it's at home. A simple way I usually approach movement physics like that is to use 3 Vector2 objects, one for position, one for velocity and one for acceleration. If you're familiar with simple physics, position = velocity * deltaTime, velocity = acceleration * deltaTime. When a player jumps you just increase the players acceleration, then in the update loop, calculate the position: // On Jump player.acceleration += someConstant // On Update this.velocity += this.acceleration * deltaTime this.position += this.velocity * deltaTime Again, I'll post some real code later. Hope this helps get you started Edit: Here's some movement code public override void Update(GameTime gameTime) { float deltaTime = ((float)gameTime.ElapsedGameTime.Milliseconds) / 1000f; currentState = Keyboard.GetState(); if (canMove) { // Input if (currentState.IsKeyDown(Keys.Left)) Acceleration.X -= 1000; if (currentState.IsKeyDown(Keys.Right)) Acceleration.X += 1000; if (!airbourne && currentState.IsKeyDown(Keys.Space) && previousState.IsKeyUp(Keys.Space)) { Acceleration.Y -= 25000; airbourne = true; } // Friction in X to limit sliding if (Velocity.X > 0) { Velocity.X -= X_FRICTION; if (Velocity.X < 0) Velocity.X = 0; } else { Velocity.X += X_FRICTION; if (Velocity.X > 0) Velocity.X = 0; } // Gravity Acceleration.Y += 500; } Velocity += Acceleration * deltaTime; if (Velocity.X > 0) Velocity.X += speedMod; else if (Velocity.X < 0) Velocity.X -= speedMod; // Move and check collisions in X Position.X += Velocity.X * deltaTime; if (game.checkCollisions(boundingBox())) { Position.X -= Velocity.X * deltaTime; Velocity.X = 0; } // Move and check collisions in Y Position.Y += Velocity.Y * deltaTime; movingUp = Velocity.Y < 0; if (game.checkCollisions(boundingBox())) { // If moving downwards, player not airbourne if (Velocity.Y >= 0) { airbourne = false; Position.Y = game.getCollisionDistance(boundingBox()) - 32; } else { Position.Y = game.getCollisionDistance(boundingBox()) + 32; } Velocity.Y = 0; } else airbourne = true; movingUp = false; // Reset acceleration Acceleration = Vector2.Zero; previousState = currentState; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Nested Static Variable Access for Dependency Injection I would like to use this pattern to enable dependency injection in my code. I feel that it keeps with the play-doh nature of dynamic languages [1]. class A { static $FOO = 'Foo'; function __construct() { $this->foo = self::$FOO::getInstance(); } } A::$FOO = 'MockFoo'; $a = new A(); Unfortunately, this doesn't work and I get: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in [test.php] on line 6 I can create a temporary variable to trick the parser, but is there another way? function __construct() { $FOO = self::$FOO; $this->foo = $FOO::getInstance(); } [1] http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming A: There is no alternative syntax to accomplish this. You need a temporary variable to trick the parser. A: Try $class = self::$FOO; $this->foo = $class::getInstance();
{ "language": "en", "url": "https://stackoverflow.com/questions/7573166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WatiN, IE instances and grabbing them by their hWnd value I am currently using WatiN to automate a proprietary website at my work, and am running into an issue with being able to grab an IE session by its hWnd value. As of this writing, I can start IE, handle the pop-up that occurs (the site uses JavaScript to generate certain things dynamically), but cannot return to the main IE (the first) window once I have finished interacting with the pop-up. Thoughts? A: I have had trouble with this before and its because i was using local variables between postbacks to store the references to the elements. don't do this var btn = Browser.Button("clientid") btn.Click(); //assume that this triggers a postback var result = btn.Text; do this Browser.Button("clientid").Click(); result = Browser.Button("clientid").Text;
{ "language": "en", "url": "https://stackoverflow.com/questions/7573168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Returning strings in PERL I am trying to get SOAP to return a message, at the moment it just returns hello world. package RAM; sub ram { #!/usr/bin/perl use Sys::MemInfo qw(totalmem freemem totalswap); return SOAP::Data->name('result')->type('string')->value("hello world"); } 1; I am trying to get SOAP to return: print "free memory: ".(&freemem / 1024)."\n"; instead of "hello world" Any help would be appreciated :) A: How about.... my $string_to_return = "free memory: ".(&freemem / 1024)."\n"; return SOAP::Data->name('result')->type('string')->value($string_to_return);
{ "language": "en", "url": "https://stackoverflow.com/questions/7573175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing for multiple controllers for a single resource in Rails 3.1 I asked a question similar to this one about a week ago, but this is a slightly different perspective on it. The nature of the question involves being redirected to the correct controller. I have a single resource, posts, and I have 4 different categories these posts can be under. I want each of these categories to be particular to a single controllers, and so I have the following in my routes.rb: resources "code", :controller => :code_posts, :as => :code resources "sports", :controller => :sports_posts, :as => :sports resources "gaming", :controller => :game_posts, :as => :gaming resources "the-nation", :controller => :personal_posts, :as => :the_nation So now I can access posts through URLs like, for example, /code/1, /sports/34 to access the same post resource, but with each controller focusing on a single scope, namely a particular category. This is all well and good, but my issue comes up when I try to edit or save particular posts. I have the following partial _form.html.erb (rendered in the new and edit views) in all the view folders for their particular controller: <%= form_for @post do |f| %> <div class="field"> <%= f.label :author %><br/> <%= f.text_field :author %> </div> <div class="field"> <%= f.label :title %><br/> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :category %> <%= f.select :category_id, Category.all.collect {|c| [c.name, c.id] }, {:include_blank => true} %> </div> <div class="field"> <%= f.label :summary %><br/> <%= f.text_area :summary, :rows => 5 %> </div> <div class="field"> <%= f.label :body %><br/> <%= f.text_area :body %> </div> <div class="field"> <%= f.label :tag_tokens %><br/> <%= f.text_field :tag_tokens, "data-pre" => @post.tags.map(&:attributes).to_json %> </div> <div class="field"> <%= f.submit "Submit" %> </div> <% end %> So whenever I create or update a post, through whichever controllers, I always get redirected back to /posts/4, /posts/123, /posts/:id, whatever. I want to get redirected to the particular controller the post being edited or created lives under. So if I go to /code/new, and submit the new post, I want to be redirected to /code/1234, and not /posts/1234. How can I do this? For some reason I'm just having major mental mind blocks this morning. Thanks. EDIT Updated <%= form_for @post do |f| %> to <%= form_for @post, :url => code_url(@post) do |f| %> and it works for /code/1/edit but not /code/new. When trying to access a new post form, I get the following error: No route matches {:action=>"show", :controller=>"code_posts", :id=>#<Post id: nil, author: "Les Peabody", summary: nil, body: nil, created_at: nil, updated_at: nil, title: nil, category_id: 1, slug: nil>} This is my CodePostsController#new method def new @post = Post.new(:category => Category.find_by_name("Programming"), :author => current_user.full_name) end A: I think the reason is the form_for method which takes for the update action as default the name of the parameter (here post) it gets. So to change that, you have to add at the beginning (for the example resource code) the following: <%= form_for @post, :url => code_path(@post) do |f| %> This is of course only the URL for an existing object, the URL for a new object should be different. It should be there new_code_path (and no argument). So your partial should only contain the fields and labels, not the form_for call, because the URL should be different then. You should look at the output of the call in the shell: bundle exec rake routes and search for the correct paths in the output. A: You may specify the url in the form <%= form_for @post, :url => gaming_path do |f| %> You may use inheritance on the model. The path in you form is determined by the class name, and in this case it is post. If they mach with resources naming it should generate proper paths as well. The dirty hack may be keeping objects path in it, I saw someone do that, but I do not recommend it too much. A: So, ultimately what is important is how the form gets turned into HTML. If you look at the differences between a form that is meant for editing, and a form that is meant for a new object, there is only one thing that is ever really different that matters - the action URL. In the case of a new form, the form tag should look something like: <form accept-charset="UTF-8" action="/code" class="new_post" id="new_post" method="post"> and in the case of an edit form: <form accept-charset="UTF-8" action="/code/1" class="edit_post" id="edit_post_1" method="post"> The only thing that matters to rails however is the name of the input elements (which are constant in both forms) and the action attribute in the form tag. That tells Rails whether or not it's rendering the edit or create action. Since we're splitting up control of a single resource through multiple controllers, the standard form_for @post will not suffice since Rails can no longer automate the rendering process through convention (as we're doing a very unconventional thing). It is necessary to do some manual labor. The following will do the trick. Convert the partial to the following: <%= form_for @post, :url => path do |f| %> <div class="field"> <%= f.label :author %><br/> <%= f.text_field :author %> </div> <div class="field"> <%= f.label :title %><br/> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :category %> <%= f.select :category_id, Category.all.collect {|c| [c.name, c.id] }, {:include_blank => true} %> </div> <div class="field"> <%= f.label :summary %><br/> <%= f.text_area :summary, :rows => 5 %> </div> <div class="field"> <%= f.label :body %><br/> <%= f.text_area :body %> </div> <div class="field"> <%= f.label :tag_tokens %><br/> <%= f.text_field :tag_tokens, "data-pre" => @post.tags.map(&:attributes).to_json %> </div> <div class="field"> <%= f.submit "Submit" %> </div> <% end %> The path variable in there is a variable passed in through the :locals mechanism in the partial render, like so: new.html.erb <%= render :partial => "form", :locals => {:path => code_index_path} %> and edit.html.erb <%= render :partial => "form", :locals => {:path => code_path(@post)} %> The nice thing with this solution is you can DRY up the code too by placing _form.html.erb in app/views/layouts or app/views/posts and reuse it in all of the new and edit views for all controllers that manipulate the Post resource in a consistent fashion. So rather than having: <%= render :partial => "form", :locals => {:path => code_path(@post)} %> we have: <%= render :partial => "layouts/form", :locals => {:path => code_path(@post)} %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7573177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XSLT ClassCastException in WebSphere when Spring tries to create an AnnotationMethodHandlerAdapter When starting WebSphere, I get this exception: Could not instantiate bean class [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]: Constructor threw exception; nested exception is java.lang.ClassCastException: com.ibm.xtq.xslt.jaxp.compiler.TransformerFactoryImpl incompatible with javax.xml.transform.TransformerFactory Caused by: java.lang.ClassCastException: com.ibm.xtq.xslt.jaxp.compiler.TransformerFactoryImpl incompatible with javax.xml.transform.TransformerFactory at javax.xml.transform.TransformerFactory.newInstance(Unknown Source) at org.springframework.http.converter.xml.AbstractXmlHttpMessageConverter.<init>(AbstractXmlHttpMessageConverter.java:47) at org.springframework.http.converter.xml.SourceHttpMessageConverter.<init>(SourceHttpMessageConverter.java:45) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.<init>(AnnotationMethodHandlerAdapter.java:197) This doesn't seem have any impact on any beans in my applicationContext.xml but it's still odd. For me, this looks as if IBM classes are leaking into my application. How can I fix this? I already set the option "Access to internal server classes" to "Restrict". A: It was indeed a class-loading issue, however this cannot be solved by changing class-loader settings. The problem was that the xml-apis and javax.xml jars were being imported over some maven dependencies. Since we already set the class loader policies for the application to PARENT_LAST, the javax.xml.transform.TransformerFactory was being loaded from the WebApp-Class loader from our jar files. However its implementation 'com.ibm.xtq.xslt.jaxp.compiler.TransformerFactoryImpl' was coming from the server class loader, this one was linked to the javax.xml.transform.TransformerFactory provided by the JDK/JRE. Since the classes were loaded from different sources a ClassCastException was thrown. Removing all dependencies to xml-apis / xerces / javax.xml jars solved the problem. Since these APIs are now part of the JDK they no longer need to be imported. ... and if you wonder why I know so much about this issue: I work together with Aaron. ;) A: I can't speak for Restrict as I have no personal experience with it,But I think the problem is more to do with IBM Class Loader. The class you are referring to is part of IBM Java implementation of TransformerFactory, I think you can try one of the following to solve this issue on hand * *Either change the server class loader policy to PARENT_LAST (This way class loader will find the class from application's local class path, before going to up the chain all the way to java run time) *The other option would be look at the jaxp.properties file, I think it is located in (was_root\java\jre\lib), I only read about this option never actually used it A: Why do you say IBM classes are leaking into your application? The TransformerFactory is asked to create a newInstance. It follows a sequence of steps to determine which TransformerFactory to use. If none of the config is specified, it simply chooses to use the default factory. Here is the javadoc for TransformerFactory: http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/transform/TransformerFactory.html#newInstance() What is the OS ? Is that AIX? http://www.ibm.com/developerworks/java/jdk/aix/j664/sdkguide.aix64.html Looking at this doc (link above) for AIX it tells me that this is the default Impl: javax.xml.transform.TransformerFactory Selects the XSLT processor. Possible values are: com.ibm.xtq.xslt.jaxp.compiler.TransformerFactoryImpl Use the XL TXE-J compiler. This value is the default. Post back additional information so that we can try and troubleshoot this. HTH Manglu
{ "language": "en", "url": "https://stackoverflow.com/questions/7573179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Insert form data into database Is it possible to just iterate through the post results and insert them into the appropriate fields in a table? Instead of doing Request.Form["something"] for each one? A: Yes: Request.Form is a NameValueCollection. This means you can refer to specific keys how you are already doing it: Request.Form["something"], or you can iterate through the items using a foreach loop foreach (string value in Request.Form){ // do stuff with value // save-to-database-function(value) // ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Different pages for different login roles I'm a beginner in JSP. While developing a web application for a sample scenario, I came across this subtlety. I have the following pages: * *index.jsp *login.jsp (and LoginServlet.java) *account.jsp To facilitate code reuse I divided all pages into 3 parts - menu-header, content, footer. For all the above pages, menu-header and footer remains the same, only the content changes. So, I created menuandheader.jsp and footer.jsp to be included into every page. index.jsp = (menuandheader.jsp+content+footer.jsp) Now I have 5 different user roles thus, 5 different index and account pages. (again for these pages only the content area changes). I created a Filter class for LoginServlet.java which takes care of authentication and stores the appropriate page name as a request attribute. (index1.jsp for role #1 and so on) Now the only contents of LoginServlet.java is dispatch = request.getRequestDispatcher(request.getAttribute("page").toString()); dispatch.forward(request, response); But in this approach I need to have 5 almost similar index and account pages. Is there a better way to deal with this scenario? A: You might write a switch in the index.jsp to dynamically generate or include the changed part, depending on a parameter return from the servlet. A: Let's first look at the downsides of your approach * *If you want to add a new role then, You need develop/build/deploy *Your tightly coupling your business requirement (role based access) to your implementation causing a change to implementation on a change to requirment I would say a better approach would be to solve the problem on hand (i.e. restrict resource access based on user role). You can do this in many ways, Here is one way you could solve the problem * *Keep one index.jsp page *Based on the role restrict access, If it is content or hyper link to different resource just hide it (you can do this with simple jsp tag) *You could also benfit from using a framework (spring, struts, jsf etc), They provide good MVC implementation *In index.jsp, you could do some thing like this, I used simple jstl tag in the example <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:if test="${role.admin == true}"> only admin could see this content </c:if> <c:if test="${role.supervisor == true}"> <a href="">only supervisor's link</a> </c:if> every one can see this content I just gave you a simple approach to solve this problem, I would let you choose what the best option would be based on your requirement, I would say keep the implementation loosely coupled and easily extendable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to populate lsitbox in asp.net web application I am trying to populate a list box from a customers table in SQL database.I tested with WPF list box the code is working good but when i try to implement in asp.net web application i am unable to populate the list box. Here is my code try { string query = "SELECT customer_ID FROM Customers WHERE ID = 1"; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(query , conn); da.Fill(ds); foreach (DataRow row in ds.Tables[0].Rows) { listbox1.SelectedValue = row["customer_ID"].ToString(); samplelist.Add(listbox1.SelectedValue); } listbox1.DataSource = samplelist; } catch (Exception) { } Can any one guide me in the right direction ? A: Try using the below code: try { string query = "SELECT customer_ID FROM Customers WHERE ID = 1"; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(query, conn); da.Fill(ds); listbox1.DataSource = ds.Tables[0]; listbox1.DataTextField = "WORKSTATION_ID"; listbox1.DataValueField = "WORKSTATION_ID"; listbox1.DataBind(); } catch (Exception) { } A: foreach (DataRow row in ds.Tables[0].Rows) { samplelist.Add(row["WORKSTATION_ID"].ToString()); } listbox1.DataSource = samplelist; listbox1.DataBind(); A: You should be able to trim this down somewhat to the following. You're missing the DataBind() as well.: try { //Existing to fill ds, check table exists, etc. listbox1.DataSource = ds.Tables[0]; listbox1.DataValueField = "COLUMNNAME"; listbox1.DataTextField = "COLUMNNAME"; listbox1.DataBind(); } catch (Exception) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to capture console output of Eclipse plugin with custom Launch Configuration? I'm writing an Eclipse plugin with a custom launch configuration, i.e. a launch() method inside a subclass of LaunchConfigurationDelegate. This method essentially just calls Runtime.exec(), but when I write to System.out from within launch() it goes to the console of the Eclipse instance which is debugging the plugin, rather than to the console of the plugin instance itself. I've analysed the ILaunchConfiguration and ILaunch arguments to the method but cannot find anywhere that they specify any output/error streams I can write to. As is recommended in the tutorials, I have 2 separate plugins running together; one which handles the UI stuff (LaunchConfigurationTab,LaunchConfigurationTabGroup,LaunchShortcut,) and the other which contains the LaunchConfigurationDelegate itself. I created a console in my UI plugin using this code, and I can write to it fine from within the UI code. But I cannot figure out how to direct output generated in my non-UI plugin to the console created in my UI plugin. I've read this post and this one, but they do not specify how to "get ahold" of the output which is generated within the launch() method in the first place. Any pointers would be really welcome, I am stuck! A: Well I finally managed to get something working as follows: In my LaunchConfigurationDelegate I introduced the following static method: public static void setConsole(PrintStream ps) { System.setOut(ps); System.setErr(ps); } Then when creating my console in my UI plugin's PerspectiveFactory I call it as follows: private void createConsole() { console = new MessageConsole("My Console", null); console.activate(); ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ console }); MessageConsoleStream stream = console.newMessageStream(); MyLaunchConfigurationDelegate.setConsole(new PrintStream(stream)); } This works, except everytime I close down Eclipse and restart it the console disappears. However when I reset my perspective, the console appears again. So obviously I need that code to be called on startup, not in the PerspectiveFactory itself. Hope this helps someone.. and if anybody has some input for this last problem (or about my approach in general) please do comment!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can I access a property from my manifest.json in my extension's JavaScript files? I'd like to refer to the version number as defined in my manifest.json in my extension's JavaScript files. Is there any way to do this? A: I think that this is what you're looking for http://www.martinsikora.com/accessing-manifest-json-in-a-google-chrome-extension chrome.manifest = (function() { var manifestObject = false; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { manifestObject = JSON.parse(xhr.responseText); } }; xhr.open("GET", chrome.extension.getURL('/manifest.json'), false); try { xhr.send(); } catch(e) { console.log('Couldn\'t load manifest.json'); } return manifestObject; })(); And that's all. This short code snippet loads manifest object and put's it among other chrome.* APIs. So, now you can get any information you want: // current version chrome.manifest.version // default locale chrome.manifest.default_locale A: Since chrome 22 you should use chrome.runtime.getManifest(). See docs here. So now it is as simple as: var manifest = chrome.runtime.getManifest(); console.log(manifest.name); console.log(manifest.version);
{ "language": "en", "url": "https://stackoverflow.com/questions/7573191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Impersonation in .NET in Windows 7 (Requested registry access is not allowed) So I am using a user to run the following code that is a member of the "User" group on a Windows 7, x64 machine. I am trying to use impersonation (by logging in as a user that is part of the Administrator group) to allow the current user to read from the registry. For some reason the login happens successfully but even though WindowsIdentity.GetCurrent() is returning the user that is part of the Administrator group I am still getting an error message saying "Requested registry access is not allowed". What am I doing wrong? This is the main code: Dim ra As RunAs = Nothing If UserDomain.Length > 0 AndAlso UserName.Length > 0 AndAlso UserPassword.Length > 0 Then ra = New RunAs ra.ImpersonateStart(UserDomain, UserName, UserPassword) End If If Not My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting", "DontShowUI", 0) Is Nothing AndAlso _ My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting", "DontShowUI", 0) = 0 Then My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting", "DontShowUI", 1) End If And suppose my RunAs class is the following: Public Class RunAs Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _ ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _ ByRef DuplicateTokenHandle As IntPtr) As Boolean ' Test harness. ' If you incorporate this code into a DLL, be sure to demand FullTrust. <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _ Public Sub ImpersonateStart(ByVal Domain As String, ByVal userName As String, ByVal Password As String) tokenHandle = IntPtr.Zero ' Call LogonUser to obtain a handle to an access token. Dim returnValue As Boolean = LogonUser(userName, Domain, Password, 2, 0, tokenHandle) 'check if logon successful If returnValue = False Then Dim ret As Integer = Marshal.GetLastWin32Error() Console.WriteLine("LogonUser failed with error code : {0}", ret) Throw New System.ComponentModel.Win32Exception(ret) Exit Sub End If 'Logon succeeded ' Use the token handle returned by LogonUser. Dim newId As New WindowsIdentity(tokenHandle) impersonatedUser = newId.Impersonate() End Sub End Class A: I agree with @Hans. With UAC, you need to restart the application with UAC privileges, which will cause the UAC prompt to display. A simple way to accomplish this is as follows: * *In normal path of the application, when admin privileges are needed, restart the application with UAC request and a command-line flag, like /admin. *On second run of the application, detect the flag /admin, and do the administrative part of the application. *When the second run finishes (#2), if it was successful, then continue application logic from the first pass. If not successful, display error/perform appropriate exception handling logic. In our application, I have a helper method called RunElevated that attempts to restart the application with requested administrator privileges, which will cause the UAC prompt to display (I have also included my IsAdmin() helper function): Private Function RunElevated(commandLine As String, Optional ByVal timeout As Integer = 0) As Boolean Dim startInfo As New ProcessStartInfo startInfo.UseShellExecute = True startInfo.WorkingDirectory = Environment.CurrentDirectory Dim uri As New Uri(Assembly.GetEntryAssembly.GetName.CodeBase) startInfo.FileName = uri.LocalPath startInfo.Verb = "runas" startInfo.Arguments = commandLine Dim success As Boolean Try Dim p As Process = Process.Start(startInfo) ' wait thirty seconds for completion If timeout > 0 Then If Not p.WaitForExit(30000) Then ' did not complete in thirty seconds, so kill p.Kill() success = False Else success = True End If Else p.WaitForExit() success = True End If Catch ex As Win32Exception success = False Catch ex As Exception MsgBox("Error occurred while trying to start application as administrator: " & ex.Message) success = False End Try Return success End Function Public Function IsAdmin() As Boolean Dim id As WindowsIdentity = WindowsIdentity.GetCurrent Dim p As New WindowsPrincipal(id) Return p.IsInRole(WindowsBuiltInRole.Administrator) End Function To use, I pass a flag and run elevated. In my case, I have a function that sets registry keys, and uses the flag /setregistry to indicate that the instance is started for UAC purposes to just set the registry keys. That code looks something like this: Dim success As Boolean If Not IsAdmin() Then ' try to create the registry keys as administrator success = RunElevated("/setregistry", 30000) success = success And ValidateKeysSet() ' check if it was successful Return success End If ' If we are Admin (Not IsAdmin() = False), then go ahead and set the keys here Then in the startup logic (Form_Load, since this is a forms application), I check if that flag is present: If Command.ToLower.Contains("/setregistry") Then ' if application instance is for sole purpose of setting registry keys as admin If IsAdmin() Then SetRegistryKeys() ' set the keys, since we are admin Else MsgBox("ERROR: Application must be run as administrator to set registry keys.") End If Else ' Perform normal startup process End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7573192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using pastebin API in VB .Net I have a small problem, I've just changed from the public Pastebin API to the new API. I get an invalid api error: Bad API request, invalid api_option Here is my code: Dim Exposure As Integer = 0 System.Net.ServicePointManager.Expect100Continue = False If ComboBox1.Text = "Public" Then Exposure = 0 Else Exposure = 1 End If Dim fi As String = "?api_paste_private=" & Exposure & "&api_paste_format=" & ComboBox2.Text & "&api_paste_expire_date=" & ComboBox3.Text & "&api_dev_key=CENSORED" & "&api_paste_code=" & code Dim w As New System.Net.WebClient() w.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim pd As Byte() = System.Text.Encoding.ASCII.GetBytes(fi) Dim rd As Byte() = w.UploadData("http://pastebin.com/api/api_post.php", "POST", pd) Dim r As String = System.Text.Encoding.ASCII.GetString(rd) TextBox6.Text = r Return r Can anyone please help me? A: You must add api_option=paste to your request, as seen here: http://pastebin.com/api#2
{ "language": "en", "url": "https://stackoverflow.com/questions/7573193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Html select dropdown list - how to choose the selected value from server code I have a select list say of states in the country, which i have in a helper to include easily in any form. (removing most options to make it brief). I have the value of the current selection stored in the database say "CA". How would i set selected="true" to option CA before rendering the list to the user? @helper StateSelect(string name = "State") { <select name="@name" id="@name" class="required"> <option value="">-- Select -- </option> <option value="AK">Alaska</option> <option value="AL">Alabama</option> <option value="AR">Arkansas</option> <option value="AZ">Arizona</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="VA">Virginia</option> <option value="VT">Vermont</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select> } A: As Darin Dimitrov says, the built-in stuff would be better. However, if you do need to, I think you have a few options: * *Add code like this to every line: * *<option value="CA" @(name == "CT" ? "selected=selected" : "")> Connecticut</option> *Just re-add the selected item to the top of the list * *This keeps the code cleaner, the selected option is just repeated at the top (and selected there), before the entire list
{ "language": "en", "url": "https://stackoverflow.com/questions/7573195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how select second item az default in dropdownlist? i have a dropdownlist, in mvc 3 razor: @Html.DropDownList( "SelectedLicensesID", new SelectList(Model, "LicensesID", "LicenseUI")) It contains 5 items. How can i set second item as the default item? A: It depends, what's it's LicensesID value. If you know it you could: @Html.DropDownList( "SelectedLicensesID", new SelectList(Model, "LicensesID", "LicenseUI", "123") ) where 123 is the LicensesID of the item you want preselected. Another possibility is to do this in the controller action: public ActionResult Index() { var model = ... // preselect the item that has LicensesID=123 ViewData["SelectedLicensesID"] = "123"; return View(model); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: to unicode or not to unicode I'm getting a value from the registry. This value might have double byte characters in it. I will later have to transfer this across the network to a C# client to display. C# is all unicode. The function returns MBCS if you call it non-unicode. What should I use? string result = string(cbData); RegQueryValueExA(h_sub_key, "DisplayName", NULL, NULL, (LPBYTE) &result[0], &cbData) or string result = string(cbData); RegQueryValueExW(h_sub_key, L"DisplayName", NULL, NULL, (LPBYTE) &result[0], &cbData) A: Using Unicode whenever possible will make your life easier. The registry contains Unicode natively and converts to MBCS on the fly when you use ReqQueryValueExA, why would you want to do an unneeded conversion? Converting to UTF-8 from UTF-16 might make sense for information going over the network, but if you control both ends of the connection it wouldn't be necessary. A: No, that's not the way it works. The string you get back from the first snippet is encoded according to the current system code page. Could be a double-byte encoding. Could be anything. Big problem of course, the C# code on the other end of that Internet connection has no way to guess what the code page might be. So do not use the first snippet. The second one gets you the string in utf16, the native encoding used in Windows, result needs to be an std::wstring. Also the encoding used by C# so you could send the binary string. Although that's not typically a good idea, xml is popular. It is up to you to set the wire format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Core Data Model change app update I would like to update my app, but I have completely changed the data structure, so is the Core Data model entirely different. Now, the data in the app does not have to be preserved, but you can't just update the app with this new model as it will crash. What is the best way to update my app? A: You need to version the core data structure. Use this guide http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreDataVersioning/Articles/Introduction.html A: If you have a completely new data model you might look into having a new database persistent-store/db file and run a merge function if the app can find an old database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Take a temporarily control of the system using Java I have developed an app for showing some information to the employees of a company. One of the specification was that this information must be seen at least 1 time by the employee once a while. For this purpose, I want to take the maximum control of the system for a while (10 seconds) for being sure the person sees the information. Ej: turn off the keywords and other stuff. This is my first question: Is there any classes in Java which let me do this sorts of things? In the case there isn't, is there another way, how would yo do it? Thanks in advance! A: You will need to use native code for this. Either just develop the application in some native language such as C or C++ or create a JNI DLL in C/C++ and call it from java (which is rather pointless). A: You can run your app in full screen. Thus overlay all other apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mySQL Nested Update using COUNT/MIN/MAX from another Table I have two large tables, products (500k records) and store_products (> 3mm records). Products is the master and product_stores is individual locations with the product. I need to run a single QUERY totaling up information from product_stores and updating the corresponding product. When this was smaller dataset we did it with a nested query: SELECT productid,COUNT(id) as count,MIN(price) as lowprice,MAX(price) as highprice FROM store_products WHILE (productid){ update product set stores = count, min = lowprice, max = highprice WHERE productid = $productid } GROUP BY productid I'm fairly new to nested updates and uncertain how to set multiple fields with a join and group by. Structure [truncated to relevant fields]: CREATE TABLE product ( product_id INT UNSIGNED NOT NULL AUTO_INCREMENT, stores INT UNSIGNED NOT NULL DEFAULT '0', lowprice DECIMAL (6,2) NOT NULL DEFAULT '000.00', highprice DECIMAL (6,2) NOT NULL DEFAULT '000.00', PRIMARY KEY (product_id), KEY stores (stores) ) CREATE TABLE store_product ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, product_id INT UNSIGNED NOT NULL, price DECIMAL(7,2) NOT NULL DEFAULT '0.00', PRIMARY KEY (storeproduct_id), KEY product_id (product_id) ); Fields to update: * *stores [count of store_product records by productid] *min price [MIN of price by productid] *max price [MAX of price by productid] A: Running a single query to perform the update on tables of this size will probably take a while. Anyway - the following should give you what you need. The trick is to alias the product table and then reference the product table in the subselect using that alias. So: update product p set p.lowprice = (select min(price) from store_product sp where sp.product_id = p.product_id), p.highprice = (select max(price) from store_product sp where sp.product_id = p.product_id), p.stores = (select count(*) from store_product sp where sp.product_id = p.product_id) where product_id in (select sp.product_id from store_product sp); One gotcha here is that the stores column will not be updated to 0 for rows that are not present in the store_product table. To cater for this you can use IFNULL while performing a global update: update product p set lowprice = ifnull((select min(price) from store_product sp where sp.product_id = p.product_id),0), highprice = ifnull((select max(price) from store_product sp where sp.product_id = p.product_id),0), stores = ifnull((select count(*) from store_product sp where sp.product_id = p.product_id),0); You may want to try both out and see which is faster. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSAccess VBA code not working on second run The below code is bound to a button. For some reason the below code executes correctly the first time. On the second time, for some users, it does not populate the fields on the website. What could the issue be? Me!WebBrowser0.Navigate "http://bk00app0001/PMD Image Upload/" While Me.WebBrowser0.Busy DoEvents Wend Me!WebBrowser0.Document.getElementById("MainContent_Year").Value = Forms![Main Menu]![SeasonList].Value Me!WebBrowser0.Document.getElementById("MainContent_ItemNumber").Value = Me.OpenArgs Me!WebBrowser0.Document.getElementById("MainContent_btnLock").Click I believe I need to set Me!WebBrowser0 = Nothing on the Close event. However, Me!WebBrowser0 = Nothing throws an error. Any ideas as to how to do this? UPDATE On the second time this code is called MS Access throws the following error when it hits this line: Me!WebBrowser0.Document.getElementById("MainContent_Year").Value = Forms![Main Menu]![SeasonList].Value 'Object variable or With block variable not set' Looks like it was a timing issue. I was able to solve it by adding the following code before I set any of the values on the webpage: While Me!WebBrowser0.Document.getElementsByTagName("p").Length < 10 DoEvents Wend I am now getting the error: "Runtime error '430' class does not support Automation or does not support expected interface" This error refers to the following line of code: Set Cnxn = New ADODB.Connection Here is a screenshot for the line of code above: http://postimage.org/image/2v7p8diis/ The above code is called when I close the form that has the button that calls the browser code. A: While Me!WebBrowser0.Document.getElementsByTagName("p").Length < 10 DoEvents Wend Solved the first issue. The second issue was due to referencing a non-existent DLL on the user's machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery and the this object jQuery is too overpowering :( String.prototype.trim = function () { return this.replace(/^(\s|&nbsp;|\u00A0)+|(\s|&nbsp;|\u00A0)+$/g, ""); } when I try to add the above code, I get "this.replace is not a function". I realise that jQuery references itself as this, so how are you meant to reference this? A: The code you've posted defines a "trim" method on a String. That allows you to do this: " some random string ".trim(); Sounds like you've copied and pasted the BODY of that trim function into some other jQuery function, like this: $('#myfield').change(function () { this = this.replace(/^(\s|&nbsp;|\u00A0)+|(\s|&nbsp;|\u00A0)+$/g, ""); }); Try this instead: $('#myfield').change(function () { $(this).val($(this).val().trim()); }); A: Problem solved: I forgot to put the semi colon on the end of the function and it was running in to the jQuery function String.prototype.trim = function () { return this.replace(/^(\s|&nbsp;|\u00A0)+|(\s|&nbsp;|\u00A0)+$/g, ""); }; (function ($) { ......
{ "language": "en", "url": "https://stackoverflow.com/questions/7573214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: InnerHTML doesn't work in FF? i'm pretty new to Javascript and basiclly everything related to web coding. i have a simple problem using InnerHTML in FF, i hope you can help me. i'm using this code, that should generate a simple html input line, and in IE it works fine (although when i load it i get the "should i enable activeX msg on top), but in FF it doesn't work at all, i can see it's on the page thorugh source, but it doesn't show anything... <div id="mainDiv"></div> <script type="text/javascript"> var siteBoxes = '<form action=HTMLPage.htm name="myform">'; for (var i = 0; i < arr1.length; i++) { siteBoxes += '<INPUT TYPE="checkbox" id="box'+i+'" VALUE="'+arr1[i]+'"/>  '+arrNames[i]+''; } siteBoxes += ''; document.getElementById("mainDiv").innerHTML=siteBoxes; i'm sure it's a simple solution, and i tried searching on the web, but i'm running out of strength for that, i hope any of you kind people can help me. thanks in advance!!! ok, the problem is with the array definition in the head. i just noticed that in the error console in FF i get a msg that the arr1 is undefined, but it is, i even tried moving it to the body and it doesn't change, still undefined... and it works in IE. could it be something with the array definition? is it different from IE and FF??? var arr1 = new Array( "http://www.google.com", "http://www.yahoo.com", "http://www.cnet.com", "http://www.google.ar/search?q=" ); again, it works great in IE, but not in FF A: Somethings I noticed at first glance. <div id="mainDiv"></div> <script type="text/javascript"> var siteBoxes = '<form action="HTMLPage.htm" name="myform">';//put quotes around page for (var i = 0; i < arr1.length; i++) { siteBoxes += '<INPUT TYPE="checkbox" id="box'+i+'" VALUE="'+arr1[i]+'"\/> &nbsp;'+arrNames[i]+'<br \/><br \/>'; } siteBoxes += '<\/form>'; document.getElementById("mainDiv").innerHTML=siteBoxes; arr1 is never declared at least from the code you present to us. A: Works in Opera, IE and FF for me. Try unescaping the output; document.getElementById("mainDiv").innerHTML = unescape(siteBoxes); A: There is something wrong with the ending quotation mark in your script tag. If I delete it and type a new one, the code works. A: There must be a problem with the rest of your code because when I change it. It works fine. <html> <head> </head> <body> <div id="mainDiv"></div> <script type="text/javascript"> var arr1 = new Array(); var arrNames = new Array(); arr1[0] = "test"; arrNames[0] = "nameTest"; var siteBoxes = '<form action=HTMLPage.htm name="myform">'; for (var i = 0; i < arr1.length; i++) { siteBoxes += '<INPUT TYPE="checkbox" id="box'+i+'" VALUE="'+arr1[i]+'"/> &nbsp;'+arrNames[i]+'<br /><br />'; } siteBoxes += '</form>'; document.getElementById("mainDiv").innerHTML = siteBoxes; </script> </body> </html> A: Here's perhaps a cleaner way of implementing this (see comments in code as well): //You can use the simple way of creating an array, and instead of having two //arrays that represent the names and urls, just make a single array of JSON var sitesArray = [ {siteName: "Google",siteUrl:"http://www.google.com"}, {siteName: "Yahoo",siteUrl:"http://www.yahoo.com"}, {siteName: "CNET",siteUrl:"http://www.cnet.com"}, {siteName: "Google Search",siteUrl:"http://www.google.ar/search?q="} ]; //Create an ouput array where you'll compile your html var outputArray = []; //Now loop through sitesArray and push the strings onto the ouputArray for (var i=0,len=arr1.length;i < len;++i) { outputArray.push("<input type=\"checkbox\" id=\"box",i,"\" ", "value="\",sitesArray[i].siteUrl,"\" />&nbsp", sitesArray[i].siteName,"<br /><br />"); } document.getElementById("mainDiv").innerHTML = outputArray.join(""); The primary reason for suggesting this is that string concatenation can be very slow, especially if you have lots of long strings. It's not as big an issue in Firefox, but it's definitely an issue in IE. So pushing strings onto an array, then joining them at the end will give you better performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two Values in Dropdown Access 2007. Is there a way to display two values in a combobox. I realize the combobox is bound to a field in a table, and it can only be bound to one field, but when you click the combobox I have it showing two field, then when you choose and release we would like to display both values. Is there anyway to do that. We don't want to add another text box just to show this additional field. Thanks A: All you can do without an additional textbox is set up your recordset to include two fields in the one: SELECT ID, Surname & ", " & Forename FROM Customers ID is the bound field, so it does not much matter how many fields are concatenated in the display.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning an exit code from a shell script that was called from inside a perl script I have a perl script (verifyCopy.pl) that uses system() to call a shell script (intercp.sh). From inside the shell script, I have set up several exit's with specific exit codes and I'd like to be able to do different things based on which exit code is returned. I've tried using $?, I have tried assigning the value of system("./intercp.sh") to a variable then checking the value of that, but the error message is always 0. Is this because even though something inside the shell script fails, the actual script succeeds in running? I tried adding a trap in the shell script (ie trap testexit EXIT and testexit() { exit 222; } but that didn't work either. A: $? should catch the exit code from your shell script. $ cat /tmp/test.sh #!/bin/sh exit 2 $ perl -E 'system("/tmp/test.sh"); say $?' 512 Remember that $? is encoded in the traditional manner, so $? >> 8 gives the exit code, $? & 0x7F gives the signal, and $? & 0x80 is true if core was dumped. See perlvar for details. Your problem may be one of several things: maybe your shell script isn't actually exiting with the exit code (maybe you want set -e); maybe you have a signal handle for SIGCHLD eating the exit code; etc. Try testing with the extremely simple shell script above to see if its a problem in your perl script or your shell script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is this a correct way to find the derivative of the sigmoid function in python? I came up with this code: def DSigmoid(value): return (math.exp(float(value))/((1+math.exp(float(value)))**2)) a.) Will this return the correct derivative? b.) Is this an efficient method? Friendly regards, Daquicker A: Looks correct to me. In general, two good ways of checking such a derivative computation are: * *Wolfram Alpha. Inputting the sigmoid function 1/(1+e^(-t)), we are given an explicit formula for the derivative, which matches yours. To be a little more direct, you can input D[1/(1+e^(-t)), t] to get the derivative without all the additional information. *Compare it to a numerical approximation. In your case, I will assume you already have a function Sigmoid(value). Taking Dapprox = (Sigmoid(value+epsilon) - Sigmoid(value)) / epsilon for some small epsilon and comparing it to the output of your function DSigmoid(value) should catch all but the tiniest errors. In general, estimating the derivative numerically is the best way to double check that you've actually coded the derivative correctly, even if you're already sure about the formula, and it takes almost no effort. A: In case numerical stability is an issue, there is another possibility: provided that you have a good implementation of the sigmoid available (such as in scipy) you can implement it as: from scipy.special import expit as sigmoid def sigmoid_grad(x): fx = sigmoid(x) return fx * (1 - fx) Note that this is mathematically equivalent to the other expression. In my case this solution worked, while the direct implementation caused floating point overflows when computing exp(-x).
{ "language": "en", "url": "https://stackoverflow.com/questions/7573229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: New Open Graph Beta meta tags? I cannot find confirmation on any of the docs pages - does the new Open Graph Beta include new meta tags, other than those defined on the OGP page? A: You can find a list of the OG: tags Facebook is using mid-way through their documentation page at http://developers.facebook.com/docs/beta/opengraph/tutorial/ While it's close, there are a few tags not shown on the OGP page such app_id which is obviously required. Type is also used to hold the namespace for the action rather any descriptor. In addition as you define actions & objects [dates, prices, additional string fields, etc] you can use corresponding tags to provide data for them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: json for parsing video for iOS I have a video file stored in json(in a URL), that requires a jsonp parse request to play, and I need to do this in an iPad app. I am not sure where to start, I know how to parse data with json. But I need to figure out how to parse video and then play it in an app. Thanks! EDITS:is this what you guys mean: SBJSON *json = [[SBJSON new] autorelease]; MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[json objectWithString:responseString ]]; //NSArray *luckyNumbers = [json objectWithString:responseString error:&error]; [responseString release]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:player]; //---play partial screen--- player.view.frame = CGRectMake(0, 0, 200, 200); [self.view addSubview:player.view]; //---play movie--- [player play]; A: use SBJSON Parser http://code.google.com/p/json-framework/ after fetching the video URL, if the URL is on http live streaming, you dont need to download it explicitly. Just create: MPMoviePlayerController's objet and use initWithContentURL. then present it on screen. It will automatically stream the video for you. if the video is not on http live streaming, you should follow what @Nikita have mentioned. A: Use any JSON Parser like JSONkit, YAJL, TouchJSON to parse your JSON data for the video URL. Then download that video and write to disk using NSURLConnection delegate methods or you can use ASIHTTP. Then play the downloaded video using MPMoviePlayerController. A: I just had the XNL format changed to store a URL call for the video instead of it being in a JSON file
{ "language": "en", "url": "https://stackoverflow.com/questions/7573242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP reload page when adding forms (maybe needs ajax) Sorry for maybe incorrect title for the topic, but this is the best that I came up with. So, I'm building admin panel for a website. I have a page, and in some part of the page, i'd like to refresh it and load another form. let's say add a schedule, and somewhere down on the page I'd like to have this form displayed as soon as the link is clicked. when a user saves it, I'd like that form to disappear and and in stead of that to have a list displaying all of the schedules. I don't want to use frames - I'm not a supporter of frames. The panel is built using PHP. Maybe this might be achived with Ajax? If yes -> How? any link to good example or tutorial. A: yes this will be solved with ajax. Here is a code example when the page is supposed to refresh $('#button').click(function() { $.ajax({ url: 'path/to/script.php', type: 'post', dataType: 'html', // depends on what you want to return, json, xml, html? // we'll say html for this example data: formData, // if you are passing data to your php script, needed with a post request success: function(data, textStatus, jqXHR) { console.log(data); // the console will tell use if we're returning data $('#update-menu').html(data); // update the element with the returned data }, error: function(textStatus, errorThrown, jqXHR) { console.log(errorThrown); // the console will tell us if there are any problems } }); //end ajax return false; // prevent default button behavior }); // end click jQuery Ajax http://api.jquery.com/jQuery.ajax/ Script explained. 1 - User clicks the button. 2 - Click function initiates an XHR call to the server. 3 - The url is the php script that will process the data we are sending based on the values posted. 4 - The type is a POST request, which needs data to return data. 5 - The dataType in this case will be html. 6 - The data that we are sending to the script will probably be a serialization of the form element that is assigned to the variable formData. 7 - If the XHR returns 200, then log in the console the returned data so we know what we are working with. Then place that data as html inside the selected element (#update-menu). 8 - If there is an error have the console log the error for us. 9 - Return false to prevent default behavior. 10 - All done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIActivityIndicatorView not working when added to UITableView I'm trying to add a UIActivityIndicatorView to the center of my UITableView while it waits for the UITableViews data to load. I am doing this as follows: UIActivityIndicatorView *activityIndicatorTemp = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhiteLarge]; [activityIndicatorTemp setCenter:[[self tableView] center]]; [self setActivityIndicator: activityIndicatorTemp]; [activityIndicatorTemp release]; [[self tableView] addSubview:activityIndicator]; [activityIndicator startAnimating]; However the activity indicator is not showing up at all when I launch the code. I'd like to do it programmatically, any suggestions on how to fix this or why it isn't working? A: please move [activityIndicatorTemp release]; after addSubview: [[self tableView] addSubview:activityIndicator]; A: The problem here is when I was setting the location of the activityindicator. I did this before the tableview had been initialized. [activityIndicatorTemp setCenter:[[self tableView] center]]; I removed the above and it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access the window object from the document object Is it possible to access the window object directly from the document object in Javascript? For example: // window.frames[0] returns the document object of the first frame or iframe found on the page myFunc(window.frames[0]); function myFunc(doc) { // I want to do something along these lines: var wnd = doc.getWindow(); alert("Found frame: " + wnd.name); for (var i=0; i<wnd.frames.length; i++) { myFunc(wnd.frames[i]); } } I can't use jQuery for this, sorry. A: According to the MDN documentation you should already be getting the window with window.frames[0]. If you want the actual document you need to grab the actual frame element and dig into the document. var firstFrame = document.getElementsByTagName( "iframe" )[ 0 ]; firstFrame.contentWindow; // The window firstFrame.contentWindow.document; // The document Note: I believe contentWindow isn't supported in very early versions of Safari (pre-3.0 IIRC)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Right way to set the OAuth Authorization header? I want to set a request header for a url xyz.com is it the right way to set it in php? header('Authorization: AuthSub token="xxxxxx"'); header('location:https://www.google.com/accounts/AuthSubRevokeToken'); I am trying to set the header for this URL for a call.But the Authorization: AuthSub header doesnt shows up in the request headers section of the FireFox NET panel.Which is used to show the requests. Any idea about it? Thanx. I was using curl previously,But it didnt seemed to issue any request as i cant see it in the NET panel of FireFox. Code is as follows: $curl = curl_init(); curl_setopt($curl, CURLOPT_URL,"https://www.google.com/accounts/AuthSubRevokeToken"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FAILONERROR, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: AuthSub token="1/xxx"' )); $result = curl_exec($curl); curl_close($curl); echo 'hererer'.$result;exit; A: header sets response headers, not request headers. (If you were trying to send a HTTP request elsewhere, it would have no effect.) Please also note what the manual says about Remember that header() must be called before any actual output is sent, .... And turn on error_reporting(E_ALL); before using header() to see if that is the issue for you. A: Header names and values need to be separated by one colon plus a space, so the location "header" is just wrong, it should be: header('Location: https://www.google.com/accounts/AuthSubRevokeToken'); (It's common to write the case this way, too, but not a need) Next to that the header function is setting response headers, not request headers. So you're basically using the wrong tool. In PHP you can not set request headers, that's part of the client (e.g. browser), not the server. So header just looks wrong here. Which HTTP client are you using? A: A call, as in using CURL to request another page? The header() function applies only for web-browser<->server communications. It cannot affect any requests your server-side script does to other webservers. For that, you need to modify the particular method you're using, e.g. curl or streams. For curl, see CURLOPT_HTTPHEADER here: http://php.net/curl_setopt
{ "language": "en", "url": "https://stackoverflow.com/questions/7573251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Method for runtime comparison of two programs' objects I am working through a particular type of code testing that is rather nettlesome and could be automated, yet I'm not sure of the best practices. Before describing the problem, I want to make clear that I'm looking for the appropriate terminology and concepts, so that I can read more about how to implement it. Suggestions on best practices are welcome, certainly, but my goal is specific: what is this kind of approach called? In the simplest case, I have two programs that take in a bunch of data, produce a variety of intermediate objects, and then return a final result. When tested end-to-end, the final results differ, hence the need to find out where the differences occur. Unfortunately, even intermediate results may differ, but not always in a significant way (i.e. some discrepancies are tolerable). The final wrinkle is that intermediate objects may not necessarily have the same names between the two programs, and the two sets of intermediate objects may not fully overlap (e.g. one program may have more intermediate objects than the other). Thus, I can't assume there is a one-to-one relationship between the objects created in the two programs. The approach that I'm thinking of taking to automate this comparison of objects is as follows (it's roughly inspired by frequency counts in text corpora): * *For each program, A and B: create a list of the objects created throughout execution, which may be indexed in a very simple manner, such as a001, a002, a003, a004, ... and similarly for B (b001, ...). *Let Na = # of unique object names encountered in A, similarly for Nb and # of objects in B. *Create two tables, TableA and TableB, with Na and Nb columns, respectively. Entries will record a value for each object at each trigger (i.e. for each row, defined next). *For each assignment in A, the simplest approach is to capture the hash value of all of the Na items; of course, one can use LOCF (last observation carried forward) for those items that don't change, and any as-yet unobserved objects are simply given a NULL entry. Repeat this for B. *Match entries in TableA and TableB via their hash values. Ideally, objects will arrive into the "vocabulary" in approximately the same order, so that order and hash value will allow one to identify the sequences of values. *Find discrepancies in the objects between A and B based on when the sequences of hash values diverge for any objects with divergent sequences. Now, this is a simple approach and could work wonderfully if the data were simple, atomic, and not susceptible to numerical precision issues. However, I believe that numerical precision may cause hash values to diverge, though the impact is insignificant if the discrepancies are approximately at the machine tolerance level. First: What is a name for such types of testing methods and concepts? An answer need not necessarily be the method above, but reflects the class of methods for comparing objects from two (or more) different programs. Second: What are standard methods exist for what I describe in steps 3 and 4? For instance, the "value" need not only be a hash: one might also store the sizes of the objects - after all, two objects cannot be the same if they are massively different in size. In practice, I tend to compare a small number of items, but I suspect that when automated this need not involve a lot of input from the user. Edit 1: This paper is related in terms of comparing the execution traces; it mentions "code comparison", which is related to my interest, though I'm concerned with the data (i.e. objects) than with the actual code that produces the objects. I've just skimmed it, but will review it more carefully for methodology. More importantly, this suggests that comparing code traces may be extended to comparing data traces. This paper analyzes some comparisons of code traces, albeit in a wholly unrelated area of security testing. Perhaps data-tracing and stack-trace methods are related. Checkpointing is slightly related, but its typical use (i.e. saving all of the state) is overkill. Edit 2: Other related concepts include differential program analysis and monitoring of remote systems (e.g. space probes) where one attempts to reproduce the calculations using a local implementation, usually a clone (think of a HAL-9000 compared to its earth-bound clones). I've looked down the routes of unit testing, reverse engineering, various kinds of forensics, and whatnot. In the development phase, one could ensure agreement with unit tests, but this doesn't seem to be useful for instrumented analyses. For reverse engineering, the goal can be code & data agreement, but methods for assessing fidelity of re-engineered code don't seem particularly easy to find. Forensics on a per-program basis are very easily found, but comparisons between programs don't seem to be that common. A: (Making this answer community wiki, because dataflow programming and reactive programming are not my areas of expertise.) The area of data flow programming appears to be related, and thus debugging of data flow programs may be helpful. This paper from 1981 gives several useful high level ideas. Although it's hard to translate these to immediately applicable code, it does suggest a method I'd overlooked: when approaching a program as a dataflow, one can either statically or dynamically identify where changes in input values cause changes in other values in the intermediate processing or in the output (not just changes in execution, if one were to examine control flow). Although dataflow programming is often related to parallel or distributed computing, it seems to dovetail with Reactive Programming, which is how the monitoring of objects (e.g. the hashing) can be implemented. This answer is far from adequate, hence the CW tag, as it doesn't really name the debugging method that I described. Perhaps this is a form of debugging for the reactive programming paradigm. [Also note: although this answer is CW, if anyone has a far better answer in relation to dataflow or reactive programming, please feel free to post a separate answer and I will remove this one.] Note 1: Henrik Nilsson and Peter Fritzson have a number of papers on debugging for lazy functional languages, which are somewhat related: the debugging goal is to assess values, not the execution of code. This paper seems to have several good ideas, and their work partially inspired this paper on a debugger for a reactive programming language called Lustre. These references don't answer the original question, but may be of interest to anyone facing this same challenge, albeit in a different programming context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you minify and/or compress JavaScript that is in a php file? I am looking at optimization options, and after checking SO questions, I don't quite see an answer for what I am trying to do. Hopefully that doesn't indicate that what I am doing is a bad practice! I have an intranet application that loads page content via ajax calls to php files. A lot of the php files have a mixture of php, JavaScript, even some HTML, specific to the interface functionality that they load into the main interface. I was wondering about minifying or compressing these files. Is there a way to do it, or am I stuck because I have mixed languages? Update: Concerning accepted answer: I have accepted wildpeaks answer because I think it most closely answers my original question. However, this is one of those times when I wish I could accept two answers because I think the answer Igor Zinov'yev provided has given me perhaps a more important design decision to think about. For that reason I have given a +1 to his answer, as I imagine others will too. Hope that makes sense and is within the SO rules. A: Your PHP script generates the Javascript code, so it can minify the code before outputting it: generate the code in a variable, then pass that variable to the minifier, and only then output to the browser. Here's a PHP library for that. A: You are starting your optimization off the wrong end. Obviously if you have hard-coded JavaScript, HTML and whatever else inside your PHP files, you seriously need to refactor the code. But even if you don't, you shouldn't minify the code in place because it would be even harder to maintain. Pull it out of there, start with small steps, and you will get there eventually. UPDATE: I thought of replying with a comment, but instead decided to elaborate on why I answered your question this way here. I'm talking here about separation of concerns. Your server-side code files are no place for the client-side code. All solutions that do this that I have seen so far sooner or later turn into an unmaintainable mess. If you want to return a piece of HTML code, put it into a template and supply the template with variables that are specific for this current situation. You can do that with Smarty. This way you get among others the following benefits: * *No repeating pieces of markup over and over - there are template loops for that *A possibility to re-use existing templates in several places *Developers working with templates do not need to get into your server-side code *And your server-side code gets cleaner, smells nice too! Later on when you separate logic from presentation maybe you will find that you don't need to send JavaScript code with HTML snippets. Maybe you will create a single JS engine (that you will minify on build) and will only have to trigger certain events upon load.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Problems doing syscall hooking I use the following module code to hooks syscall, (code credited to someone else, e.g., Linux Kernel: System call hooking example). #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/unistd.h> #include <asm/semaphore.h> #include <asm/cacheflush.h> void **sys_call_table; asmlinkage int (*original_call) (const char*, int, int); asmlinkage int our_sys_open(const char* file, int flags, int mode) { printk(KERN_ALERT "A file was opened\n"); return original_call(file, flags, mode); } int set_page_rw(long unsigned int _addr) { struct page *pg; pgprot_t prot; pg = virt_to_page(_addr); prot.pgprot = VM_READ | VM_WRITE; return change_page_attr(pg, 1, prot); } int init_module() { // sys_call_table address in System.map sys_call_table = (void*)0xffffffff804a1ba0; original_call = sys_call_table[1024]; set_page_rw(sys_call_table); sys_call_table[1024] = our_sys_open; return 0; } void cleanup_module() { // Restore the original call sys_call_table[1024] = original_call; } When insmod the compiled .ko file, terminal throws "Killed". When looking into 'cat /proc/modules' file, I get the Loading status. my_module 10512 1 - Loading 0xffffffff882e7000 (P) As expected, I can not rmmod this module, as it complains its in use. The system is rebooted to get a clean-slate status. Later on, after commenting two code lines in the above source sys_call_table[1024] = our_sys_open; and sys_call_table[1024] = original_call;, it can insmod successfully. More interestingly, when uncommenting these two lines (change back to the original code), the compiled module can be insmod successfully. I dont quite understand why this happens? And is there any way to successfully compile the code and insmod it directly? I did all this on Redhat with linux kernel 2.6.24.6. A: I think you should take a look to the kprobes API, which is well documented in Documentation/krpobes.txt. It gives you the ability to install handler on every address (e.g. syscall entry) so that you can do what you want. Added bonus is that your code would be more portable. If you're only interested in tracing those syscalls you can use the audit subsystem, coding your own userland daemon which will be able to receive events on a NETLINK socket from the audit kthread. libaudit provides a simple API to register/read events. If you do have a good reason with not using kprobes/audit, I would suggest that you check that the value you are trying to write to is not above the page that you set writable. A quick calculation shows that: offset_in_sys_call_table * sizeof(*sys_call_table) = 1024 * 8 = 8192 which is two pages after the one you set writable if you are using 4K pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cocos2D: Passing a CGPoint through CCCallFuncND What is the appropriate way to call a method with an action, and what should the method itself look like for passing a CGPoint parameter? I've tried to look up examples online without much luck, so I've been pretty much guessing. What I have tried is this for calling it: CGPoint spriteCoord = saveStation.sprite.position; id a1=[CCMoveTo actionWithDuration:.4 position:ccp(saveStation.sprite.position.x,saveStation.sprite.position.y)]; id actionSaveStationReaction = [CCCallFuncND actionWithTarget:self selector:@selector(saveStationReaction : data:) data:&spriteCoord]; [hero.heroSprite runAction:[CCSequence actions:a1, actionSaveStationReaction, nil]]; And the method itself: -(void) saveStationReaction:(id)sender data:(void *)data { CGPoint spriteCoord = (void *)data; //error: Invalid initializer NSLog(@"spriteCoord x = %f", spriteCoord.x); NSLog(@"spriteCoord y = %f", spriteCoord.y); } A: The proper way to send a CGPoint (or any non-id type like C structs) to a method that takes an id as parameter (any method that uses performSelector) is by wrapping it in an NSValue object: NSValue* value = [NSValue valueWithBytes:&spriteCoord objCType:@encode(CGPoint)]; In the method that is being called you can retrieve the point from the NSValue object by casting the data pointer to NSValue* and calling getValue: -(void) saveStationReaction:(id)sender data:(void *)data { CGPoint spriteCoord; [((NSValue*)data) getValue:&spriteCoord]; NSLog(@"spriteCoord x = %f", spriteCoord.x); NSLog(@"spriteCoord y = %f", spriteCoord.y); } A: GamingHorror's suggestion on wrapping the CGPoint in an NSValue is spot-on. But there's a simpler way than using valueWithByte:objCType: method: valueWithCGPoint:, assuming you are coding for iOS and not MacOS. NSValue *spriteCoordValue = [NSValue valueWithCGPoint:spriteCoord]; [CCCallFuncND actionWithTarget:self selector:@selector(saveStationReaction:data:) data:spriteCoordValue]; // and .. -(void) saveStationReaction:(id)sender data:(void *)data { CGPoint spriteCoord = [(NSValue *)data CGPointValue]; NSLog(@"spriteCoord x = %f", spriteCoord.x); NSLog(@"spriteCoord y = %f", spriteCoord.y); } NSValue can also deal with CGSize and CGRect using similar way. A: You can't typecast to a CGPoint with that syntax. Try.... CGPoint *spriteCoord = data; CGFloat ptX = spriteCoord->x; CGFloat ptY = spriteCoord->y; I tried... CGPoint* spriteCoord = (CGPoint)data; which didn't work and I guess expectedly so. Try my first suggestion and see if that works for you. It did compile for me but I'm not sure how it will execute and that may depend on your particular situation. A: CGPoint is a struct, not an object, so you can't pass it directly to any of the CCCallFunc's. There are several ways of dealing with this, but the quickest converts the CGPoint to NSString using NSStringFromCGPoint, passing the string, then converting it back to a CGPoint using CGPointFromString.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jsTree + jsTreeGrid -> render icons for newly created node I successfully implements jsTree + jsTreeGrid in admin panel for managing categories for products. The only one problem is, that when i create new node via right mouse button context menu, the newly created row does not contain columns with icons set in jsTreeGrid panel. The icons are ID based (linked to other pages), therefore while rendering icons code have to know ID of newly created node. Please note: After page refresh icons for new node are visible. Of course. Any help is really appreciated. A: What about programmatically refreshing the jsTree after adding new node? Search for refresh in doc for core
{ "language": "en", "url": "https://stackoverflow.com/questions/7573262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Image to Byte[] I have an image that sits inside some folder in my MVC3 application. In my controller, how do I convert that image into a Byte array. A: byte[] buffer = File.ReadAllBytes("foo.png"); and because that's inside a controller you probably want to calculate the path relative to the root: string imageFile = Path.Combine(Server.MapPath("~/App_Data"), "foo.png"); byte[] buffer = File.ReadAllBytes(imageFile);
{ "language": "en", "url": "https://stackoverflow.com/questions/7573263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to write to file in an multithreaded environment I have a program that runs on multithread but all of them need to save results to same text file I get access violation error how can i avoid doing that A: Wrap file IO into a lock statement: private static object _syncRoot = new object(); and then: lock(_syncRoot) { // do whatever you have to do with this file } A: Take a look at the lock statement: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx A: The simplest is to simply make sure you have some locking construct (mutex, monitor, etc) against access to the file, then each thread can access it in isolation. This could either be accessing the same underlying Stream/TextWriter/etc, or could be opening/closing the file inside the locked region. A more complex approach would be to have a dedicated writer thread, and a synchronised work queue. Then all threads can add to the queue and a single thread draughts and writes to the file. This means your main threads are only blocked while adding to a queue (very brief), rather than blocked on IO (slower). However, note that if the process exits abnormally, data in the queue may be lost. A: I would recommend reading up on the ReaderWriterLock class or the ReaderWriterLockSlim class which is faster but has some gotchas, I believe it would suit your needs perfectly. ReaderWriterLock ReaderWriterLockSlim
{ "language": "en", "url": "https://stackoverflow.com/questions/7573264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Just switched to JRuby, having some trouble getting rails started I just installed JRuby on my mac using the following command: rvm install jruby-1.6.4 And then installed rails using the following command: rvmsudo gem install rails When I try to start my server, I get the following error: Invalid memory access of location 0x0 rip=0x10fc4c5f9 [1] 14068 segmentation fault rails server Has anyone seen this before? What should I do? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is the difference between ? and T in class and method signatures? why does public interface ArrayOfONEITEMInterface <T extends ONEITEMInterface>{ public List<T> getONEITEM(); } compile, but not public interface ArrayOfONEITEMInterface <? extends ONEITEMInterface>{ public List<?> getONEITEM(); } what is the difference between ? and T in class and method signatures? A: T is a placeholder for a type that will be provided by an implementing or instantiating class. ? is a placeholder saying "I don't know or care what the generic type is" generally used when the work you'll do on the container object doesn't need to know the type. The reason you can't use '?' in the class/interface definition is because there's the value is saying defining the name of the placeholder (and the type will be provided elsewhere). Putting a '?' doesn't make sense. Furthermore, the placeholder doesn't need to be T, it can any standard Java variable. By convention, it is one capital character, but need not be. A: ? allows you to have a list of Unknown types, where as T requires a definite type. A: ? is a wildcard and means any subclass of ONEITEMInterface including itself. T is a specific implementation of ONEITEMInterface in this case. Since ? is a wildcard, there is no relation between your ? in the class declaration and the ? in your method declaration hence it won't compile. Just List<?> getONEITEM(); will compile though. The first scenario means the entire class can handle exactly one type of Bar per instance. interface Foo<T extends Bar> { List<T> get(); } The second scenario allows each instance to operate on any subtype of Bar interface Foo { List<? extends Bar> get() } A: The clause <T extends ONEITEMInterface> is declaring a type parameter named T. This allows your generic type, ArrayOfONEITEMInterface, to refer to the parameter elsewhere. For example you can declare a method like void add(T t). Without naming the type parameter, how would you refer to it? If you never refer to the type parameter, why is your type generic in the first place? For example, you don't need a parameterized type to do something like this: public interface ArrayOfONEITEMInterface { List<? extends ONEITEMInterface> getONEITEM(); } It doesn't make sense to declare an anonymous type parameter, so it is syntactically illegal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How do I lock files using fopen()? I wonder if there is any way to lock and unlock a file in Linux when I open a file using fopen (not open)? Based on Stack Overflow question C fopen vs open, fopen is preferred over open. How can I implement my own file lock (if possible) by creating and deleting lock files? A: Files can be locked by using flock(). Its syntax is #include <sys/file.h> #define LOCK_SH 1 /* shared lock */ #define LOCK_EX 2 /* exclusive lock */ #define LOCK_NB 4 /* don't block when locking */ #define LOCK_UN 8 /* unlock */ int flock(int fd, int operation); First file is opened using fopen() or open(). Then this opened file is locked using flock() as given below int fd = open("test.txt","r"); int lock = flock(fd, LOCK_SH); // Lock the file . . . // . . . . // Locked file in use // . . . . int release = flock(fd, LOCK_UN); // Unlock the file . . . A: I would strongly disagree with the claim that fopen is prefered over open. It's impossible to use fopen safely when writing a file in a directory that's writable by other users due to symlink vulnerabilities/race conditions, since there is no O_EXCL option. If you need to use stdio on POSIX systems, it's best to use open and fdopen rather than calling fopen directly. Now, as for locking it depends on what you want to do. POSIX does not have mandatory locking like Windows, but if you just want to ensure you're working with a new file and not clobbering an existing file or following a symlink, use the O_EXCL and O_NOFOLLOW options, as appropriate. If you want to do cooperative locking beyond the initial open, use fcntl locks. A: Note that in below code fopen will fail (and return NULL) if the lock file /var/lock/my.lock doesn't exist. FILE* f = fopen("/var/lock/my.lock", "r"); int result = flock(fileno(f)), LOCK_SH); Use fopen with w+ if you need the lockfile to be created if it doesn't exist. FILE* f = fopen("/var/lock/my.lock", "w+"); int result = flock(fileno(f)), LOCK_SH); A: In Linux, if you need a file descriptor (e.g., to pass to a file-locking primitive), you can use fileno(FILE*) to retrieve it. After retrieving the file descriptor, you can use it as if it had been returned by open. For example, instead of int fd = open("myfile.txt", flags); int result = flock(fd, LOCK_SH); you could equally well do this: FILE* f = fopen("myfile.txt", "r"); int result = flock(fileno(f)), LOCK_SH); Note that fileno is defined in the POSIX standard, but not in C or C++ standards. As for your second question, the Linux open() man page has this to say: The solution for performing atomic file locking using a lockfile is to create a unique file on the same file system (e.g., incorporating hostname and pid), use link(2) to make a link to the lockfile. If link() returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful. A: If you wish to implement your own lock simply, I suggest Rob's answer of using flock. If you wish to implement it in a complex manner, such as for high availability, you can try something like using a thread to touch a file at a regular interval. All other programs wanting to lock the file should also check the file to see if its update time has been updated in at another fixed, but larger interval (the larger part is important). This is probably overkill for most applications, but it handles things such as crashes, freezes, etc. much better than flock. A: There is another way with open() function, but I'm not sure about this called locked file. I am using file permissions to open a file. The code is here: #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #define FILE_NAME "hello.txt" int main() { int fd; fd = open(FILE_NAME, O_CREAT, S_IRWXU); // Error checking if(fd == -1){ perror("[error]\n"); } else{ printf("[file is opened]\n"); } return 0; } I used a flag for permissions (third argument). This flag gives read, write and execute permissions to the user. $ls -alh total 24K drwxrwxr-x 2 arien arien 4.0K Dec 28 20:56 . drwxrwxr-x 18 arien arien 4.0K Dec 27 22:20 .. -rwxrwxr-x 1 arien arien 8.5K Dec 28 20:56 fopen -rw-rw-r-- 1 arien arien 290 Dec 28 20:56 fopen.c -rwx------ 1 arien arien 0 Dec 28 20:55 hello.txt A little tip: If you are using Ubuntu or Debian, you can see the description of functions with man [function_name] man pages of open() function. A: The below code is not letting me lock the file using lockf, flock works fine though #include <iostream> #include <unistd.h> #include<thread> #include <vector> #include <sys/file.h> #include <fcntl.h> #include <string.h> using namespace std; void append() { FILE *fp=fopen("a.txt","a"); if(fp) { cout<<lockf(fileno(fp),F_LOCK,0)<<endl; //flock(fileno(fp), LOCK_EX); fprintf(fp,"abcdefghijklmnopqrstuvwxyz\n");fflush(fp); sleep(1); fprintf(fp,"^$^&%&*&^&*(*)_*)_()_*&***&(\n");fflush(fp); fclose(fp); } else { printf("null\n"); } } int main() { fclose(fopen("a.txt","w")); //return 0; vector<thread*> v; //#pragma omp parallel for for(int i=0;i<1000;++i) { v.push_back(new thread(append)); //append(); } for(auto y:v) { y->join(); delete y; } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Adding class attribute from code behind I have the following code: div1.Attributes.Add("class", "displayNone"); it works on page load but doesn't on an OnClick event. This is because my html <div id="div1"></div> seems to change to: <div id="div1_ucSomeControl_SoemthingElse"></div> after the page has been rendered. How can I get around this? A: I don't think that the ID of the control matters in this case. You may be running into this issue because the class attribute already exists. Try this instead: div1.Attributes["class"] = "displayNone"; A: <div id="div1" runat ="server"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> </div> code behind: protected void Button1_Click(object sender, EventArgs e) { div1.Attributes.Add("class", "displayNone"); } this will be work. A: Normally you should do this kind of attributes manupilation/addition in the Page_PreRender event: div1.Attributes.Add("class", "displayNone"); anyway when you say it does not work in the OnClick event you still meant Server side I guess; because on client side you cannot execute that code in that way. Server side, usage of the object by id like div1 should always work, in codebehind objects's ids are not changed through the page life cycle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Perl threads and hash keys If a have a hash shared between 2 threads and if I ensure that thread1 just interacts with key1 and thread2 just with key2, can I assume it as thread-safe? If so, do I need to create key1 and key2 before share the hash over the treads or can each thread create its own key? Is there any place where I can get some information about Perl hashes internal mechanisms and its behavior with threads? A: A hash is an array of linked lists. A hashing function converts the key into a number which is used as the index of the array element ("bucket") into which to store the value. More than one key can hash to the same index ("collision"), so the linked lists handle this case. If a thread modifies one of the linked lists (e.g. to add an element) while another is navigating it (e.g. to fetch an element), It could lead to problems. As such, adding elements is not safe. You could address this by precreating the elements of the hash (or array). So that leaves the question of whether accessing existing elements is safe or not. It might be, but there is no guarantee of that. You might find these interesting: * *illguts goes into internal details of Perl data structures. *Devel::Peek is a very useful tool. A: Yes, as long as different threads don't step over each other's keys, you're fine. I use a similar idea with arrays (eg having each processing thread record how many items it has processed so that a reporter thread can add up the entries from the array every second or so and report the result).
{ "language": "en", "url": "https://stackoverflow.com/questions/7573288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bing maps with world spanning polygons not working in IE7 and IE8 I have an application using Bing Maps that draws polygons on a map. For most polygons, the system works fine, and shows the shape correct. However, with huge polygons (covering almost the entire planet), I get errors in IE7 and IE8. The errors are related to a setSize method within the map script (veapicore.js). The map works correctly in IE9 and FF (still working on Chrome). The page is [http://data.nbr.org/Mapping/chinamissilerange]. The first two checkboxes work fine, the third is where the problem is (803 Brigade Base 55). I can't figure out what could be causing the problem. Does anyone know what this issue could be? Thanks, Erick A: I have solved this question. It turns out that IE7 and IE8 have issues with this particular API when everything isn't finished loading. Moving the map javascript to $(window).load fixed the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Semaphores in operating system Well, what exactly changes the context of processes. Say i have a algo, in which say S=0; begin signal(S); <critical> wait(S); end Now in this, when my signal is executed, will the process be preempted and the process from the queue will be executed? A: I think what you want to do this S=0; begin wait(S); <critical> signal(S); end First wait for some signal(locking, or signal from some other process) and then enter into the critical section. And once out of the critical section, signal the other waiting processes to wake up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does Aspect Oriented Programming (AOP) influence code quality? Aspect Oriented Programming (AOP) seems like an interesting concept. At first I was pretty enthusiastic about it, but as I read more and saw the use cases people were describing I grew disappointed. A lot of sites I saw, plus a presentation from the developers of AspectC++, presented use cases that I found rather dubious. They talked about how AOP can be used to do error handling (throwing exceptions), do bounds checking on parameters and return values, return safe null objects in case something goes wrong, security, etc. Are these just bad examples (and not actual use cases), or am I missing something? How are you supposed to be aware of what's happening when you call a function? Virtually anything can happen, depending on what aspects you decide to apply. Isn't that going to mess up things really really badly? What about API documentation, how am I supposed to write that? So far the only good use cases for AOP I've seen are things like logging or profiling — things that don't influence the actual logic flow and serve only as debugging tools. Is AOP useful for anything else other than debugging mechanisms? A: AOP is most useful when you have concerns that aren't relevant to the main concern of your application (called orthogonal concerns). It can be super handy when you have to add a concern to existing code (say security to something that was built for internal private use) or have to add functionality that for whatever reason just doesn't fit into your domain model without really obscuring your business logic. I wouldn't use it anywhere you have to wonder what is happening when you call a function. That seems like code smell to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SqLite3 NFS mount issue with locking - can I use something like CIFS nobrl? I'm having a locking problem where an SQLITE3 databse is permanently locked when created on an NFS file system. I have read that an option called nobrl can help this issue when the file system in question is CIFS. (its an option to the mount command). From: http://linux.die.net/man/8/mount.cifs nobrl Do not send byte range lock requests to the server. This is necessary for certain applications that break with cifs style mandatory byte range locks (and most cifs servers do not yet support requesting advisory byte range locks). Is there any way to stop byte-range-lock requests in NFS if they occur, or am I running in the wrong direction by even thinking about this? I'm happy to change the mount command as was done for the CIFS solution. A: I recommend to open you sqlite db by software with nolock parameter enabled, golang exg.: sql.Open("sqlite3", "file:/media/R/Databases//your.db?nolock=1") while /media/R is a mounted windows nfs-network-drive. Be carefull because you have to lock your db interactions by software otherwise you could corrupt your db, when accessing it simultaneously. You can read more about sqlite parameters here: https://www.sqlite.org/c3ref/open.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7573301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can you do entity inheritance in EF on an entity that is mapped to stored procedures? I have a question about inheritance in Entity Framework 4. We are using a database-first approach and would like to restructure our model to use inheritance. Here is a white board mock up of the hierarchy we would like to use in our model. Image 1 In case those scribbles are not very readable, it's something like this. USER <- PROVIDER USER <- VENDOR PROVIDER <- EMPLOYEE So USER is the base class for providers and vendors. And employee then inherits from provider. I found a couple great articles describing Table-Per-Hierarchy inheritance and Table-Per-Type inheritance. They seem simple enough but both ways require an entity to be mapped to a table or tables. What if you have an entity that is mapped entirely to stored procedures? Image 2 Is it still possible to do inheritance in EF even if an entity is mapped to stored procedures? How would that look? What kinds of stored procedures would we need to have to accomplish this? If it's possible we really just need pointed in the right direction. A: I have searched and searched and finally arrived at the conclusion that it is not possible to do inheritance with entities that are mapped to stored procedures. So unless someone can prove otherwise, I'm marking this as the answer. A: I am using a completely stored procedure mapped repository architecture in my MVC project. In that we are not using the entity framework, instead of that we use Microsoft Enterprise Library. We are using the methods from it. From my experience, The repository contains only methods for data manipulation using stored procedures. The Tables are mapped to Models. There are ViewModels which are custom Model classes for handling properties which are defined as custom in the project. There is one service layer to separate the Controllers and Repositories. So I think you can adopt the method of repository mapped entirely to stored procedures
{ "language": "en", "url": "https://stackoverflow.com/questions/7573305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Apps Script UrlFetchApp Exception Im in the process of creating a custom timesheet using Google Docs and Google Apps Script. One of the requirements is to save the timsheet as a PDF when the user submits the timesheet. Heres what I currently have: function createPdf(){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var oauthConfig = UrlFetchApp.addOAuthService("google"); oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken"); oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/"); oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken"); oauthConfig.setConsumerKey("anonymous"); oauthConfig.setConsumerSecret("anonymous"); var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&gid=0&portrait=true" +"&exportFormat=pdf"; var requestData = { "oAuthServiceName": "google", "oAuthUseToken": "always" }; var result = UrlFetchApp.fetch(url, requestData); var content = result.getBlob(); var file = DocsList.createFile(content); return file; } When debugging the script, I get the following error: Unexpected exception upon serializing continuation Any help would be appreciated. A: After some further digging, I found this solution: function createPdf(){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var pdf = ss.getAs("application/pdf"); var file = DocsList.createFile(pdf); file.rename("Test"); return file; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to run queries in the background I have listed of products with different category. I have to sort them. Because of the queries, It is taking more time to load. Between two activities, the screen is coming black. I want to run the query in the background. How can I do that and how to use its result in main activity? private class InsertTask extends AsyncTask { String cat; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(String... params) { Boolean success = false; try { category(cat); success = true; } catch (Exception e) { if(e.getMessage()!=null) e.printStackTrace(); } return success; } @Override protected void onPostExecute(Boolean success) { super.onPostExecute(success); } private void category(String category) { try{ Cursor1 = mDbHelper.fetchcategory(category); }catch(Exception e){ Log.v("Excep", ""+e); } } And when called InsertTask task = new InsertTask(); task.execute(); I have listed the category in buttons. How can I get the values then? A: You should use AsyncTask for that. And some more info. A: Its good you have thought of AsyncTask. Firstly, you can declare this class as inner in you class activity (if you haven't previously did) and so you are able to access you view class members. You can do this also by creating thread and one handler that will be used to update your UI components. Remember that if you use threads you'll need to lock/unlock your database object because of the thread safety(if any other thread is accessing the database for any reason). Read more about thread safety of dbs. A: I was doing some searching myself, and I came across this read, its rather long but looks extremely helpful, with lots of code examples. (I bookmarked it for myself). Threads, Async, and Handlers O MY! But some form of threading is the ticket. From Android dev. (My favorite code snippet) public void onClick(View v) { new Thread(new Runnable() { public void run() { //Do Work here } }).start(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook Canvas application with Rails 3: Detect if user is a fan Hello and excuse me again I am trying to know if user in my canvas application is fan or not. I am working with Rails 3 with fbgraph gem. So in my controller I try: def find_auth if params.has_key? :signed_request session[:signed_request] = params[:signed_request] @auth = authorizor.from_signed_request params[:signed_request] decode_signed_request = Canvas.parse_signed_request(configatron.fb_authentication_app_secret, params[:signed_request]) else @auth = authorizor.from_signed_request session[:signed_request] end end def authorizor FbGraph::Auth.new(configatron.fb_authentication_app_key, configatron.fb_authentication_app_secret) end however decode_signed_request haven´t got page data only is a hash with 3 elements: Algorithm User(age,country and locale) issued_at Depending if the user is fan or not i should render a page or another. If the user is fan show the main content, else i should render a page with a like button. If the user click "like" I should ask for permission in a popup. Thanks in advance. If you need more information please to comment. A: I can solve my problem. In a canvas application this need permissions. However in tab application when i parsed params[:signed_request] exist a key with like information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DB2/iSeries SQL clean up CR/LF, tabs etc I need to find and clean up line breaks, carriage returns, tabs and "SUB"-characters in a set of 400k+ string records, but this DB2 environment is taking a toll on me. Thought I could do some search and replacing with the REPLACE() and CHR() functions, but it seems CHR() is not available on this system (Error: CHR in *LIBL type *N not found). Working with \t, \r, \n etc doesn't seem to be working either. The chars can be in the middle of strings or at the end of them. DBMS = DB2 System = iSeries Language = SQL Encoding = Not sure, possibly EBCDIC Any hints on what I can do with this? A: I used this SQL to find x'25' and x'0D': SELECT <field> , LOCATE(x'0D', <field>) AS "0D" , LOCATE(x'25', <field>) AS "25" , length(trim(<field>)) AS "Length" FROM <file> WHERE LOCATE(x'25', <field>) > 0 OR LOCATE(x'0D', <field>) > 0 And I used this SQL to replace them: UPDATE <file> SET <field> = REPLACE(REPLACE(<field>, x'0D', ' '), x'25', ' ') WHERE LOCATE(x'25', <field>) > 0 OR LOCATE(x'0D', <field>) > 0 A: If you want to clear up specific characters like carriage return (EBCDIC x'0d') and line feed (EBCDIC x'25') you should find the translated character in EBCDIC then use the TRANSLATE() function to replace them with space. If you just want to remove undisplayable characters then look for anything under x'40'. A: Here is an sample script that replaces X'41' by X'40'. Something that was creating issues at our shop: UPDATE [yourfile] SET [yourfield] = TRANSLATE([yourfield], X'40', X'41') WHERE [yourfield] like '%' concat X'41' concat '%' If you need to replace more than one character, extend the "to" and "from" hexadecimal strings to the values you need in the TRANSLATE function. A: Try TRANSLATE or REPLACE. The brute force method involves using POSITION to find the errant character, then SUBSTR before and after it. CONCAT the two substrings (less the undesirable character) to re-form the column. The character encoding is almost certainly one of the EBCDIC character sets. Depending on how the table got loaded in the first place, the CR may be x'0d' and the LF x'15', x'25'. An easy way to find out is to get to a green screen and do a DSPPFM against the table. Press F10 then F11 to view the table is raw, hexadecimal (over/under) format. A: For details on the available functions see the DB2 for i5/OS SQL Reference. A: Perhaps the TRANSLATE() function will serve your needs. TRANSLATE( data, tochars, fromchars ) ...where fromchars is the set of characters you don't want, and tochars is the corresponding characters you want them replaced with. You may have to write this out in hex format, as x'nnnnnn...' and you will need to know what character set you are working with. Using the DSPFFD command on your table should show the CCSID of your fields. A: we struggled a lot to replace the new line char and carriage return from flat file. Finally we used below sql to sort the issue. REPLACE(REPLACE(COLUMN_NAME, CHR(13), ''), CHR(10), '') Try it out CR = CHR(13) LF = CHR(10)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Powershell - assign source code of ASP page to a variable probably it is a silly question, but I couldn't find the answer in Google so far. I need to read the HTML source code of a page http://Mysite/ViewRequest.aspx?request_id=xxx. I've setup following wc = new-object -com internetexplorer.application $wc.visible = $false $wc.navigate2($strGRSpage).Document $wc.silent = $true $wc.visible = $false $GRSstr = $wc.Document.body.IHTMLElement_outerText Unfortunately the IE page pops up, even if I set $wc.silent = $true and $wc.visible = $false. Is there another way (even with HTTP request GET) to retrieve that data without getting the IE page. NOTE. The site http://Mysite/ViewRequest.aspx?request_id=xxx supports just IE and Mozilla. When I tried to use Webclient Class I get always unsupported browser. In VBscript following works (but I want it in Powershell) Set oHTML = CreateObject("Microsoft.XMLHTTP") Set oWeb = CreateObject("InternetExplorer.Application") oHTML.open "GET" , strGRSpage, false oHTML.send strGRStext = oHTML.responseText Many thanks, Marco A: When trying the webclient Class maybe You're just missing to add a "valid" user Agent $wc.Headers.Add("user-agent", "Valid WebClient Header")   A: You just have to add an appropriate user-agent header. For example: $wc = new-object system.net.webclient $wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)") $wc.DownloadFile("http://whatsmyuseragent.com/","d:\index.html") A: After Googling a little bit I found out how to setup my user agent to get the compatibility with IE. Final code is $wc = new-object system.net.webclient $wc.Headers.Add("user-agent", "Windows-RSS-Platform/2.0 (MSIE 9.0; Windows NT 6.1)") $GRSstr = $wc.DownloadString($strGRSpage) Many thanks for your help. Regards, Marco ----- Please mark as answer ------
{ "language": "en", "url": "https://stackoverflow.com/questions/7573326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php counter is being reset each loop I've got a rather complicated set of loops that pulls data out of mysql and compares it to values in an array and increments a counter. When I echo a flag when the counter is incremented, I get a bijilion flags (there're like 2600 records returned from the mysql query). But each time it prints, the counters are always 1 and when I print the counter's value at the end, it shows up as zero. It seems like something is re-setting the counter… code # ARRAY $demographics=array( "region"=>array( "Northeast"=>array('total'=>0,'consented'=>0,'completed'=>0), //more... "West"=>array('total'=>0,'consented'=>0,'completed'=>0) ),"societal envirn"=>array( "Urban"=>array('total'=>0,'consented'=>0,'completed'=>0) ),"age"=>array( '18-19'=>array('total'=>0,'consented'=>0,'completed'=>0), '20-24'=>array('total'=>0,'consented'=>0,'completed'=>0), //more... '55-59'=>array('total'=>0,'consented'=>0,'completed'=>0) ), //more... ); # LOOPS while ($dbrecord = mysql_fetch_assoc($surveydata)) { foreach ( $dbrecord as $dbfield=>$dbcellval ) { foreach ( $demographics as $demographic=>$options ) { foreach ( $options as $option=>&$counter ) { if($demographic==="age"){ list($min,$max) = explode('-', $option); if ($dbcellval >= $min && $dbcellval <= $max){ $counter['total']++; echo '$' . $option . "['total'] = " . $counter['total'] . "<br />"; if ($dbrecord['consent']==="1"){ $counter['consented']++; echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />"; if ($dbrecord['completion status']==="complete") { $counter['completed']++; echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />"; break 3; } // if } // if break 2; } } // if age else if ($option===$dbcellval){ $counter['total']++; echo '$' . $option . "['total'] = " . $counter['total'] . "<br />"; if ($dbrecord['consent']==="1"){ $counter['consented']++; echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />"; if ($dbrecord['completion status']==="complete") { $counter['completed']++; echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />"; break 3; } // if } // if break 2; } // else if $option==$dbcellval } // foreach $options } // foreach $demographics } // foreach $dbrecord } // while sample output $40-44['total'] = 1 $White['total'] = 1 $35-39['total'] = 1 $Northeast['total'] = 1 // the 'total' counter is 1 $Northeast['consented'] = 1 $Northeast['completed'] = 1 $South['total'] = 1 $Northeast['total'] = 1 // notice the 'total' counter is 1 again :( $Northeast['consented'] = 1 $Northeast['completed'] = 1 A: You're defining counter from a foreach instruction, as $value in foreach($foo as $key=>$value), when using the foreach you only have a local copy of $counter. You need to use either foreach($foo as $key=>&$value) or to refer to the full array path of your counter from $demographics. A: You need to reference your array at each level, otherwise you are working on a copy of the data: foreach ( $dbrecord as $dbfield=>$dbcellval ) { foreach ( $demographics as $demographic => &$options ) { foreach ( $options as $option => &$counter ) { if($demographic==="age"){ list($min,$max) = explode('-', $option); if ($dbcellval >= $min && $dbcellval <= $max){ $counter['total']++; A: What if you simply stick with the $demographics variable. i.e. ... foreach ( $options as $option ) { ... $demographics[$option]['total']++; ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7573331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to pass struct with Vector4 array to cbuffer I'm playing around with SlimDX (with DX10/11) a bit and I got some nice results so far, but I'm stuck on passing an array of Vector4s to the shaders. If I try the following struct: [StructLayout(LayoutKind.Sequential)] public struct PerFrameBuffer { public Vector4 Position; public Matrix World; public Matrix View; public Matrix Projection; [MarshalAs( UnmanagedType.ByValArray, SizeConst=2)] public Vector4[] Lights; } and try to store it in the following cbuffer: cbuffer cPerFrame : register( b0 ) { float4 xPosition; matrix xWorld; matrix xView; matrix xProjection; float4 pointLights[2]; } I don't get any errors, but the values in the matrices are broken. However when I declare my struct in c# as follows: [StructLayout(LayoutKind.Sequential)] public struct PerFrameBuffer { public Vector4 Position; public Matrix World; public Matrix View; public Matrix Projection; public Vector4 Light1; public Vector4 Light2; } Then everything works fine as expected. I don't really want to make 64 fields in the struct and fill them up like that (I could with reflection but still). How can I use an array to pass the Vector4's to my constantbuffer? If by any means this is a dumb idea and should be done in another way, please let me know. It's my first time programming directx and shader related stuff. To be complete: Declaration of the buffer in C# cPerFrameBuffer = new SlimDX.Direct3D11.Buffer(device, new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = Marshal.SizeOf(typeof(PerFrameBuffer)), BindFlags = BindFlags.ConstantBuffer }); context.VertexShader.SetConstantBuffer(cPerFrameBuffer, 0); How I'm updating the buffer: var cb = new AbstractDXManager.PerFrameBuffer() { Position = new Vector4(camera.Position, 1.0f), Projection = Matrix.Transpose(camera.ProjectionMatrix), View = Matrix.Transpose(camera.ViewMatrix), World = Matrix.Transpose(Matrix.Identity), }; cb.Lights = new Vector4[2]; cb.Lights[0] = cb.Position; cb.Lights[1] = new Vector4(20, 20, 20, 1); var context = device.ImmediateContext; using (DataStream data = new DataStream(Marshal.SizeOf(typeof(PerFrameBuffer)), true, true)) { data.Write(cb); data.Position = 0; context.UpdateSubresource(new DataBox(0, 0, data), cPerFrameBuffer, 0); } Thanks in advance A: I had the same problem. I changed buffer writing. Now it works This is my struct [StructLayout(LayoutKind.Sequential,Pack=1)] public struct WorldConstants { public Matrix View; public Matrix Projection; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public Color4 [] DiffuseColor; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public Color4[] AmbientColor; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public Vector4[] LightDirection; public Vector4 ViewPosition; } I used StructToPtr to get the alligned data. using (DataStream stream = new DataStream(streamSize, true, true)) { int rawsize = Marshal.SizeOf(typeof(ElementT)); IntPtr buffer = Marshal.AllocHGlobal(rawsize); foreach (var element in elements) { Marshal.StructureToPtr(element, buffer, false); stream.WriteRange(buffer,rawsize); } Marshal.FreeHGlobal(buffer); Unfortunately this causes an additional copy of the data. In my case I didn't notice any performance problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Architecture behind large-scale social sites like Twitter - help with a new startup. I apologize in advance for this not being a specific programming question, but I believe this is the best place for such an inquiry. Basically, I have an idea for what I believe to be an interesting social networking site (not just a clone of existing things, but something useful and unique); I have a detailed specification document describing how everything works, but I'm not sure how best to proceed from here. Architecturally, it seems like it would be most similar to something like Twitter, and I have some idea of what technologies are involved in this (SQL database, ajax, mobile integration, etc.). I do not have the time to code everything myself, and honestly some of it is likely beyond me. So, I suppose my pool of questions is something like this: Assume I am non-programmer with a legitimately good idea for a new and large-scale social networking service, similar (in architecture) to Twitter, and some capital to make it happen: How do I proceed? What is the architecture behind a site like Twitter and what technologies does it use? How do I find people with experience building these types of systems for consulting/development purposes? Are there any initiatives (government or otherwise) that can help me in such a start-up endeavor? I appreciate any help you can offer. Thanks, and again I apologize for the broadness of this question. A: The High Scalability blog ( http://highscalability.com/ ) periodically describes the architecture of major sites. Browse through archives there to get a feel for how they get built.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Put condition on select command : charindex - SQL I need help with the following query. I want to put a condition on the returned value of select command which is an integer between 0 and any number. DECLARE @month varchar(50); set @month ='01-03-05-07-09-11'; <--- clarification: these are all months Declare @cur_month int; set @cur_month = Month(GetDate()); select charindex(str(@cur_month), @month); I essentially want If ( select charindex(str(@cur_month), @month)) // successful I get error An expression of non-boolean type specified in a context where a condition is expected, near 'print'. I tried CAST and CONVERT but to no Avail. As you can see, I am trying to see if the current month is in my @month field, I want to execute certain actions if it is. A: Taking the answer from @PaulStock with a couple tweaks will work better. Changes from PaulStock's answer * *Left pad for leading zeros. 2 != 02 and wouldn't match. *Add hyphens at the beginning and end of the string so each value is in the form -XX- I included this in case you realize you won't be having the leading zeros. If you'll always have leading zeros you won't need this. Actual code DECLARE @month VARCHAR(50); set @month ='03-05-12-09'; set @month = '-' + @month + '-' IF CHARINDEX('-' + right('00' + CAST(MONTH('2/13/2011') AS VARCHAR), 2) + '-', @month) > 0 PRINT 'exists' ELSE PRINT 'does not exist' A: Instead of using string functions, use date functions since you are trying to compare one datefield to another. And use datetime for @month instead of varchar: DECLARE @month datetime; set @month ='09-03-05'; IF MONTH(@month) = MONTH(CURRENT_TIMESTAMP) PRINT 'Same Month' UPDATE Based on your updated question, here is new code: DECLARE @month VARCHAR(50); set @month ='03-05-02-09'; IF CHARINDEX(CAST(MONTH(CURRENT_TIMESTAMP) AS VARCHAR), @month) > 0 PRINT 'Same Month' A: I don't know what variation on the SQL language you are using, since SQL does not support variables and IF statements, but why not use a variable to represent the result of the condition? SELECT @MyResult=charindex(str(@cur_month), @month); -- Now you can write an IF statement using the variable IF @MyResult... A: The return value for select charindex is an integer, not a boolean type. You'll need to put a boolean into your if statement. Try something like: If ( select charindex(str(@cur_month), @month) > 0) A: This solution pads a zero to the left for months < 10, to make sure it works for February (2) when december is on the list (12), as it was pointed out by OCary DECLARE @month varchar(50); set @month ='01-05-07-09-11-12'; If (charindex(right('0' + CAST(MONTH(getdate()) as varchar), 2), @month) > 0) PRINT 'Same Month' if you run this: select right('0' + CAST(MONTH(getdate()) as varchar), 2) it returns 09
{ "language": "en", "url": "https://stackoverflow.com/questions/7573339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Method Sleep Until Notification Is there any way that I can have a method sleep until a notification is posted? This is for an asynchronous NSURLConnection. I cannot move to a synchronous connection for multiple reasons. A: Methods cannot "sleep"; that only applies to threads. Just split the code that needs to wait out into another method and have that method called when the notification arrives. - (void) doStuffBeforeConnection { [self doPreConnectionStuff]; NSURL * url = [NSURL URLWithString:@"/U/R/L"]; NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:0]; NSURLConnection * conn = [NSURLConnection connectionWithRequest:request delegate:self]; return; // We are now "waiting"... } - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self nowDoStuffThatNeededToWait:response]; } A: use addobserver and set a target class with selector to be fired on notification. when you need to trigger, use postNotification with notificatonName. there you go..!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex validation of operators in conditional statements I've built a dynamic conditional validator in C# that can validate if a condition written in a textbox input is true or false. string a = "25 > 20"; bool aResult = ValidateInput(a); // Will generate true string b = "10 != 10"; bool bResult = ValidateInput(b); // Will generate false Now im stuck at validating the input which comes from a textbox, Im thinking regex but dont know where to start really. The valid conditionals are = == < > <= >= != Any advice is highly appreciated Thanks. A: You could use a third party libray like Flee to evaluate your expressions. A: Or you can split the string based on your operators and then perform the validation. A quick and dirty code sample in LinqPad: void Main() { string a = "25 > 20"; string b = "10 != 10"; var splits = a.Split(new string[]{}, StringSplitOptions.RemoveEmptyEntries); splits.Dump(); var result = Validate(splits); result.Dump(); splits = b.Split(new string[]{}, StringSplitOptions.RemoveEmptyEntries); splits.Dump(); result = Validate (splits); result.Dump(); } // Define other methods and classes here bool Validate(string[] input) { var op = input[1]; switch(op) { case ">": return int.Parse(input[0]) > int.Parse(input[2]); case "!=": return int.Parse(input[0]) != int.Parse(input[2]); } return false; } You can easily customize this a lot if you want to. A: Assuming you only allow integers on each side of the conditional, something like this should work: ^\s*\d+\s*(?:==?|<=?|>=?|!=)\s*\d+\s*$ The \s* all over the place is to make this very tolerant of extra whitespace. A: ^\d+\s*(>=|<|>|<=|=|==|!=|<>)\s*\d+$
{ "language": "en", "url": "https://stackoverflow.com/questions/7573351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between no-cache and no-store in Cache-control? I don't find get the practical difference between Cache-Control:no-store and Cache-Control:no-cache. As far as I know, no-store means that no cache device is allowed to cache that response. In the other hand, no-cache means that no cache device is allowed to serve a cached response without validate it first with the source. But what is that validation about? Conditional get? What if a response has no-cache, but it has no Last-Modified or ETag? Regards. A: But what is that check about? Exactly checking Last-Modified or ETag. Client would ask server if it has new version of data using those headers and if the answer is no it will serve cached data. Update From RFC no-cache If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server. This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests. A: As you identified, no-cache doesn't mean there is never caching, but rather that the user agent has to always ask the server if it's OK to use what it cached. By contrast, no-store says to not even keep a copy, which means there's nothing to ask about. If you know the answer to "Can I reuse this?" is always no, you get a performance boost by skipping cache validation and saving room in the cache for other data. Aside from performance, there is a behavior difference with browser history. HTTP 1.1 section 13.13 says that "expiration time does not apply to history mechanisms." The no-cache header describes expiration, and so doesn't apply to history mechanisms such as the back button. Thus, the user can navigate backward to a previous page with no-cache without the server being contacted. The no-store header, on the other hand, prevents the data from being stored outside of a session, in which case it simply isn't available for a history mechanism to use. With no-store, if the user ends his session by navigating to another domain and then goes back, the only way for browser to know what to display is to get the initial page again from the server. Here's how a Chromium issue on this topic makes the distinction: no-cache doesn't mean "don't cache this" (that would be no-store). no-cache means don't use this for normal loads unless the resource is revalidated for freshness. History navigations are not normal loads. A: See the below flow chart for better understanding Ref: (https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=en#cache-control) A: * *No-store : Client will not make any caching operation. *No-cache : Client will cache the response, but client will check server before using that cached data: "data has changed on the server or not?" :with help of 'If-Modified-Since' or 'If-None-Match' header.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "77" }
Q: JQuery Tokenizing Autocomplete w/ trigger key Is there a good solution to create textfield inputs like those of Facebook or Google+ status updates and posts where a tokenizing autocomplete is allowed to happen after certain trigger keys like "@" or "+"? It seems like there are a couple of good tokenizing autocomplete plugins but I'm trying to find a way to call the autocomplete only when the key is present before a term but let's the user type plain non-autocompleted text otherwise. It seems like you might be able to hack something together with bind but I'm pretty new to JavaScript so if there is a simple more elegant solution I'd love to hear it. A: Using jquery is not very difficult. First set a class to identify your input boxes. For example: <input type="text" class="autocomplete" name="the_name" /> Then, you can simply capture the keyup event and check for the key you need. For example, @ symbol has the keycode 64 $(".autocomplete").keypress(function(e) { if (e.which == 64) { // your event handler } }); You can see all event codes and more info about .keypress() here. Your event handler may use the jquery.ajax function to ask the server for the data to fill your selector. If you want to autocomplete after entering some text, for example if the user writes "@tyle" you have to modify the condition in the above code, to get the last word written and check if it has an @ at the beginning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Publish/deploy exe from Visual Studio 2010 Trying to deploy a little C# app to another server...in visual studio am doing the publish from the menu,it creates a publish folder & subfolders,etc. Copy those to another machine and try to run the setup.exe there - gets following error, also tried just copying the exe created and the .exe.config and get same error. When publishing, selected "install from CD" so all file paths relative to install directory...so something is not right! Messages below: Description: Stopped working Problem signature: Problem Event Name: CLR20r3 Problem Signature 01: loadadjusterphotosapp.exe Problem Signature 02: 1.0.0.0 Problem Signature 03: 4e81f332 Problem Signature 04: mscorlib Problem Signature 05: 2.0.0.0 Problem Signature 06: 4d8c19ca Problem Signature 07: 344a Problem Signature 08: 119 Problem Signature 09: System.IO.DirectoryNotFound OS Version: 6.0.6002.2.2.0.272.7 Locale ID: 1033 thanks, Phil J. A: I get this error and seems to be due to missing libraries. In my case it was to do with windows media player. My program only worked on computers that had Visual Studio installed. No idea what the actual fix is though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AIR multiple HTTPService call Mac OSX I am instantiating and sending multiple instances of HTTPService On a Mac, however, many of the calls fail with a 2032 error. <?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" click="windowedapplication1_clickHandler(event)" creationComplete="windowedapplication1_creationCompleteHandler(event)"> <fx:Script> <![CDATA[ import mx.controls.Alert; import mx.events.FlexEvent; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; [Bindable] private var r:int=0; [Bindable] private var f:int=0; private var a:Array= ['url1', 'url2', 'url3', 'url4', 'url5']; private var sa:Array=[]; protected function windowedapplication1_clickHandler(event:MouseEvent):void { for(var i:int=0; i<sa.length; i++) { sa[i].send(); } } protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void { for(var i:int=0; i<100; i++) { var random:int=Math.floor(Math.random() * a.length); var s:HTTPService=new HTTPService(); s.addEventListener(ResultEvent.RESULT, sr); s.addEventListener(FaultEvent.FAULT, sf); s.resultFormat="text"; s.url=a[random]; sa.push(s); } //s.useProxy=true; } private function sf(e:FaultEvent):void { f++; t.text="MESSAGE: " + e.message + "HEADERS:" + e.headers + "FAULTCONTENT: " + e.fault.content + "ERROR: " + e.fault.errorID + "|" + e.fault.faultCode + "|" + e.fault.faultDetail + "|" + e.fault.faultString + "FAULTMESSAGE:" + e.fault.message + "FAULRNAME:" + e.fault.name + "ROOTCAUSE:" + e.fault.rootCause + "AT " + e.fault.getStackTrace(); } private function sr(e:ResultEvent):void { r++; } ]]> </fx:Script> <fx:Declarations> </fx:Declarations> <s:Label x="10" y="19" text="Result {r}"/> <s:Label x="10" y="120" text="Fault {f}"/> <s:TextArea x="10" y="198" width="610" height="294" id="t"/> </s:WindowedApplication> It works as expected on PC (I get all 100 results as successful) but on a Mac, I get wuite a few that fail. Why is this happening and how do I get around it? A: It seems Win7 and Mac OS X block very quick requests to different addressed. Adding a 1 second timeout works fine
{ "language": "en", "url": "https://stackoverflow.com/questions/7573365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In-place edits with sed on OS X I'd like edit a file with sed on OS X. I'm using the following command: sed 's/oldword/newword/' file.txt The output is sent to the terminal. file.txt is not modified. The changes are saved to file2.txt with this command: sed 's/oldword/newword/' file1.txt > file2.txt However I don't want another file. I just want to edit file1.txt. How can I do this? I've tried the -i flag. This results in the following error: sed: 1: "file1.txt": invalid command code f A: You can use the -i flag correctly by providing it with a suffix to add to the backed-up file. Extending your example: sed -i.bu 's/oldword/newword/' file1.txt Will give you two files: one with the name file1.txt that contains the substitution, and one with the name file1.txt.bu that has the original content. Mildly dangerous If you want to destructively overwrite the original file, use something like: sed -i '' 's/oldword/newword/' file1.txt ^ note the space Because of the way the line gets parsed, a space is required between the option flag and its argument because the argument is zero-length. Other than possibly trashing your original, I’m not aware of any further dangers of tricking sed this way. It should be noted, however, that if this invocation of sed is part of a script, The Unix Way™ would (IMHO) be to use sed non-destructively, test that it exited cleanly, and only then remove the extraneous file. A: You can use -i'' (--in-place) for sed as already suggested. See: The -i in-place argument, however note that -i option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondly sed is a Stream EDitor, not a file editor. Alternative way is to use built-in substitution in Vim Ex mode, like: $ ex +%s/foo/bar/g -scwq file.txt and for multiple-files: $ ex +'bufdo!%s/foo/bar/g' -scxa *.* To edit all files recursively you can use **/*.* if shell supports that (enable by shopt -s globstar). Another way is to use gawk and its new "inplace" extension such as: $ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 A: This creates backup files. E.g. sed -i -e 's/hello/hello world/' testfile for me, creates a backup file, testfile-e, in the same dir. A: I've similar problem with MacOS sed -i '' 's/oldword/newword/' file1.txt doesn't works, but sed -i"any_symbol" 's/oldword/newword/' file1.txt works well. A: The -i flag probably doesn't work for you, because you followed an example for GNU sed while macOS uses BSD sed and they have a slightly different syntax. All the other answers tell you how to correct the syntax to work with BSD sed. The alternative is to install GNU sed on your macOS with: brew install gsed and then use it instead of the sed version shipped with macOS (note the g prefix), e.g: gsed -i 's/oldword/newword/' file1.txt If you want GNU sed commands to be always portable to your macOS, you could prepend "gnubin" directory to your path, by adding something like this to your .bashrc/.zshrc file (run brew info gsed to see what exactly you need to do): export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH" and from then on the GNU sed becomes your default sed and you can simply run: sed -i 's/oldword/newword/' file1.txt A: sed -i -- "s/https/http/g" file.txt A: You can use: sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path> Example: sed -i -e 's/Hello/Bye/' file.txt This works flawless in Mac. A: If you need to substitute more than one different words: sed -i '' -e 's/_tools/tools/' -e 's/_static/static/' test.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7573368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "242" }
Q: Silverlight 4 Overloaded Textbox's textchanged event is fired by parent textbox I have an custom textbox that I got from http://blog.roboblob.com/2010/07/16/custom-silverlight-textbox-control-that-immediately-updates-databound-text-property-in-twoway-binding/comment-page-1/: public class ImmediateTextBox : TextBox { public ImmediateTextBox() { this.Loaded += ImmediateTextBox_Loaded; } void ImmediateTextBox_Loaded(object sender, RoutedEventArgs e) { this.GotFocus += ImmediateTextBox_GotFocus; this.TextChanged += new TextChangedEventHandler(ImmediateTextBox_TextChanged); } void ImmediateTextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox txt = sender as TextBox; if (txt != null) { BindingExpression bindExp = txt.GetBindingExpression(TextBox.TextProperty); if (bindExp != null) { bindExp.UpdateSource(); }//if }//if } void ImmediateTextBox_GotFocus(object sender, RoutedEventArgs e) { this.SelectAll(); } } In my xaml I am using this, and it works fine, except when I have it nested and the parent container has a ImmediateTextBox: <ItemsControl Grid.Column="1" ItemsSource="{Binding Path=LstForecast}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <customControls:ImmediateTextBox Padding="8" Height="36" Text="{Binding Path=DForecastQuantityShippedTotal, StringFormat=\{0:n0\}, Mode=TwoWay, Converter={StaticResource StringToNullableDoubleConverter}}" Width="70" IsEnabled="{Binding Path=IsForecastUserEditable}"/> <!--Weeks--> <ItemsControl ItemsSource="{Binding Path=LstWeeks}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <customControls:ImmediateTextBox Padding="8" Width="70" Height="36" Text="{Binding Path=DForecastQuantityShippedTotal, StringFormat=\{0:n0\}, Mode=TwoWay, Converter={StaticResource StringToNullableDoubleConverter}}" IsEnabled="{Binding Path=IsForecastUserEditable}"/> <!--days data--> <ItemsControl ItemsSource="{Binding Path=LstDays}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <customControls:ImmediateTextBox Padding="8" Width="70" Height="36" Text="{Binding Path=DForecastAutoManual, StringFormat=\{0:n0\}, Mode=TwoWay, Converter={StaticResource StringToNullableDoubleConverter}}" IsEnabled="{Binding Path=IsForecastUserEditable}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <!--end days data--> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <!--end weeks--> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> At the lowest level it gets really funky. modifying the previous and sometimes the following generated textboxes. If I use an autocompletebox, of course it works. The problem is that I am wanting to add behaviors to the textbox for copy/paste/selectall, etc that I can't do with the autocompletebox, since there is no selectedtext or a selectall() method. Also I noticed in the RoutedEventArgs, the originalsource is null. I figured using that would cause it to work, but no. Any help? thanks in advance. A: Okay so I figured it out. I have each text-box bound to properties. When any one of these text-boxes are modified then the bound properties of the ViewModel update each other. When that happens they update the text-box where it occurs and not just the property, because it is a 2-way binding. So when there is an update that is caused by the user's input it updates. It shouldn't when the user doesn't type anything in that text-box (when the text-box is being updated from the algorithm. My solution is creating a boolean property "isUser" in ImmediateTextBox. When my overridden OnKeyDown or OnMouseLeftButtonPressed are called I set isUser to true. When the text changes from the user typing in or pasting in something, then i update the binding and set isUser to false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Base 64 encoder on localhost? I've placed this script on my localhost but it appears to be malformed (should display an input field for encoding and one for decoding base64. The author's site has apparently gone dark. Any ideas how to fix it or get a new one? <? // PHP OBFUSCATOR // (C)2003 Richard Fairthorne -- http://richard.fairthorne.is-a-geek.com // -------------------------- // Permission is granted to disctibute this file UNMODIFIED from its original // form. All other rights are reserved. function splitByNewline($string, $length) { while (strlen($string)>0) { $newstring.=substr($string, 0, $length) . "\n"; $string=substr($string, $length); } return $newstring; } echo "<big><b>Free Code Obfuscator (PHP, PERL)</b></big><br>By <a href='http://richard.fairthorne.is-a-geek.com'>Richard Fairthorne</a><hr>"; $b64_input=stripslashes($b64_input); switch($b64_action) { case "perl_encode": $output=$b64_input; $output=base64_encode($output); $output=splitByNewline($output,40); $output="#!/usr/bin/perl\nuse MIME::Base64;\neval(decode_base64('\n$output'));"; $ilength=strlen($b64_input); $olength=strlen($output); ?> <table border=0 width=100%><tr><td valign=top> <textarea rows=18 cols=60 name=done><?=$output;?></textarea> </td><td valign=top> <b>PERL code obfuscated!</b><br><br> Your PERL code has been obfuscated. <br><br> <font color=maroon> Obfuscation-Strength: Normal (Fast code execution)<br> Compatibility: 100% Code compatibility<br> Input Length: <?=$ilength;?><br> Output Length: <b><?=$olength;?></b><br> </font> <br> To use the code, simply cut and paste it in place of the old code. You may need to update the perl path. It is important to understand that code obfuscation can act as a deterrant, but is not a replacement for encryption.<br><br> <a href='?'>Click here</a> to obfuscate another page. </td></tr></table> <? break; case "php_encode": $output=$b64_input; $output=gzdeflate("?>".$output."<?",9); $output=base64_encode($output); $output=splitByNewline($output,40); $output="<? eval(gzinflate(base64_decode('\n$output'))); ?>"; $ilength=strlen($b64_input); $olength=strlen($output); ?> <table border=0 width=100%><tr><td valign=top> <textarea rows=18 cols=60 name=done><?=$output;?></textarea> </td><td valign=top> <b>PHP code obfuscated!</b><br><br> Your PHP code has been obfuscated. <br><br> <font color=maroon> Obfuscation-Strength: Normal (Fast code execution)<br> Compatibility: Zlib Required. 100% Code compatibility<br> Input Length: <?=$ilength;?><br> Output Length: <b><?=$olength;?></b><br> </font> <br> To use the code, simply cut and paste it in place of the old code. It is important to understand that code obfuscation can act as a deterrant, but is not a replacement for encryption.<br><br> <a href='?'>Click here</a> to obfuscate another page. </td></tr></table> <? break; case "php_encode_hi": $output=$b64_input; for ($b64_counter=0; $b64_counter<10; $b64_counter++) { $output=gzdeflate("?>".$output."<?",9); $output=base64_encode($output); $output="<? eval(gzinflate(base64_decode('$output'))); ?>"; } $output=gzdeflate("?>".$output."<?",9); $output=base64_encode($output); $output="<? eval(gzinflate(base64_decode('\n$output'))); ?>"; $ilength=strlen($b64_input); $olength=strlen($output); ?> <table border=0 width=100%><tr><td valign=top> <textarea rows=18 cols=60 name=done><?=$output;?></textarea> </td><td valign=top> <b>PHP code obfuscated!</b><br><br> Your PHP code has been obfuscated. <br><br> <font color=maroon> Obfuscation-Strength: Trecherous (Best Protection)<br> Compatibility: Zlib Required. 100% Code Compatibility.<br> Input Length: <?=$ilength;?><br> Output Length: <b><?=$olength;?></b><br> </font> <br> To use the code, simply cut and paste it in place of the old code. It is important to understand that code obfuscation can act as a deterrant, but is not a replacement for encryption.<br><br> <a href='?'>Click here</a> to obfuscate another page. </td></tr></table> <? break; // case "decode": // $output=htmlentities(base64_decode($b64_input),ENT_QUOTES); // break; default: ?> <table border=0 width=100%><tr><td valign=top> <form method=post> <textarea name=b64_input cols=60 rows=16></textarea><br> <SELECT name=b64_action> <OPTION value='php_encode'>PHP - Normal Strength - Compressed</OPTION> <OPTION value='php_encode_hi'>PHP - Trecherous Strength - Compressed</OPTION> <OPTION value='perl_encode'>PERL - Normal Strength</OPTION> </SELECT> <input type=submit name=submit value='obfuscate'> <!-- <input type=submit name=b64_action value=decode> --> </form> </td><td valign=top> <b>Free Code obfuscator</b><br><br> If you would like a quick way to hide your php code from prying eyes, try this PHP code obfuscator.<br><br>Copy an entire PHP page, into the obfuscator, and it will return a code that also works on any PHP server, but is not human readable.<br><br> With code 5k or bigger, you may notice that the obfuscated code is smaller than the original code. You can thank me later. </td></tr></table> <? break; } ?> A: Change all <? to <?php. Then break its reliance on register_globals with the following: // Change this //$b64_input=stripslashes($b64_input); // To: $b64_input=isset($_POST['b64_input']) ? stripslashes($_POST['b64_input']) : ""; // And below it, add: $b64_action = isset($_POST['b64_action']) ? $_POST['b64_action'] : ""; Also, fix these short open tag dependencies: Ln 43 - 44: Input Length: <?php echo $ilength;?><br> Output Length: <b><?php echo $olength;?></b><br> Ln 67: <textarea rows=18 cols=60 name=done><?php echo $output;?></textarea> Ln 105: <textarea rows=18 cols=60 name=done><?php echo $output;?></textarea> Ln 114 - 115: Input Length: <?php echo $ilength;?><br> Output Length: <b><?php echo $olength;?></b><br> With the above changes, I was able to successfully obfuscate the obfuscator code. A: I would honestly never use this code. Its just bad PHP and HTML code. (it seems like it might be old, due to the caps'ed HTML Tags and the reliance on global variables.) If you want to just Base 64 Encode and decode it would be as easy as something like (off the top of my head): <!DOCTYPE html> <html> <head><title>Meh</title></head> <body> <form action="" method="POST"> <select name="action"> <option value="encode">Base64 Encode</option> <option value="decode">Base64 Decode</option> </select><br /> <textarea name="content"></textarea><br /> <input type="submit" value="Base64 It!" /> </form> <?php if($_SERVER['REQUEST_METHOD'] == "POST"){ if($_POST['action'] == "decode") echo base64_decode($_POST['content']); else echo base64_encode($_POST['content']) } ?> </body> </html> This is just a rough example i just wrote, of course- but it should be enough, unless you are trying to do some more than that. Shai.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: basic question about setting up event listeners in jquery I come from as3 and I'm a bit lost with jQuery. I have the feeling I haven't grasped the concept of how events work with jQuery, or javascript for that matters. I'm trying to do this: animation 1 ends --> load image --> animation 2 starts By now I'm doing this through the complete:function(){} parameter in .animate(). It works, but is not very flexible. How is it possible to set up a scenario like this?: * addEventListener(when animation 1 ends, do whatever) addEventListener(when image loading ends, do whatever) addEventListener(when animation 2 ends, do whatever) * I' tried using .bind() and .live(), something like $(window-document-div-etc).bind('load','animation stored in a variable', etc) with no results. Any suggestions on how to do it? Thanks in advance First of all, thanks everybody for your help. Sorry for using this "answer your question" feature, I haven't beenn able to use the "add comment" link, and, after all, I find a little silly pasting the same answer to everybody. If there is some kind any kind of moderator around, please move this to wherever it should be moved. Please excuse my lack of a proper technical language. This "callback functions" approach is the one I've used at first, and it works fine, but the resulting code is not very reusable. I would like to know how is it possible to write something more respectful with encapsulation, something like this: Image A is loaded, event is dispatched "IMAGE LOADED" Totally unrelated Object B has a listener for the "IMAGE LOADED" event, so receives the event and processes it through its method bDoesThis(). Totally unrelated Object C has a listener for the "IMAGE LOADED" event, so receives the event and processes it through its method cDoesThat(). Thanks again! A: I think you're referring to Callback Functions. $('div').animate({ left: 50 }, 500, function() { // animation completed. $(this).hide(); }); $('img').bind('load', function() { // Callback (image has loaded) $(this).fadeIn(200); }); A: You bind events to objects that you obtain using a $(selector) format, for instance $(document) or $('#yourElementid') and add event handlersr using bind or live. Live has the advantage that any newly created elements that match the selector automatically get bound using your event handler. For example, $('.clickme').bind('click', function() {//event handler. $(".block:first").animate({"left": "+=50px"}, "slow" , "swing", function(){ //animation 1 ends.do whatever in callback }); }; You can alternatively just use $('.clickme').click(function(){}); as a shortcut instead of the cumbersome $('.clickme').bind('click',function(){}) syntax. A: You would use callback functions, and an event listener for the image like this: // select what you want to animate, and do some animation // set a callback function to execute upon completion $('div').animate({width:100},2000,function(){ // in the callback - create a new IMG element $('div').html('<img id="newImage" src="http://farm7.static.flickr.com/6085/6027474363_42050547b2_b.jpg" />') // set an event listener for your IMG element $('#newImage').load(function(){ // do second animation $('div').animate({width:800},2000) }) }) You can see a demo of this code here: http://jsfiddle.net/fePzu/
{ "language": "en", "url": "https://stackoverflow.com/questions/7573378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a multiline string or multiline label as a CGPath in iOS? Does the API support this? If not, how could I do it? There is CTFontCreatePathForGlyph in Core Text, which can translate a single character into a path. I could use that in a loop to create my string as a path, but I'd have to deal with spacing and kerning and all the other nasty things. I'm looking for a string path that would looks the same if it was drawn in a UILabel with same font and size. A: There is an article called Low-level text rendering by Ohmu that covers this pretty extensively. I have tried this code and can confirm that it works. It does use Core Text, though, so the rendering is probably not exactly like that of a UILabel. Also, the sample article only deals with a single line. To extend it to multiple lines, you have to setup the complete Core Text system. Instead of: CTLineRef line = CTLineCreateWithAttributedString( attStr ) ; you need to set up a CTFramesetterRef (CTFramesetterCreateWithAttributedString) and CTFrameRef (CTFramesetterCreateFrame) as described in the Core Text Programming Guide. You can then get all lines in the frame with CTFrameGetLines(). You would then wrap the for loop in the sample article: CFArrayRef runArray = CTLineGetGlyphRuns(line); // for each RUN for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++) with another loop that iterates over all lines. The inner core of the loop should be identical. The sample article creates a graphics context and adds the paths for the single glyphs to this context's path, but you can just as easily create a CGMutablePathRef or UIBezierPath and add the single glyph's paths to that object. One thing that is not 100% clear to me without testing this is how to adjust the vertical position of the glyphs in the final path. You probably have to call CTFrameGetLineOrigins() to get the position of each line and add this position to each rendered glyph (possibly after transforming it with the text matrix). A: Look at the UIBezierPath+TextPaths category in this project: https://github.com/aderussell/string-to-CGPathRef. It shows how to create paths for single and multi-line strings and how to use them with CAShapeLayers. The category is just a wrapper and the internal functions can be used in iOS or Mac OS X, you just need to link your project to the CoreText framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Solr: match results with and without whitespaces The data in our solr field looks like this: <str name="property_Info_Hd">320 GB SATA 7200RPM</str> <str name="property_Info_Hd">320GB SATA</str> <str name="property_Info_Memory">4 GB of DDR2</str> <str name="property_Info_Memory">2GB of DDR3</str> The field is dynamic ("property_*"), so both cases use the same analyzer. Currently, when searching for "2gb", it returns documents with "2GB" but misses "2 GB" (whitespace). Question is: how could I set this field type in schema so it matches results with and without whitespaces? For example: Searching for +(property_Info_Memory:("320gb")) should return both the first lines above, matching "320GB" AND "320 GB". This is how the field type is set: <fieldType name="textFilter" class="solr.TextField" positionIncrementGap="100"> <analyzer> <tokenizer class="solr.KeywordTokenizerFactory" /> <filter class="solr.WordDelimiterFilterFactory" splitOnCaseChange="0" splitOnNumerics="0" stemEnglishPossessive="0" catenateWords="1" catenateNumbers="1" catenateAll="1" preserveOriginal="1" generateWordParts="1" generateNumberParts="1"/> <filter class="solr.TrimFilterFactory" /> <filter class="solr.LowerCaseFilterFactory" /> <filter class="solr.ISOLatin1AccentFilterFactory" /> </analyzer> </fieldType> I've tried using splitOnCase and splitOnNumerics variations, none succeeded. Results then would match the ones with whitespaces (320 GB) and miss the non-whitespaced ones (320GB). Most documents have it's data without whitespaces, thats why the current setup. Thanks in advance for your help. A: Worked from the analysis tool. you may want to give it a try :- <fieldType name="textFilter" class="solr.TextField" positionIncrementGap="100"> <analyzer type="index"> <tokenizer class="solr.KeywordTokenizerFactory" /> <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" catenateNumbers="1" catenateAll="1" preserveOriginal="1" generateWordParts="1" generateNumberParts="1"/> <filter class="solr.TrimFilterFactory" /> <filter class="solr.LowerCaseFilterFactory" /> </analyzer> <analyzer type="query"> <tokenizer class="solr.KeywordTokenizerFactory" /> <filter class="solr.WordDelimiterFilterFactory" splitOnNumerics="1" preserveOriginal="1"/> <filter class="solr.TrimFilterFactory" /> <filter class="solr.LowerCaseFilterFactory" /> </analyzer> </fieldType> Analysis - Index time - 2gb of data Query time - 2gb Tokens - 2gb, 2 gb 2 gb is generated as a token in the analysis and it shows a match in the index. A: I know of two ways to accomplish this: * *Have two fields store the data, each tokenized in a different way (i.e. use a copy field) *Have one field with a custom synonym filter #2 is the better solution, but will require writing some java. I'd recommend just extending the WordDeliminterFilter; you can see the source of SynonymTokenFilter for how to create synonyms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In Java how to extract string from the phrase with split() function Can I extract string from the phrase using split() function with subphrases as delimeters? For example I have a phrase "Mandatory string - Any string1 - Any string2". How can I extract "Any string1" with delimiters as "Mandatory string" and "[a-zA-Z]" This is how I'm trying to extract: String str="Mandatory string - Any string1 - Any string2"; String[] result= str.split("Mandatory\\string\\s-\\s|\\s-\\s[a-zA-Z]+"); Result of this code is result = ["Mandatory string","ny string1","ny string2"] But desired is: result = ["Any string1"] Could appreciate some help, thanks. A: First of all, there's a typo right here: Mandatory\\string This should probably read Mandatory\\sstring Anyway, I would either use " - " as the delimiter and get the second token: str.split(" - ")[1] // TODO: prod version should do bounds checking etc or use a different tool entirely, probably a regex match with the following regular expression: "Mandatory string - (.*) - .*" The parenthesised capture group will give you the string you're after. A: String[] result= str.split("Mandatory\\s(1)string\\s-\\s|\\s-\\s[a-zA-Z\\s(2)]+"); You just forgot an "s" in position(1) and there should be a "\\s" in position(2) try this line: String[] result= str.split("Mandatory\\sstring\\s-\\s|\\s-\\s[a-zA-Z\\s]+"); A: If there is a definite format to your input string, just split it and then use the parts that are needed: String[] resultArray = str.split(" - "); String whatYouWant = resultArray[1]; A: Why not String[] result = str.split(" - "); return result.length < 2 ? "" : result[1];
{ "language": "en", "url": "https://stackoverflow.com/questions/7573388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Datagrid MouseOver and Selected States when using arrow keys I have a wpf datagrid. I have added styling to show a mouseover color on a row. What I am trying to achieve is when the mouseover appears, and a user starts using the arrow keys to navigate up and down, the mouseover needs to disappear and only the row that the user used arrow keys to get to, is the highlighted one. The issue is the mouse cursor has been left on the grid while the user navigates with the arrow keys and the row under the cursor holds the highlight as well as the row the went to using arrows. Here is my sample xmal: <DataGrid AutoGenerateColumns="True" Height="277" HorizontalAlignment="Left" Margin="0,311,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="478" ItemsSource="{Binding Path=Persons}" RowHeight="20" RowHeaderWidth="35" Grid.ColumnSpan="2" > <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="Green" /> </Trigger> </Style.Triggers> </Style> </DataGrid.RowStyle> </DataGrid> Thanks A: You'll need to set some kind of flag when the user hits an Arrow key so that the background only changes if IsMouseOver and IsUsingArrowKeys is false. You might even be able to use the Mouse Visibility as a condition instead of using a flag I'm not positive the exact syntax, but it should be something like this <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <!-- May need to reference RelativeSource here, not sure --> <Condition Property="IsMouseOver" Value="False" /> <Condition Binding="{Binding IsUsingArrowKeys}" Value="False" /> </MultiDataTrigger.Conditions> <Setter Property="Background" Value="Green" /> </MultiDataTrigger> </Style.Triggers> A: I would suggest highlighting the row based on thier focus triggers. Something like this: <EventTrigger RoutedEvent="GotFocus"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="dataGrid1" Storyboard.TargetProperty="Background" Duration="0:0:0.1" To="Green"/> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> <EventTrigger RoutedEvent="LostFocus"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="dataGrid1" Storyboard.TargetProperty="Background" Duration="0:0:0.1" To="White"/> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> And giving focus to them manually, something like this: private void Btn_Click(object sender, RoutedEventArgs e) { dataGrid1.Focus(); } So when another row gets focus, the current row loses focus & automatically falls back to non highlighted color background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pushing JAX-B object over network I have some interface description in text describing a RESTful webserver. I also have JAX-B annotated objects that I want to push and receive from that interface. I'm not sure how much support for such a task is already implemented. There is some Jersey thing around, but is that still up to date? Do I have to define a target URL, open a stream, serialize the xml object (maybe turning it into a string first?), and then write it to the stream? Or is there some magic method that only expects a URL and the JAX-B object and maybe if I want to PUT,DELETE,POST or GET it? A: JAX-RS is what you want to use in this case and Jersey is the reference implementation. JAXB is the default binding layer for JAX-RS. Below is an example of a RESTful service that supports PUT, DELETE, POST, and GET: package org.example; import java.util.List; import javax.ejb.*; import javax.persistence.*; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Stateless @LocalBean @Path("/customers") public class CustomerService { @PersistenceContext(unitName="CustomerService", type=PersistenceContextType.TRANSACTION) EntityManager entityManager; @POST @Consumes(MediaType.APPLICATION_XML) public void create(Customer customer) { entityManager.persist(customer); } @GET @Produces(MediaType.APPLICATION_XML) @Path("{id}") public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id); } @PUT @Consumes(MediaType.APPLICATION_XML) public void update(Customer customer) { entityManager.merge(customer); } @DELETE @Path("{id}") public void delete(@PathParam("id") long id) { Customer customer = read(id); if(null != customer) { entityManager.remove(customer); } } @GET @Produces(MediaType.APPLICATION_XML) @Path("findCustomersByCity/{city}") public List<Customer> findCustomersByCity(@PathParam("city") String city) { Query query = entityManager.createNamedQuery("findCustomersByCity"); query.setParameter("city", city); return query.getResultList(); } } Below are links to the full example: * *Part 1 - Data Model *Part 2 - JPA *Part 3 - JAXB (using MOXy) *Part 4 - RESTful Service (using an EJB session bean)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can pointers be used with Dictionary? Let's say I have the following class: public class MyClass { public string FirstAttribute { get { return Attributes["FirstAttribute"]; } set { Attributes["FirstAttribute"] = value; } } public string SecondAttribute { get { return Attributes["SecondAttribute"]; } set { Attributes["SecondAttribute"] = value; } } public Dictionary<string, string> Attributes; public MyClass(Dictionary<string,string> att) { Attributes = att; } } and I wanted to be able to obtain a pointer to the value that is stored in the Dictionary, so that I can get and set the values (yes unsafe) directly without having to wait for the Dictionary to search for the element by key every time. Is there a way to do that in c#? A: No, no, no, no. strings are immutable for a reason. A string might be shared between multiple references: modifying it directly with unsafe code might lead to weird behavior. A way to go around this would be to write a wrapper class that olds your value, and keep a reference to an instance of that wrapper. The getters and setters would then modify the wrapper's property. A: No, I don't believe so. You could store a mutable wrapper in the dictionary though: public class Wrapper<T> { public T Value { get; set; } } Then create the dictionary (which should be private, by the way - public fields are a really bad idea other than for constants) as a Dictionary<string, Wrapper<string>>. You can then keep fields for the Wrapper<string> objects associated with "FirstAttribute" and "SecondAttribute". Frankly I don't think this would be a particularly good idea - I'd just stick with the dictionary lookup - but it's an option. (Assuming nothing's going to change which wrapper is associated with the keys.) Another option is simply to use fields for the two specific attributes - when you're asked to set a new value, set it in the dictionary and set a field. When you're asked for the current value, just return the value from the field. Of course, that's assuming that you're in control of the dictionary (i.e. so it can't change outside your class). A: If the values in the dictionary were mutable, you could grab the reference to them and mutate them. But strings are immutable. So the dictionary has its own copy of a reference to your string, and you can't alter the string it is pointing to. If you try to replace it with another string, you need to update the dictionary with the new reference. So basically there's no way to improve on what you have in this situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: API usage conventions Im quite new to the usage of API in web development. Im working on a web application in python/django that makes ajax jsonp requests to the giantbomb api. As I learn how to use this api to get the info want, im beginning to realize certain things should probably be handled better in my code for various efficiency/security reason. But I am unfamiliar with conventions for the usage of web-based API's. Here a few questions ive been thinking about: * *Is it bad to have my api-key in the address bar, or in the source. *Since i am using Django/Python, should i just create a custom view for each api request and and use simplejson? I wanted to use AJAX to reduce the amount of requests, and for better dynamic UI. *In these situations, are api-keys, api-urls saved into a session then accessed as needed? thank you for help and patience in advance, A: * *Having your API key visible to the user means they can do requests as you. Whether this is bad or not depends on the API in question. If it is possible to do three-legged auth, your server can negotiate a temporary key (e.g. Oauth's session key) with the API server and only share that temporary key with the browser. *If you intend for the browser to do the API requests via AJAX, your views don't enter into the picture at all, except to pass the API credentials to the browser for use in javascript. *If you are doing three-legged auth, your server would store the API key somewhere permanent (database or file), but the session key could live in a more temporary location (e.g. wherever your session data is stored). But it will still need to be passed to browser, assuming it is doing the actual API requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I programmatically add new row to gridview on button click handler? This is my markup: <asp:Button runat="server" ID="btnabc" Text="Hello" onclick="abc_Click" /> <br /> <br /> <asp:GridView runat="server" ID="test" AutoGenerateColumns="false"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:TextBox runat="server" ID="txt" Text = "<%# Container.DataItem %>" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> This is my button click handler: protected void abc_Click(object sender, EventArgs e) { } I can't find any method like gridview.Rows.Add(). A: You don't. But you can simply and straightforwardly add a new item to your grid's DataSource and you are done. A: Try adding a row to the datasource object, and then rebind the GridView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby singleton class I am unsure about the difference between this. def String.hello puts "hello there" end and x = Person.new def x.hello puts "hello there" end From my understanding the second code block will create an object of class Person. When I do the def x.hello it creates an anonymous class (singleton class) that will be checked first for methods when sending a message to the x object. Is this the same case for the def String.hello? String is just an instance of class Class correct? I have read that doing def String.hello will add the method as one of String's class methods.... this would be different than an anonymous class being created that sits in between the object and its class where it gets its instance methods. What happens with both blocks of code above? A: I love this part of ruby. There is this beautiful symmetry where most of the core functionality is just sugar over the advanced functionality, so once you fully grok a concept, you can apply that understanding to a lot of the language. Is this the same case for the def String.hello? String is just an instance of class Class correct? Yes, you are creating an instance of Class, and assigning it to a constant. I have read that doing def String.hello will add the method as one of String's class methods.... this would be different than an anonymous class being created that sits in between the object and its class where it gets its instance methods. Nope, the piece you are missing is thinking its possible to have a class level method WITHOUT adding it to a singleton class. What you have is an object that is an instance of Class, and you are adding methods to an implicit class that sits inbetween it and Class. You will also see this syntax sometimes class << self def method end end That is doing the same thing, just being very explicit about it. A: Just to add to the Matt's answer: Both examples do the same thing, Writting them in another way: String = Class.new # < done inside ruby initialization def String.hello puts "hello there" end and x = Person.new def x.hello puts "hello there" end On Ruby you can add methods to a class, created with A = Class.new or with the syntax sugar class A; ...; end, or to a Eigenclass, that exists for every object. Class methods are, on really, methods of the Eigenclass of an instance of Class, think about what is "self" in def self.method; ...; end. Eigenclasses can be opened with this sintax: x = Person.new class << x # ... end As Eigenclasses are also instances of class (try to add p self.class on last example) they also have Eigenclasses and so on. If it appears to be confusing, just remember that Object is a class and Class is an object. This is why I love Ruby! A: The following code will add the "hello" method to the String class, that way all following strings will have the "hello" method: def String.hello puts "hello there" end Whilst the following code, will add the "hello" method, to the instance x of the class Person. If you create a new Person, that object will not have the "hello" method. x = Person.new def x.hello puts "hello there" end That is the main difference, as I understand it. Does this help?
{ "language": "en", "url": "https://stackoverflow.com/questions/7573407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Redirect all file IO in Windows I'm using a virtual file system (PhysFS) and I'd like the entire application to do file IO through this VFS (that includes third-party libraries). How can I redirect all file IO operations (C FILE* objects and C++ streams) through this VFS in Windows? Also, a related question. Is file IO redirection a common feature of OS APIs? Will it be easy for me to port my application? A: API hooking is probably the only way to address the problem. Hooking can be done using third-party helper libraries such as Detours and some other. This method is both non-trivial and not portable. In theory you could use a filesystem filter driver, but this way is much more complicated and requires a kernel-mode driver (which is a PITA to develop).
{ "language": "en", "url": "https://stackoverflow.com/questions/7573410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP model design with caching I'm designing the model for an application that will get/set objects in a remote database. For performance, we need to cache the data locally. I've read in various threads that it's best to put the caching logic into a parent model rather than the main controller. This is probably a basic OOP question, but I'm not sure about the implementation. In my PHP design, I have three objects. Let's call them P (for Parent model), L (for Local) and R (for Remote). Currently, I'm planning on having them interact like this: class P { var $column1; var $column2; ... var $R; var $L; ... function __construct() { $this->R = new Remote(); $this->L = new Local(); } function get($id) { if (is_cached()) { $this->L->($id); } else { $this->R->get($id); } } } class R { public function get($id) { return $this->remoteDB->get($id); } } class L { public function get($id) { return $this->localDB->get($id); } } The problem I see with this design is that it is A) probably requiring load() functions in all three objects which seems inefficient and B) requires passing properties from one object to another (rather than just referencing them directly). Any suggestions for a better way of doing this? A: I would suggest that you look into the existing frameworks that deal with database access tiers and have built in cache management. A Few: Kohana, Zend, Code Ignitor I'm also not sure why you can't abstract your load functions and have your models extend the abstraction?
{ "language": "en", "url": "https://stackoverflow.com/questions/7573414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: On Linux, how do you determine which individual pages are resident? How can one determine which individual pages are resident (i.e., committed in RAM)? On Linux, /proc/pid/smaps gives, for a fixed set of ranges, how many bytes are resident in that range, but this information doesn't tell you what actual ranges of memory are resident. As for what this is intended to be used for: I already have data associating allocation ranges with the source line info. This is useful for finding who is allocating how much. Given resident memory ranges, I could correlate the data to find who is allocating how much memory that was being kept resident. Thanks! A: There is a syscall to do this: mincore - determine whether pages are resident in memory int mincore(void *addr, size_t length, unsigned char *vec);
{ "language": "en", "url": "https://stackoverflow.com/questions/7573418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }