text
stringlengths
8
267k
meta
dict
Q: How do you pass cucumber a text file of features to run? ie. rerun.txt I finally figured out how to output failing tests to a rerun.text cucumber -p headless --format rerun --out rerun.txt 'path of feature files' We get the output file of rerun.txt but when we try to do cucumber -p headless rerun.txt it gets a lexing error because gherkin can't take this input. How do we run the file in cucumber? We tried also just running: cucumber -p headless --format rerun --out rerun.txt with no path listed, but it will just run all the feature files. The rerun.txt does contain our failing features. A: From the cucumber help text (cucumber -h): Use --format rerun --out features.txt to write out failing features. You can rerun them with cucumber @rerun.txt. So you'd probably want to use: cucumber -p headless @rerun.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7587561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert a string to type "LuaFunction" I'm using the LuaInterface in .net for a large project I'm working on. Is it possible to convert a string straight into a LuaFunction (similar to how LoadString() works?). A: LuaInterface has LoadString, that is how you get lua source code parsed into a LuaFunction, you can then use the Call method to execute the function. static void Main(string[] args) { Lua lua = new LuaInterface.Lua(); LuaFunction func = lua.LoadString("return 5", "name for debugging"); func.Call(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I read in a CLOB column that's too large to fit in a string? I have an Oracle SQL database with a CLOB column that holds a great deal of data. I'm running into the issue that a regular PHP string variable will not hold all of the data that I have in the CLOB column. It will only read in 4618 bits, but my file is much larger. The CLOB column has a series of IP addresses in it. What I need to do is parse the CLOB column so I can extract those IP addresses; however, the string variable won't hold enough data to even get to the portion of the document where the IP addresses are stored. Any thoughts? A: First, try increasing the PHP memory limit to see if that has any effect on the error. If the CLOB object being retrieved is truly huge, like 2 GiB, then there is no way (currently) to process it in PHP since the whole object must be held in memory. If the column has fixed length data, it should be fairly easy to compose an appropriate query which extracts a portion of it. Assuming the data is encoded as fixed-length text, then something like this will work: // assumes subfield is xxx.xxx.xxx.xxx: 19 fixed characters SELECT substr (TO_CHAR(gnarly_ipadddress_fieldname), 1, 19) as ipaddr1, substr (TO_CHAR(gnarly_ipadddress_fieldname), 20, 19) as ipaddr2, substr (TO_CHAR(gnarly_ipadddress_fieldname), 39, 19) as ipaddr3 FROM table WHERE (whatever); If the subfields are variable length, then maybe grabbing something like 16K chunks and parsing it in PHP is the way to go. A: Based on your comments: If you right click in your browser and say "view source" you'll see that you indeed have the entire file. Most likely you just need to set the appropriate ContentType when emitting the data back to the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GWT using UiBinder vs Pure Java I'm starting a new gwt project, and I've decided to use UiBinder instead of pure java. I'm starting to regret this decision. In fact, I'm starting to think that maybe I should switch to pure java. But before that, I thought I post a question and get your feedback. In my limited experience, UiBinder is all great, until something goes wrong. Then there is no indication of how to solve the problem. All I get from eclipse is "Failed to create an instance of vai deferred binding." Followed by a null pointer stacktrace. Not very useful. And if I want to figure out what's going on, I guess I'll have to figure out where the compiled is stored and scan through that...which defeats the point of having a compiler. Am I missing a compiler option or something that would generate better error messages? Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store forum subcategories in the same table or in a separate table I'd like to hear opinions on if it is better to keep forum categories and subcategories in the same table or in two separate tables... Let's say you have a table ForumCategories. By adding a colum ParentId referencing the PK Id in the same table you could easily keep both the main categories and subcategories in the same table. Alternatively, you could create a separate table ForumSubCategories and make the Id on that table a FK referencing PK Id column of the ForumCategories table. Both solutions would work but what are the pros and cons of each solution? Obviously, this is a more generic question that can apply to many other scenarios I just couldn't come up with a better phrasing in a hurry... A: I can't think of any benefits of using 2 tables. Using 2 tables is going to constrain you to a 2 level tree. If you look at things as objects, then subcategories really are just category object. So put them in the same table. The 1 table structure will be simpler to design around and develop queries for. A: If you know for sure that your forums will have only 2 levels of categories, then having 2 tables is reasonable. Though storing categories in one table with foreign key to itself, basically, allows you store a tree of categories with virutally unlimited levels. A: If they are the same entity (Category), you can link to itself. The parent would have a null for the parent ID or it could be linked to itself. This limits you to only one level unless you have a second table to handle the many-to-many possible relationships. They must have the same fields or you're going to have unecessary fields for one or the other type. A separate table is why you would do this because they're not the same. This is typical for an employee table. The supervisor is another employee record.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery error in using css function after get function It seems the syntax below is wrong because I am getting an error "css is not a function" in Firefox. What's the correct syntax? I am trying to add a css property to the first object in the set. $("div[id$='rvReport']").get(0).css("overflow", "auto"); A: You shouldn't be using .get(). Instead, use .first(): $("div[id$='rvReport']").first().css("overflow", "auto"); You can also use .eq(0) to get the first element. It'll work the same, the only difference being that it's more flexible if you want to return an element that isn't first. A: Use eq(0) instead. $("div[id$='rvReport']").eq(0).css("overflow", "auto"); You could also use first() for readability.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define a parameter recursively in GAMS? I need to define a set of parameters that have a natural recursive relation. Here is a MWE where I try to define the factorial function over a set of (nine) parameters S: $title TitleOfProblem set S / s1*s9 /; alias(S, S1, S2); set delta1(S1,S2); delta1(S1,S2) = yes$(ord(S1) + 1 = ord(S2)); parameter f(S); f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1); display f; "delta1" is a relation containing pairs of elements in sorted order that differ by 1. Logically, the definition of f matches the definition of the factorial function (for inputs 1 to 9), but GAMS doesn't seem to like that f is defined recursively. The output of GAMS compilation looks something like this: f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1); $141 141 Symbol neither initialized nor assigned A wild shot: You may have spurious commas in the explanatory text of a declaration. Check symbol reference list. Question: Is it possible to recursively define a parameter in GAMS? If not, what is a work-around? (P.S. Someone with enough rep should create a tag "GAMS" and add it to this question.) A: Someone showed me a solution for my example using a while loop. However, this solution is specific to factorial and does not generalize to an arbitrary recursive function. $title factorial set S / s1*s9 /; parameter f(S); parameter temp; Loop(S, temp=ord(s); f(S)=ord(s); While(temp > 1, f(S) = f(S) * (temp-1); temp = temp - 1; ); ); display f;
{ "language": "en", "url": "https://stackoverflow.com/questions/7587575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Help Me Understand What is Going On Here? Class/Objects I'm a beginner and I wrote this code: #import <Foundation/Foundation.h> @interface XYPoint : NSObject { int pointX; int pointY; } - (void) print; - (void) setX: (int) x; - (void) setY: (int) y; @end @implementation XYPoint -(void) print { NSLog(@"X is %i and Y is %i", pointX, pointY); } -(void) setX: (int) x { pointX = x; } -(void) setY: (int) y { pointY = y; } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; XYPoint *myCord = [[XYPoint alloc] init]; [myCord setX: 4]; [myCord setY: 6]; [myCord print]; [myCord release]; [pool drain]; return 0; } What I need help with is I cannot for the life of me understand the relationship between "pointX" and setX and "x" A: PointX is called an instance variable - this is what would be called in most other languages a private class-level variable. It represents a piece of information that your class needs to store internally, and by default is not exposed to other objects in the system. setX is a method that you explicitly create, that allows other objects to assign a value to the private PointX instance variable. x is the parameter that the external calling object passes to the setX method. Note that the most common way of exposing access to a private instance variable is through the use of defined properties. In your case, you would add something like this in your interface: @property (nonatomic) int PointX; and then this in your implementation: @synthesize PointX; This syntax allows you to (effectively) directly access the PointX instance variable, by automagically creating a wrapper property (with matching -get and -set methods) with the same name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the ActiveRelation (arel) equivalent to :from I have this named_scope in one of my models: named_scope :latest_100, :from => '(select * from videos order by videos.created_at desc limit 0, 100) as videos' Its purpose is to create a pool of the last 100 videos (returning that results as 'videos' so the other scopes operate on that dataset), and then I can chain scopes after that and filter records out of that pool of results. # video.rb named_scope :most_popular, :order => 'popularity' named_scope :take_5, :limit => 5 # video_controller.rb # it gets the latest 100 videos, then sorts those by popularity, and takes the top 5. @videos = Video.latest_100.most_popular.take_5 Is there an equivalent statement for Arel? A: There exists a .from() method in Arel. I used it in the following manner: # video.rb scope :latest_100, from('(select * from videos limit 100 order by created_at desc) as videos') scope :most_popular, order('popularity') scope :take_5, limit(5) # video_controller.rb @videos = Video.latest_100.most_popular.take_5 The latest_100 will create a pool of valid videos from which you can pull the top 5 most popular.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using an "AS" clause in a sub-query than contains a "WHERE" clause I want to store result in the variable generated by using "AS" clause in the MS Access, and use this result in the sub-query with WHERE clause. I tried this: SELECT en_date AS date_en, (select sum(amount) from main where CrDb='Cr' and en_date=date_en) AS CR_AMT FROM main GROUP BY en_date; A: select m.en_date date_en, sum(m.amount) from main m where CrDb = 'Cr' group by m.en_date In other words, I dont think you even need a sub-query to get the results you are looking for. A: I'm fairly certain you can't use an alias (the AS destination) in the same SELECT you defined it in. I can't tell quite what you're trying to do, but it kind of looks like you want to be joining the table to itself. A: SELECT en_date, SUM(amount) FROM main a INNER JOIN ( SELECT en_date AS date_en, CrDb FROM main WHERE CrDb='Cr' )b ON a.en_date = b.date_en AND a.CrDb = b.CrDb GROUP BY en_date
{ "language": "en", "url": "https://stackoverflow.com/questions/7587591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read binary data from std::cin What is the easiest way to read binary (non-formated) data from std::cin into either a string or a stringstream? A: For windows, you can use the _setmode function in conjunction with cin.read(), as already mentioned. _setmode(_fileno(stdin), _O_BINARY); cin.read(...); See solution source here: http://talmai-oliveira.blogspot.com/2011/06/reading-binary-files-from-cin.html A: On a Unix/POSIX system, you can use the cin.get() method to read byte-by-byte and save the data into a container like a std::vector<unsigned int>, or you can use cin.read() in order to read a fixed amount of bytes into a buffer. You could also use cin.peek() to check for any end-of-data-stream indicators. Keep in mind to avoid using the operator>> overload for this type of operation ... using operator>> will cause breaks to occur whenever a delimiter character is observed, and it will also remove the delimiting character from the stream itself. This would include any binary values that are equivalent to a space, tab, etc. Thus the binary data your end up storing from std::cin using that method will not match the input binary stream byte-for-byte. A: cin.read would store a fixed number of bytes, without any logic searching for delimiters of the type that @Jason mentioned. However, there may still be translations active on the stream, such as CRLF -> NL, so it still isn't ideal for binary data. A: All predefined iostream objects are obligated to be bound to corresponding C streams: The object cin controls input from a stream buffer associated with the object stdin, declared in <cstdio>. http://eel.is/c++draft/narrow.stream.objects and thus the method of obtaining binary data is same as for C: Basically, the best you can really do is this: freopen(NULL, "rb", stdin); This will reopen stdin to be the same input stream, but in binary mode. In the normal mode, reading from stdin on Windows will convert \r\n (Windows newline) to the single character ASCII 10. Using the "rb" mode disables this conversion so that you can properly read in binary data. https://stackoverflow.com/a/1599093/6049796 A: std::cin is not opened with ios_binary. If you must use cin, then you need to reopen it, which isn't part of the standard. Some ideas here: https://comp.unix.programmer.narkive.com/jeVj1j3I/how-can-i-reopen-std-cin-and-std-cout-in-binary-mode Once it's binary, you can use cin.read() to read bytes. If you know that in your system, there is no difference between text and binary (and you don't need to be portable), then you can just use read without worrying. A: cplusplus.com: * *Unformatted input Most of the other member functions of the istream class are used to perform unformatted input, i.e. no interpretation is made on the characters got form the input. These member functions can get a determined number of characters from the input character sequence (get, getline, peek, read, readsome)... As Lou Franco pointed out, std::cin isn't opened with std::ios_base::binary, but one of those functions might get you close to the behavior you're looking for. A: With windows/mingw/msys/bash, if you need to pipe different commands with binary streams in between, you need to manipulate std::cin and std::cout as binary streams. The _setmode solution from Mikhail works perfectly. Using MinGW, the neaded headers are the following: #include <io.h> #include <fcntl.h>
{ "language": "en", "url": "https://stackoverflow.com/questions/7587595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: jQuery toggle toggles itself back to its original state I have two bits of code, nearly the same <div class="favButtonHolder" alt="{% url inturl int.id %}"> {% if int in user.get_profile.favorites.all %} <div class="favorite favButton" style="display:none;">Favorite</div> <div class="favorited favButton">Favorite</div> {% else %} <div class="favorite favButton">Favorite</div> <div class="favorited favButton" style="display:none;">Favorite</div> {% endif %} </div> and <div class="favButtonHolder" alt="{% url inturl result.object.id %}"> {% if result.object in user.get_profile.favorites.all %} <div class="favorite favButton" style="display:none;">Favorite</div> <div class="favorited favButton">Favorite</div> {% else %} <div class="favorite favButton">Favorite</div> <div class="favorited favButton" style="display:none;">Favorite</div> {% endif %} </div> And some matching jQuery: $(document).ready(function() { // Selecting Favorites $('.favButtonHolder').click(function() { var container = $(this); $.get( container.attr('alt'), {'fav': 1}, function() { container.find('.favButton').toggle(); }); }); }); For some reason, when I toggle on the first bit of code, it works just fine. It hides the proper div and displays the proper div. For some unknown reason, when I toggle on the second bit of code, it flips for just a few milliseconds and then flips back (hidden becomes block, and then hidden almost immediately, and vice versa). It is executing the GET, but not toggling properly. Why would this happen? A: Making an answer out of my comment Check your JavaScript files to see if you've duplicated the code you posted. If it's present in two places, when the .click() event fires, two GET requests and two .toggle()s will be triggered, cancelling each other out in respect to the latter. Check your JS files for duplicate code (as you have) and remove it to fix your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update Lookup field using SOAP I'm using the PHP SOAP CRUD classes provided in the CRM 2011 Developer Training Labs. The routines are working fine for standard read, create & updates. However, I can't work out how to define the GUID attribute, e.g. If I want to update the leadsourceid within a contact. Definition below. Result is not an error - it just doesn't complete the update. $accountsRequest = EntityUtils::getUpdateCRMSoapHeader($CRMURL, $securityData). '<s:Body><Update xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"> <entity xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <b:Attributes xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic"> <b:KeyValuePairOfstringanyType> <c:key>originatingleadid</c:key> <c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/">a9cc53ae-266f-e011-8d6c-1cc1de72e35e</c:value> </b:KeyValuePairOfstringanyType> </b:Attributes> <b:EntityState i:nil="true"/> <b:FormattedValues xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic"/> <b:Id>'.$contactId.'</b:Id> <b:LogicalName>contact</b:LogicalName> <b:RelatedEntities /> </entity></Update> </s:Body> </s:Envelope>'; A: To update a lookup value in SOAP you need to use an Entity Reference. The following updates the owner of the record for example. <a:KeyValuePairOfstringanyType> <b:key>ownerid</b:key> <b:value i:type="a:EntityReference"> <a:Id>{6710C3A0-6EE9-E211-B17C-984BE16D3DAA}</a:Id> <a:LogicalName>systemuser</a:LogicalName> <a:Name i:nil="true" /> </b:value> </a:KeyValuePairOfstringanyType>
{ "language": "en", "url": "https://stackoverflow.com/questions/7587605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Microsoft Office Communicator SDK vs Lync SDK Since Lync is the replacement to Microsoft Office Communicator, does that mean that if I write an app that integrates Microsoft Office Communicator 2007 R2, and then later I upgrade to Lync 2010, will I have to rewrite the integration portions of my app? A: Presumably you're talking about client side integration with OCAA or UCCA? These are both still supported against Lync 2010, so your app should still work if you upgrade. However, one or both of these APIs will definitely not be supported against the next version of Lync.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do simple osascript commands fail in OS X Lion? I have two very simple OSA scripts to allow logon and logoff of computers in a lab environment. These scripts work flawlessly in Snow Leopard when pushed via ARD, interactively within an ssh session, but they fail on machines running Lion. Stripped down to its essentials, the logout script looks like this: osascript -e 'tell application "System Events" to log out' * *WORKS when run directly from an interactive shell on a machine *WORKS when pushed from ARD *FAILS with "execution error: The variable out is not defined. (-2753)" when run from an ssh session *WORKS when the script is compiled to an .scpt, then run from ssh (e.g. "/usr/bin/osacript logout.scpt") The login script is directly based on this. A stripped-down version that exhibits the problem is: osascript -e 'tell application "System Events" to keystroke "frontend"' * *WORKS when run directly from an interactive session *WORKS when pushed from ARD *FAILS with execution error: An error of type -10810 has occurred. (-10810) when run from ssh *WORKS when run as a compiled scpt and run from ssh Because these scripts work fine interactively, and because they worked fine in all modes in Snow Leopard, I think something must have changed in osascript, but I don't know what, and the error messages aren't very descriptive. Any suggestions would be welcome. A: Try escaping the quotes. So: osascript -e 'tell application "System Events" to log out' becomes: osascript -e 'tell application \"System Events\" to log out' And osascript -e 'tell application "System Events" to keystroke "frontend"' becomes: osascript -e 'tell application \"System Events\" to keystroke \"frontend\"' Give that a go and tell us what happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get the correct non-virtual MAC address in java I am programming a virtual router. And my first task is to build an Ethernet Frame. I am currently trying to get the MAC source address. I have code that gets all the MAC addresses being used on my machine but I have a virtualbox host network so the code is grabbing this MAC address as well. I am having trouble determining programmatically which MAC address I should be using for my Ethernet Frame. This is my current code private byte[] grabMACAddress(){ try{ InetAddress[] addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); for(int i = 0; i < addresses.length; i++){ NetworkInterface ni = NetworkInterface.getByInetAddress(addresses[i]); mac = ni.getHardwareAddress(); if (mac != null){ for(int j=0; j < mac.length; j++) { String part = String.format("%02X%s", mac[j], (j < mac.length - (1)) ? "" : ""); s += part; } System.out.println(); } else{ System.out.println("Address doesn't exist or is not accessible."); } } } catch(IOException e){ } System.out.println(s); return mac; } A: Support for isolating multiple network interfaces is OS-specific, so no built-in support is available in Java. A simple way to find your 'main' IP address is to connect to a public server, and inspect the 'client address' used for the connection: Socket socket= new Socket(); SocketAddress endpoint= new InetSocketAddress("www.google.com", 80); socket.connect(endpoint); InetAddress localAddress = socket.getLocalAddress(); socket.close(); System.out.println(localAddress.getHostAddress()); NetworkInterface ni = NetworkInterface.getByInetAddress(localAddress); byte[] mac = ni.getHardwareAddress(); StringBuilder s=new StringBuilder(); if (mac != null){ for(int j=0; j < mac.length; j++) { String part = String.format("%02X%s", mac[j], (j < mac.length - (1)) ? "" : ""); s.append(part); } System.out.println("MAC:" + s.toString()); } else{ System.out.println("Address doesn't exist or is not accessible."); } Beyond this, you may want to look into low-level JNI-based libraries for handling low-level network protocols, or even looking up routing tables. Something like http://jnetpcap.com/ may be interesting for you. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7587612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tilt Effect for HubTile I added the TiltEffect.IsTiltEnabled property to my HubTile: <toolkit:HubTile toolkit:TiltEffect.IsTiltEnabled="True" Title="title" Message="This is message" x:Name="name" DisplayNotification="False" Source="pB.png" Tap="tap" /> I also added the HubTile type to the TiltableItems collection in the page's constructor, per the : public HubPage() { TiltEffect.TiltableItems.Add(typeof(HubtTile)); } but the HubTile don't have tilt effect.... Thanks! A: Try adding your HubTile as Content of HyperLinkButton or Button which supports TiltEffect Add a Style to PhoneApplicationPage.Resources which works for Button and HyperLinkButton that adds support for other controls as Content <phone:PhoneApplicationPage.Resources> <Style x:Key="EmptyButtonStyle" TargetType="primitives:ButtonBase"> <Setter Property="Background" Value="Transparent" /> <Setter Property="Padding" Value="0" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="primitives:ButtonBase"> <Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </phone:PhoneApplicationPage.Resources> Also add the primitives namespace to the page xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows" Then use your HubTile as HyperLinkButtons's (or Button) Content like this <HyperlinkButton Style="{StaticResource EmptyButtonStyle}"> <toolkit:HubTile toolkit:TiltEffect.IsTiltEnabled="True" Title="title" Message="This is message" x:Name="name" DisplayNotification="False" Source="pB.png" Tap="tap" /> </HyperlinkButton> This will finally support TiltEffect and HubTile A: Get TiltEffect from Updated Tilt Effect - Peter Torr's Blog OR download the Silverlight Toolkit Source from Silverlight Toolkit - Downloads and then add the HubTile class to the list of 'tiltableItems' in TiltEffect.cs: /// <summary> /// Default list of items that are tiltable /// </summary> static List<Type> tiltableItems = new List<Type>() { typeof(ListBoxItem) , typeof(HyperlinkButton) , typeof(HubTile) }; If you decide to modify the Toolkit, be sure to build the project on Release, and target the .dll you create inside your own application. A: I've found other simple solution that works great when HubTile is used as ListBox.ItemTemplate. Simply set TiltEffect.IsTiltEnabled="True" on ListBox and IsHitTestVisible="False" on HubTile and voila - it works :) You can still respond to HubTile clicks through ListBox.SelectionChanged event and HubTile has working tilt effect. A: Hubtile by default is not added to TiltableItems List and needs to be added manullay... Add the following code to codebehind public MainPage() { InitializeComponent(); TiltEffect.TiltableItems.Add(typeof(HubTile)); // Sample code to localize the ApplicationBar //BuildLocalizedApplicationBar(); } and add the following line to your hubtile or grid containing the hub tile <phone:PanoramaItem CacheMode="{x:Null}" Header="item3" toolkit:TiltEffect.IsTiltEnabled="True">
{ "language": "en", "url": "https://stackoverflow.com/questions/7587613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is "Not Found" necessary in "HTTP/1.1 404 Not Found" I've found that header('HTTP/1.1 404'); works just as well as header('HTTP/1.1 404 Not Found'); in PHP. So I looked in the specification, but couldn't find anything about it; Is the HTTP status header description optional? A: The description can be any human-readable string. Clients may not depend on the string and they must only check the code. However, as usual clients aren't always complying. Browsers will probably do fine, but you can bet that there's HTTP clients out there that specifically check for the string. HTTP/1.1 says: http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1 The client is not required to examine or display the Reason- Phrase. But HTTPbis clarified it with stronger wording: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p1-messaging-16#section-5.1.1 A client SHOULD ignore the content of the Reason Phrase.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bonjour/ZeroConf Implementation for Android(HoneyComb) I am trying to implement bonjour/zero conf on my android app for Android tablet using Honeycomb. I am using jmDns library for searching the all the available devices. I need a list of android devices connected to wifi. Basically, i am adding them in a list so that i can display a list of all available devices. Now when I am running this code on emulator, nothing is added to my list( but there are 5-6 devices in the list) Can anyone please help in providing some code snippet. I am not sure if bonjour/zero conf is supported by Honeycomb or its a problem with my emulator. Thanx in advance A: Emulator has a private virtual network between it and host machine. Zeroconf uses broadcast to query for devices and this query only propagates on this virtual network. http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
{ "language": "en", "url": "https://stackoverflow.com/questions/7587620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using member functions within Sench Touch List itemTpl The documentation about List mention that itemTpl follows the XTemplate syntax. I would like to use member functions in my itemTpl If I initialize itemTpl with an XTemplate and that the member function has no argument it works: items: { xtype: 'list', store: myStore, itemTpl: new Ext.XTemplate('<i>{name} {[this.hello()]}</i>', { hello: function () { return 'Hello'; } }) But as soon as I try to pass an argument (like in the two examples below) it does not work anymore: items: { xtype: 'list', store: myStore, itemTpl: new Ext.XTemplate('<i>{name} {[this.helloWorld(name)}</i>', { helloWorld: function (name) { return 'Hello ' + name; } }) items: { xtype: 'list', store: myStore, itemTpl: new Ext.XTemplate('<i>{name} {name:helloWorld}</i>', { helloWorld: function (string) { return 'Hello ' + name; } }) TypeError: 'undefined' is not a function (evaluating 'fm.helloWorld(values['name'])') I guess I should not create a new Ext.XTemplate object. Is there any solution to pass the member functions without creating a separate XTemplate? Or should I give up on the List and build the list myself in the template? A: The following code should work: items: { xtype: 'list', store: myStore, itemTpl: new Ext.XTemplate( '<i>{name} {[this.helloWorld(values.name)]}</i>', { compiled: true, helloWorld: function (name) { return 'Hello ' + name; } }) } your first example would work, with values.name instead of just name A: Use {[this.helloWorld(name)} instead of {[this.helloWorld(values.name)} A: This usage is also ok: itemTpl :new Ext.XTemplate( '<section class="movieListItem">', '<img src="{UserLogo:this.showLogo}"/>', '<h1>{NickName}</h1>', '<div>{Content}</div>', '</section>', { showLogo:function(value){ } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7587622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Truncating memory mapped file I would like to use a read/write memory mapped file to manage some indexes (unsigned int) I'm creating. I've followed the code examples found here and here I don't know the size of the file initially, so I plan on making it about 4K to start with and grow accordingly. However, I'm unsure how to truncate the file once I'm done with the map. So if I only use about 1K in the file, I would like to truncate it to 1K and not waste 3K in the process. My concern is not specifically with wasting file space, but rather I check the size of the file to determine how many unsigned int I have. EDIT So to clarify...while the file is memory mapped...I'm allocating 4K chunks...when I'm done with the memory mapped file, I want to cleanup the file so it is exactly what I've put into it. A: Use ftruncate to truncate your file, it just requires the file descriptor and a size. Then later you can use fstat to query the properties of the underlying file and use the size you obtain from there to dimension future mappings. A: If you ftruncate() the file, you'll have to "simultaneously" mremap() the mapping to the new size. You can do a similar thing for extents (but that may cause mremap to place the segment in a different part of your address space) A: When you try to optimize, use the value that getpagesize() returns. That is the standard system memory page size, no need to truncate it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Row Header For Cross Tab Report In Crystal Reports I have designed one crystal cross tab report.it is displaying like this col1 col2 col3 row1 row11 val1 val2 val3 row2 row21 val1 val2 val3 but i want heading for the row also i.e. i want report like this name1 name2 col1 col2 col3 row1 row11 val1 val2 val3 row2 row21 val1 val2 val3 can any one help? A: Ryans solution only works for the first page, but he is on the right track. This solution works for all pages 1) The crosstab needs to be in its own group section header. 2) you need to have 2 page header sections. Section 2 (page header a) contains all the text you want to appear on each page including the row header. In my case i have the row headers "Table Curr MinBet" Section 2 (page header a) needs to have the "Underlay Following sections" checkbox checked from Section expert. This makes CR display the page header section underneath the crosstab. 3) PageHeaderSection2 (page header b) is used to space the crosstab to the right position. Without this, the page header and row header appear underneath the crosstab report rather than above it. I am running CR version 13_0_1 for visual studio 2010 A: You can just overlay a text object as the heading.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android: start listener after timing i've an activity with a ToggleButton that must start (if checked on) or stop (if checked off) a listener. The problem is that i want to start the listener after a specific time (10 sec for example) but keeping the ToggleButton active and if the user click on it before the timing ending, abort the timing and listener activation. I'm in confusion with the correct way to do that... do you have any idea? thanks in advance A: Use a Timer and TimerTask. Put the timer on 10 seconds delay. If the user clicks the button again on these 10 seconds, cancel the Timer. If not, start the listener. Note that in order to change UI elements through the TimerTask thread, you will have to use an handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add field to array without index defining - PHP Thanks guys. I was wrong about my way. Please don't post anymore. I had some trouble with my array. I generate my array in this way: private function _getMenuBar(){ $data = array(); $query = $this->db->query("SELECT * FROM df_menubar_table WHERE visible = 1 AND parent = -1 ORDER BY priority"); foreach($query->result_array() as $row){ $data[count($data)] = array( "menu" => array( "title" => $row['title'], "url" => $row['url'], "name" => $row['name'], "selected" => 0 ) ); } return $data; } As usual array will feed like array[0] = menu => array(title,url,name,selected); but I want to not define $data[**count($data)**] as index and define 'menu' as index. And CodeIgniter doesn't support something like this for passing to views. Therefore I need to key be the menu. It means: array[0] = menu => array(title,url,name,selected); To: array['menu'] = array(title,url,name,selected); BTW, I tried += but It just stored the last row. Thanks. Edit: I tried your way it turned to this: I tried it. But it turned to this: array(1) { ["menu"]=> array(5) { [0]=> array(1) { ["menu"]=> array(4) { ["title"]=> string(8) "اصلی" ["url"]=> string(30) "http://localhost/dreamfactory/" ["name"]=> NULL ["selected"]=> int(0) } } A: do an array_shift() on $data. That way, you get rid of the array[0] wrapper. Is this what you meant? If not, pleace be more explicit A: You need some type of unique identifier. Adding multiple items to array['menu'], with no unique identifier, will cause the last/newest item to overwrite the ones before. You can have an array set up like below. Array 1: Array ( [menu] => Array ( [0] => Array ( [title] => Title [url] => URL [name] => Name [selected] => Selected ) ) ) Array 2: Array ( [0] => Array ( [title] => Title [url] => URL [name] => Name [selected] => Selected ) ) The last one can be with or with out the menu item. Code will look like below (simplified) private function _getMenuBar(){ $data = array(); $query = $this->db->query("SELECT * FROM df_menubar_table WHERE visible = 1 AND parent = -1 ORDER BY priority"); $countRows = 0; foreach($query->result_array() as $row){ $data[$countRows] = array( "title" => $row['title'], "url" => $row['url'], "name" => $row['name'], "selected" => 0 ); $countRows++; } return $data; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Rails 3 migration Current migration: t.string "email", :default => "", :null => false add_index :users, :email, :unique => true I want to create a new migration to remove the :null => false requirement and also remove the default => "" for email. Also, I would like to change the index to remove :unique => true. What's the syntax? A: I haven't done much with indices, and there doesn't seem to be a change_index method on ActiveRecord::Migration, but you can try something like this: class ChangeUserStuff < ActiveRecord::Migration def self.up change_column :users, :email, :default => "", :null => true remove_index :users, :column => :email add_index :users, :email end def self.down change_column :users, :email, :default => "", :null => false remove_index :users, :column => :email add_index :users, :email, :unique => true end end There was some funny behavior regarding changing :null options, but I believe setting them to true instead of omitting should handle it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ScheduledDisposable What is a good case/example for using the ScheduledDisposable in Reactive Rx I like the using the CompositeDisposable and SerialDisposable, but would you need the ScheduledDisposable. A: The logic of using the Rx disposables is that code that performs some sort of set up operation can return an IDisposable that anonymously contains the code that will do the associated clean up at a later stage. If this pattern is used consistently then you can compose together many disposables to perform a single clean up operation without any specific knowledge of what is being cleaned up. The problem is that if that clean up code needs to run on a certain thread then you need some way for Dispose called on one thread to be marshalled to required thread - and that's where ScheduledDisposable comes in. The primary example is the SubscribeOn extension method which uses ScheduledDisposable to ensure that the "unsubscribe" (i.e. the Dispose) is run on the same IScheduler that the Subscribe was run on. This is important for the FromEventPattern extension method, for example, that attaches to and detaches from event handlers which must happen on the UI thread. Here's an example of where you might use ScheduledDisposable directly: var frm = new SomeForm(); frm.Text = "Operation Started."; var sd = new ScheduledDisposable( new ControlScheduler(frm), Disposable.Create(() => frm.Text = "Operation Completed.")); Scheduler.ThreadPool.Schedule(() => { // Long-running task Thread.Sleep(2000); sd.Dispose(); }); A little contrived, but it should show a reasonable example of how you'd use ScheduledDisposable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: EF using LINQ trying Contains In passing in a Array Is there a better way to write this CONTAINS from an ARRAY? I am passing a string/array into my LINQ statement. In SQL the code that is working is SELECT * FROM dbo.option1 WHERE option1Code IN ('9841','V237','SV02','2057') In EF using LINQ I am trying using (var ctx = new ProductEntities()) { //--------------------------------------------------------------------// string csvSKU = '984,237,102,207'; string[] mArray = csvSKU.Split(','); var results = (from o in ctx.option1 join p in ctx.Products on o.option1Code equals p.productSKU where mArray.Contains(o.option1Code) orderby o.option1Sort select o).Distinct().ToList(); return results; } A: This looks perfectly fine and should result in similar SQL as you posted (at least for the Contains part). Also not really sure what your join is for right now - are there any option codes that have no entry in the Products table / productSKU?
{ "language": "en", "url": "https://stackoverflow.com/questions/7587636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Computers "Member Of" VBS Script I have the following VBS script and it has been very helpfull when adding multiple new computer accounts to a school that I work for. I would like to know if anyone can modify the script so that it can also add a group to the "Members Of" tab of the newly created computer accounts. Thanks ' Author Guy Thomas http://computerperformance.co.uk/ ' Found at http://www.computerperformance.co.uk/vbscript/vbscript_computer_spreadsheet.htm ' Version 1.2 - May 2010 ' ------------------------------------------------------' Option Explicit Dim strComputer, strOU, strSheet, intRow Dim objRootLDAP, objContainer, objComputer, objShell Dim objExcel, objSpread ' -----------------------------------------------' ' Important change OU= and strSheet to reflect your domain ' -----------------------------------------------' strOU = "OU=New Computers,OU=Workstations,OU=123,OU=Site Based Computer Accounts ," ' Note the comma strSheet = "C:\Documents and Settings\257466\Desktop\Create Computer Accounts\Computer Accounts.xls" ' Bind to Active Directory, Computers container. Set objRootLDAP = GetObject("LDAP://rootDSE") Set objContainer = GetObject("LDAP://" & strOU & _ objRootLDAP.Get("defaultNamingContext")) ' Open the Excel spreadsheet Set objExcel = CreateObject("Excel.Application") Set objSpread = objExcel.Workbooks.Open(strSheet) intRow = 2 'Row 1 often containes headings ' Here is the loop that cycles through the cells Do Until objExcel.Cells(intRow,1).Value = "" strComputer = objExcel.Cells(intRow, 1).Value ' Build the actual computer. Set objComputer = objContainer.Create("Computer", _ "cn=" & strComputer) objComputer.Put "sAMAccountName", strComputer & "$" objComputer.Put "userAccountControl", 4096 objComputer.SetInfo intRow = intRow + 1 Loop objExcel.Quit WScript.Quit A: Thanks to the comment from oracle certified professional, I was able to come up with the following to add the created computers to a group. ' Added section to add the computer to the group ' Comment out with if not needed Dim objGroup, strGroup strGroup = "OU=New Computers,OU=Workstations,OU=123,dc=company,dc=com" Set objGroup = GetObject("LDAP://" & strGroup) objGroup.add objComputer.adspath Just place the above lines between objComputer.SetInfo and intRow = intRow + 1 and it will add the computer to a group.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript eval for boolean expression evaluation I need to evaluate a boolean expression built by the user. I see two ways to do it: 1) build a string and pass it off to eval 2) build an abstract syntax tree and evaluate it myself I have implemented it with eval since it's the simplest solution. I'm not convinced that the second option is going to be much better, i wouldn't be surprised if it was actually slower. Security shouldn't be an issue since i'm building the expression from a set of predetermined values. In most cases the expressions are going to be pretty simple, but it's possible to build more complex expressions. This is about as complex as it's going to get: "(true||false&&false)&&(true)" Thoughts? A: I think this is a valid usecase for eval. However, if you were to ever want to use CSP (content security policy), which is awesome.. eval may be disabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mac App Store Sample Receipt... Where Is It? I'm adding some features to a pre-existing mac app that uses receipt verification. The way the app was coded, it relied on Apple's sample receipt to be on the desktop (for debugging). The URL that the receipt used to be at now redirects to a different page. Where can I get this sample receipt?! Old URL: http://developer.apple.com/devcenter/mac/documents/validating.html#//apple_ref/doc/uid/TP40010573-CH1-SW21 UPDATE For future internet surfers looking for the answer. I found it at this url: http://images.worldofapple.com/validating_051110.pdf You'll have to format the text before creating a usable receipt. TextWrangler with a find and replace of "\r\r" -> "\r" did the trick. Also, do that off the HTML representation. The PDF version is all gunked up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Ruby can't find the method capture2e from open3 module I am trying to use the script blogger.rb and I just can't get it work. It keeps giving me the error : blogger.rb:294:in text2html': undefined methodcapture2' for Open3:Module (NoMethodError) The script does a require Open3 in the beginning. I don't understand where is the problem ! I have no knowledge of Ruby. However, I can intelligently read and edit codes in general. A: I'd guess that you're using Ruby 1.8 but the script requires 1.9. The Open3 class in 1.8.7 has a popen3 class method and nothing else. The Ruby 1.9 Open3 has the capture2 and capture2e class methods that you're looking for. So you need to upgrade your Ruby to 1.9 or find another script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting Single OR Double Tap I'm trying to add 2 actions inside an IBAction, one for 1 tap and a different one for a double tap, and I came up with this code: .h UITouch * touch; .m - (IBAction) button { BOOL tappedTwice = NO; if ([touch tapCount] == 2) { tappedTwice = YES; // Action } else if ([touch tapCount] == 1 && !tappedTwice) { // Action } } No errors, no warnings, but nothing happens when I tap the button... Any ideas??? A: You cannot capture events like that. The Action is tagged to touchUpInside event so you cannot capture single tap or double tap Try this link http://sree.cc/iphone/handling-touche-events-for-uibuttons-in-iphone
{ "language": "en", "url": "https://stackoverflow.com/questions/7587644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I move an element up/down one position in tree I cannot seem to find what should be a basic function of JavaScript. I want to move an element up one position or down one position by a button click. jQuery and other proprietary libraries are not an option. function moveDown() { if (document.getElementById('CMSeditingNode')) { var node = document.getElementById('CMSeditingNode'), parent = node.parentNode, nextNode = node.nextSibling, secondNode = nextNode.nextSibling, oldChild = parent.removeChild(node); parent.insertBefore(oldChild, secondNode); } } The answer worked perfectly and I have add to this post a supplement for insertAfter(). A: The methods/properties you're looking for are parentNode, previousSibling, nextSibling, removeChild, insertBefore, and insertAfter. A snippet might look like: var node = document.getElementById('somenode'), parent = node.parentNode, prev = node.previousSibling, oldChild = parent.removeChild(node); parent.insertBefore( oldChild, prev ); Just for comparison, the (complete) jQuery for this would be: var $node = $('#somenode'), $node.prev().before($node);
{ "language": "en", "url": "https://stackoverflow.com/questions/7587646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Symfony2 FOSUserBundle Registration Role Exception i am quite new in Symfony2, i`ve tried to use FOSUserBundle, most of it works fine, but when i try to register i do always get same result: Warning: Invalid argument supplied for foreach() in /var/www/own/envelope/vendor/bundles/FOS/UserBundle/Model/User.php line 372 500 Internal Server Error - ErrorException And in Stack Trace i can see that this is caused the empty array with Roles, but i really do have no idea where i can find it or what i should add to configs or somewhere else. I didn`t override any controlers, only template for registration, but i think i use proper one. Thanks for answers. A: I deleted the method getGroups and addGroups from my custom User Class and it solved the problem. A: Ok, i did found what is a problem - i didn't add any Role for Group. So in FOSUserBundle each Group has to have a Role, that`s it. A: I'm not sure if my problem was exactly the same but atleast it was similar. The error message was the same. After searching for hours I finally understood what went wrong and looking back it has actually been an obvious mistake. The only thing I had to do was add the following line to the __constructor function of the user class: $this->groups = new \Doctrine\Common\Collections\ArrayCollection(); It may not have been the OPers solution but maybe it can help someone else! A: i got exactly same error but i solved this by constructor overloading of user class public function __construct(){ $this->groups = new \Doctrine\Common\Collections\ArrayCollection(); return parent::__construct(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing user credentials to a Webservice We have a website that calls a remote web service. This web service is stateless and needs the credentials every time to get the data back. How do we pass the credentials back and forth? for example a call to string GetAddress( userid,password) Is it ok to store the credentials in a session and pass them across https in post ? What is the best way to do this? A: According to me it is ok to use session as they will be at server. another alternative as per me I dont know it will be useful to you or not but use XML to share credential. I have used such application on my previous project so on that basis I am suggesting you to use xml. OR session over ssl will also be good.. Check it if better way exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XCode 4 -> Quick way to jump (or switch) to super class If we press ctrl+command+up arrow we switch between file code and header code. (.m to .h) If we press ctrl+command+j or command + mouse click we jump to definition of variable. But it not work for super. So, there are a fast way to do it? A: I'm a little late to the party, but here's a good method for seeing both superclasses and subclasses. Click on the related files icon. It looks like this: and you'll find it in the upper left of the edit window. You'll get a menu of many kinds of related files among which will be the superclass and subclass lists. You can also open that menu using Ctrl+1, if you happen to be a keyboard person. A: Try Command + Shift + D. Jump to definition. Does that work? Also check out the link bellow. It lists a bunch of Xcode keyboard shortcuts. http://developer.apple.com/library/mac/#documentation/IDEs/Conceptual/xcode_help-command_shortcuts/Introduction/Introduction.html%23//apple_ref/doc/uid/TP40010560-CH1-SW1
{ "language": "en", "url": "https://stackoverflow.com/questions/7587654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: After upgrading Ruby1.9.2 from p180 to p290, libruby dynamic library path isn't updated I used RVM to upgrade Ruby 1.9.2 from patch level p180 to p290: rvm upgrade 1.9.2-p180 1.9.2-p290 Then, I used these commands to update my Rails gem and other gems gem install rails 3.0.5 gem update Everything seems to be fine; rvm info shows all Ruby binaries and gems have been moved to the correct p290 path (~/.rvm/*/ruby-1.9.2-p290/*). However, when I go to my Rails application directory and issue the command rails console, I get the error message saying a gem (activesupport-3.0.5) cannot load the libruby.1.9.1.dylib file. 10:30 AM ~/Development/rails_projects/my_app_0515 $ rails console /Users/whk/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `require': dlopen(/Users/whk/.rvm/gems/ruby-1.9.2-p290/gems/serialport-1.0.4/lib/serialport.bundle, 9): Library not loaded: /Users/whk/.rvm/rubies/ruby-1.9.2-p180/lib/libruby.1.9.1.dylib (LoadError) Referenced from: /Users/whk/.rvm/gems/ruby-1.9.2-p290/gems/serialport-1.0.4/lib/serialport.bundle Reason: image not found - /Users/whk/.rvm/gems/ruby-1.9.2-p290/gems/serialport-1.0.4/lib/serialport.bundle . . . Rails can't find the dylib file in ~/.rvm/rubies/ruby-1.9.2-p180/lib, because the p180 path no longer exists, but the file is in ~/.rvm/rubies/ruby-1.9.2-p290/lib. From a separate StackOverflow post, I found a workaround is adding this line to .bashrc export DYLD_LIBRARY_PATH="/Users/whk/.rvm/rubies/ruby-1.9.2-p290/lib:$DYLD_LIBRARY_PATH" However, I want to understand why the rvm ruby upgrade doesn't take care of the lib path change? Does anyone know a cleaner solution -- one that removes the p180 path from where it is configured? Here are my environment: * *Mac OS X 10.6.6 (Snow Leopard) *rvm 1.8.4 *ruby 1.9.2p290 *Rails 3.0.5 Thanks! A: the problem was in gems native extension - their were nto rebuild during rvm upgrade 1.9.2-p180 1.9.2-p290 - next time please have closer look on the output ... it should give your information what's wrong. as for this particular use case it shoudl be enough to reinstall the given gem: gem install serialport -v 1.0.4 ... not sure if it should be uninstalled first
{ "language": "en", "url": "https://stackoverflow.com/questions/7587655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Building Intrusion Detection System but from where to begin I have searched a lot on Intrusion Detection system but now I am confused as now from where should I start. I dont know whether any open source reusable codes exists but I want to make Intrusion Detection and Prevention System with Neural Network. From the Developer point of view my question is from where should I begin with. Kindly guide me on this topic. Also I am presently working and analysing KDD CUP 1999 Dataset. And in search for more such data sets. Kindly tell me which will be the best algorithms for building Intrusion Detection System. Thanks to whomsoever reply or read.. Kindly guide me on this. Thanks in advance. A: I study in the same subject. Intrusion detection and machine learning. It is rather broad subject. I will answer more about data pre-processing and feature construction point of view. Neural Network part is different story altogether. First of all, this area is heavily commercialized therefore there is almost no open source code examples. A lot things are done commercially in a closed ecosystem. From academic perspective: There is a big data set problem. DK99C (Darpa - KDD99 data set) exists but it is very old. KDD99 dataset is constructed from DARPA tcpdumps. They used bro IDS , tcpdump api to construct features. From my perspective it is a lot harder to create features from raw tcpdump than working with machine learning algorithms (Neural Network) on ready features. Read this article to learn more about how it (KDD99) is constructed Article (Lee2000framework) Lee, W. & Stolfo, S. J. A framework for constructing features and models for intrusion detection systems ACM Trans. Inf. Syst. Secur., ACM, 2000, 3, 227-261 Read this article and its presentation to learn why this subject is a hard problem to study. Inproceedings (Sommer2010Outside) Sommer, R. & Paxson, V. Outside the Closed World: On Using Machine Learning for Network Intrusion Detection Proceedings of the 2010 IEEE Symposium on Security and Privacy, IEEE Computer Society, 2010, 305-316 Read this article to see how most academics work in this subject. A bit disappointing really. Article (Tavallaee2010Toward) Tavallaee, M.; Stakhanova, N. & Ghorbani, A. Toward Credible Evaluation of Anomaly-Based Intrusion-Detection Methods Systems, Man, and Cybernetics, Part C: Applications and Reviews, IEEE Transactions on, 2010, 40, 516 -524 Read this why DK99C is considered harmful. It is harmful but no other credible dataset exists. Article (Brugger2007KDD) Brugger, S. KDD Cup’99 dataset (Network Intrusion) considered harmful KDnuggets newsletter, 2007, 7, 15 Read this about taxonomy of IDS data pre processing Article (Davis2011Data) Davis, J. J. & Clark, A. J. Data preprocessing for anomaly based network intrusion detection: A review Computers & Security, 2011, 30, 353 - 375 A: Most intrusion detection systems which use Neural Networks make use of supervised training, ie. the system prompts you for an opinion when certain changes are requested to its host. I suggest that you start with finding out the methodology for hooking change requests. In windows that could involve using a system hook to filter certain actions that are requested by applications. This will allow your app the option of prompting you for a response, that response will overtime be fed into the neural net. This dataset then can be used to optimize the recognition of certain patterns and your responses to those patterns. There are obviously more things to consider when building a system such as this but you should be off to a good start based on what I said.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visual Studio 11 italic parameters I'm currently trying out the new Visual Studio 11 which can be obtained here. And I must say I do like it :) I have only some small nuisances with it... VS11 now supports some new coloring options for keywords/typedefs/etc and also for parameters you get passed in a function. Some hipster at Microsoft decided they should display italic... And ugh it is ugly and I can't turn it off! In the 'Fonts and Colors' section only bold can be ticked and unticked. Does anyone know some registry/xml-file hack to change the font to non-italic again? A: You can try changing values for the following reg-key: HKEY_CURRENT_USER\Software\Microsoft\Visual Studio\11.0\FontAndColors\{*****}\***** FontFlags
{ "language": "en", "url": "https://stackoverflow.com/questions/7587658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Filter null or empty input using LOAD DATA INFILE in MySQL I have some very large files (millions of records) that I need to load into a database. They are of the form: word1\tblahblahblah word2\tblahblah word3\tblahblah word4 word5\tblahblah ... My problem, is that I want to ignore the lines that have no second record (the 'blahblah's'), like word4. I'm currently using the following query to load the file: LOAD DATA LOCAL INFILE 'file' IGNORE INTO TABLE tablename COLUMNS TERMINATED BY '\t' LINES TERMINATED BY '\n' (col1, col2); This has the functionality I want, except that it still accepts the null values. Is there a way to skip the word4 type lines and not add them to the DB? Intuitively, I thought using a WHEN or WHERE clause would be perfect, but looking through documentation and other info online, I can't find any examples where this would work. Am I forced to filter these records out before hand, or can I do it within this query? Any help is grealy appreciated! A: I would do this by filtering the file with grep or awk and then piping it into MySQL (via /dev/stdin). Something like this: cat your_file.txt | awk '/\t.+/' | mysql -u your_username -pyour_password \ -e "LOAD DATA LOCAL INFILE '/dev/stdin' \ IGNORE INTO TABLE tablename \ COLUMNS TERMINATED BY '\t' \ LINES TERMINATED BY '\n' \ (col1, col2);" \ your_database_name The regular expression given to awk on the second line just matches any line that has a tab character followed by one or more of any character. You might want to tweak it to fit your needs. Edit: One other possibility occurred to me. You could use SET to set some magic value on columns that are blank and put a BEFORE INSERT trigger on the table that will bail on a row when it sees that value. I don't have much experience with triggers but I think something like this should work: CREATE TRIGGER skip_magic_rows BEFORE INSERT ON tablename FOR EACH ROW BEGIN IF NEW.col2 = 'IDSPISPOPD4815162342' THEN # Some unlikely magic string # Trigger an error, which will cause the INSERT to fail† # If you have MySQL < 5.5 this is kludgy -- see Note 1 DROP TABLE `Skipped row` # OR # In MySQL >= 5.5 you can send a signal--'45000' is a generic error SIGNAL SQLSTATE '45000' SET message_text = 'Skipped row'; # See Note 2 END IF END ; †: Per the docs: An error during either a BEFORE or AFTER trigger results in failure of the entire statement that caused trigger invocation. Then... LOAD DATA LOCAL INFILE 'file' IGNORE INTO TABLE tablename COLUMNS TERMINATED BY '\t' LINES TERMINATED BY '\n' (col1, @var2) SET col2 = IF(@var2 IN (NULL, ''), 'IDSPISPOPD4815162342', @var2) ; Hope it's helpful! Note 1: Relevant blog post and comments Note 2: Relevant SO thread
{ "language": "en", "url": "https://stackoverflow.com/questions/7587660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AS3 Returning a variable from an event listener function I'm trying to return XML from an event complete back to the main function, but can't figure out how to do it. Here's the functions I'm calling: Main File: public var mySendAndLoad:SendAndLoad = new SendAndLoad(); mySendAndLoad.sendData(url,variables) The mySendAndLoad class: package { import flash.events.*; import flash.net.*; import flash.xml.XMLDocument; public class SendAndLoad { public var xml:XML = new XML(); public var xmlList:XMLList; public function SendAndLoad() { } public function sendData(url:String, _vars:URLVariables):String { var request:URLRequest = new URLRequest(url); var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.TEXT; request.data = _vars; request.method = URLRequestMethod.POST; loader.addEventListener(Event.COMPLETE, handleComplete); loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError); loader.load(request); } private function handleComplete(event:Event):String { var loader:URLLoader = URLLoader(event.target); xml = XML(loader.data); xmlList = xml.children(); return(xmlList[1]); } private function onIOError(event:IOErrorEvent):void { trace("Error loading URL."); } } } What I want to happen is have the xmlList come back to the main file. But since it isn't in the event I called (sendData) it doesn't get brought back. Any ideas? A: package { import flash.events.*; import flash.net.*; import flash.xml.XMLDocument; //THIS CLASS EXTENDS EVENTDISPATCHER SO IT CAN DISPATCH EVENTS public class SendAndLoad extends EventDispatcher { public var xml:XML = new XML(); public var xmlList:XMLList; public function SendAndLoad() { super(null); } public function sendData(url:String, _vars:URLVariables):void { var request:URLRequest = new URLRequest(url); var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.TEXT; request.data = _vars; request.method = URLRequestMethod.POST; loader.addEventListener(Event.COMPLETE, handleComplete); loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError); loader.load(request); } private function handleComplete(event:Event):void { var loader:URLLoader = URLLoader(event.target); xml = XML(loader.data); xmlList = xml.children(); //NEW CODE var evt:Event=new Event(Event.COMPLETE); dispatchEvent(evt); //return(xmlList[1]); } private function onIOError(event:IOErrorEvent):void { trace("Error loading URL."); } } } and in the main file public var mySendAndLoad:SendAndLoad = new SendAndLoad(); mySendAndLoad.addEventListener(Event.COMPLETE, xmlLoadCompleted); mySendAndLoad.sendData(url,variables) private function xmlLoadCompleted(e:Event):void { var childToUse:XML=mySendAndLoad.xmlList[1]; //whatever else you want to do } A: Without serious modifications you have two options: * *Your SaveAndLoad class to derrive EventDispatcher and send a custom event with the data in it. *More clean/non obtrusive is to make sendData method modifications: public function sendData(url:String, _vars:URLVariables, resultHandler:Function=null):String { loader.addEventListener(Event.COMPLETE, resultHandler); } You can pass a function defined in your main file, still have the ability to attach inner listeners for whatever you want in SaveAndLoad class, and you will have your data. A: Just dispatch an event package { import flash.events.Event; import flash.display.Sprite; import flash.events.*; import flash.net.*; import flash.xml.XMLDocument; public class SendAndLoad extend Sprite { public var xml:XML = new XML(); public var xmlList:XMLList; public function SendAndLoad() { } public function sendData(url:String, _vars:URLVariables):String { var request:URLRequest = new URLRequest(url); var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.TEXT; request.data = _vars; request.method = URLRequestMethod.POST; loader.addEventListener(Event.COMPLETE, handleComplete); loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError); loader.load(request); } private function handleComplete(event:Event):String { var loader:URLLoader = URLLoader(event.target); xml = XML(loader.data); xmlList = xml.children(); // return(xmlList[1]); this.dispatchEvent( new Event( 'ONDATA' ) ); } private function onIOError(event:IOErrorEvent):void { trace("Error loading URL."); } } } // usage var sender:SendAndLoad = new SendAndLoad( ); sender.addEventListener( 'ONDATA', myXMLLoaded); sender.sendData( url, _vars ) function myXMLLoaded( e:Event ):void{ trace(sender.xml); } A: You must use dispatchEvent; first declare to it public class personal_info extends EventDispatcher { } and you must define listener into that class dispatchEvent(new Event(Event.COMPLETE)); A: you must declare variable such as public public var variable:String; You must use dispatchEvent; first declare to it public class personal_info extends EventDispatcher { ... and you must define listener into that complete event variable = "variable"; dispatchEvent(new Event(Event.COMPLETE)); ... And you must call just like calling normal event in another class var sample:SampleClass = new SampleClass (); sample.addEventListener(Event.COMPLETE , cComplete); And you can use that variable in this class like: private fonction (e:Event):void { trace (e.target.variable); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access the properties of an instance of a derived class which is passed as a parameter in the form of the base class In C# I have a base class and a derived class. I have a function which has the base class as an input parameter public void SomeFunction(BaseClass InstanceOfDerivedClass) Is there a way I can access the properties specific to the derived class, even though it has been passed as a base class? Could I use GetType or Cast or something like that? I appreciate that the solutions may not be elegant but at the moment the alternative is to repeat this function many times for the different derived classes. A: Casting should definitely do the trick, since the reference in the heap is to that class. Maybe something like: if (InstanceOfDerivedClass is DerivedClass) And in that block you can cast it and interact with it. But the bigger question is, why do you need to? It sounds like this method is using the wrong abstraction if the type being accepted as an argument isn't the correct type. This is breaking Liskov Substitution and looks like a prime candidate for refactoring the design. (Of which we don't know enough to help much.) A: you could do this (bad way): public void SomeFunction(BaseClass instanceOfDerivedClass) { DerivedClass derived = null; if(instanceOfDerivedClass is DerivedClass) { derived = instanceOfDerivedClass as DerivedClass; // Do stuff like : int prop = derived.DerivedProperty; } } Or, as suggested by Eric (good way): public void SomeFunction(BaseClass instanceOfDerivedClass) { DerivedClass derived = instanceOfDerivedClass as DerivedClass; if(derived != null) { // Do stuff like : int prop = derived.DerivedProperty; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ringtone Preference not saving choice I have a ringtone preference in my app but when I select the tone I want, it does not get stored in the preference value. I can click the preference again and it will not show what I just selected. here is the XML <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Audio Settings"> <CheckBoxPreference android:key="SMS_PREF_TTS" android:title="Say name of sender" android:summary="When a person in your contact list sends you a sms/mms message its says their name" android:defaultValue="false"> </CheckBoxPreference> <CheckBoxPreference android:key="SMS_PREF_TTS_MSG" android:title="Say Message" android:summary="Will say the message of sender from contact list" android:dependency="SMS_PREF_TTS" android:defaultValue="false"> </CheckBoxPreference> <RingtonePreference android:key="SMS_PREF_SOUND" android:title="Change Sound" android:ringtoneType="notification" android:summary="Select the notification Sound" android:dialogTitle="Change Sound" android:defaultValue="Silent"> </RingtonePreference> </PreferenceCategory> </PreferenceScreen> and the weird thing is I just wrote another xml for another part of my app with a ringtone preference looking the same way and that one works so I dont understand. here is the working one <RingtonePreference android:key="CAL_PREF_TONE" android:title="Default ringtone" android:summary="Select default notification ringtone" android:ringtoneType="notification" android:defaultValue="Silent" android:dependency="CAL_PREF_ON"> </RingtonePreference> A: If you have overriden onActivityResult() and forgotten to call super.onActivityResult() you can see this problem as well. See RingtonePreference not firing OnPreferenceChangeListener A: I had the same problem. In the AndroidManifest.xml file I had my preference activity set with noHistory="true". Once I removed it everything worked correctly. A: I ended up saving it manually by registering a onPreferenceClickListener and getting the result A: I managed to resolve this by removing android:launchMode="singleInstance" and android:excludeFromRecents="true" from the settings activity entry on AndroidManifest.xml (setting either or both of these options will cause the same issue). It seems to be a bug on Android. A: the solution I used was provided by Udo Held, I just wanted to add one thing, I had to remove the launchMode="singleInstance" and I am now using android:launchMode="singleTask" and everything works fine. Just in case someone else needs a launchMode, this one worked for me. A: I just had the same problem, but then I reviewed my codes, when I read the preference: SharedPreferences settings = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE); Which is wrong, the correct solution is: SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7587668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: AppEngine mapper API import error EDIT: I just gave it a go on appengine itself and it seems like it actually works there, so the problem is just with the dev server. I would still be interested in understanding why this is happening... I am using the AppEngine mapper API (mapreduce) and am having a problem with imports. Here is my file structure: ├── [ost 12] app.yaml -> src/app.yaml ├── [ost 4096] doc ├── [ost 615] fabfile.py ├── [ost 18] gae -> /home/ost/dev/gae/ ├── [ost 70] INFO ├── [ost 0] LICENSE ├── [ost 5] README ├── [ost 38] run_clean ├── [ost 64] run_deploy ├── [ost 83] run_pylint ├── [ost 78] run_tests ├── [ost 4096] src │   ├── [ost 4096] admin │   ├── [ost 504] app.yaml │   ├── [ost 4822] data.py │   ├── [ost 4096] dhandler │   ├── [ost 2273] ds.html │   ├── [ost 5424] generator.py │   ├── [ost 0] __init__.py │   ├── [ost 3527] lib.py │   ├── [ost 4211] main.py │   ├── [ost 457] mappers.py │   ├── [ost 298] mapreduce.yaml │   ├── [ost 4192] parser.py │   └── [ost 4096] static ├── [ost 4096] test │   └── [ost 2445] test_data.py └── [ost 98] TODO My app.yaml is: application: <removed> version: 1 runtime: python api_version: 1 builtins: - datastore_admin: on - appstats: on handlers: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin - url: /admin script: admin/admin.py login: admin - url: /dhandler/.* script: dhandler/dhandler.py - url: /mapreduce(/.*)? script: $PYTHON_LIB/google/appengine/ext/mapreduce/main.py login: admin - url: /static static_dir: static - url: /.* script: main.py My mapreduce.yaml: mapreduce: - name: insert-domain-mapper params: - name: done_callback value: /dhandler/insert_job_done mapper: input_reader: google.appengine.ext.mapreduce.input_readers.BlobstoreLineInputReader handler: mappers.insert_domain params: - name: blob_keys default: "" Finally mappers.py from google.appengine.ext.mapreduce import operation as op from data import RegisteredDomain, make_key, clean_domain def insert_domain((byte_offset, line)): domain = line # TODO: domain validity check (??) # clean domain domain = clean_domain(domain) # create domain entity domain_entity = RegisteredDomain(key_name=make_key(domain)) # yield put operation yield op.db.Put(domain_entity) Now the problem is that, although I can load the /mapreduce page and the job is available, as soon as I try to start the job I get the following error (on the page): ImportError: Could not find 'input_readers' on path 'google.appengine.ext.mapreduce' Here is a complete stack trace: DEBUG 2011-09-28 18:30:54,829 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_CONNECTION': 'keep-alive', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'HTTP_COOKIE': 'dev_appserver_login="test@example.com:True:1858 04764220139124118"', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'CURRENT_VERSION_ID': '1.1', 'SERVER_S OFTWARE': 'Development/1.0', 'SCRIPT_NAME': '', 'USER_ORGANIZATION': '', 'REQUEST_METHOD': 'GET', 'HTTP_HOST': '10.1 .2.20:8000', 'PATH_INFO': '/mapreduce/status', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_STRING': '', 'TZ': 'UTC', 'HTTP _CACHE_CONTROL': 'max-age=0', 'USER_EMAIL': 'test@example.com', 'USER_IS_ADMIN': '1', 'CONTENT_LENGTH': '', 'USER_ID ': '185804764220139124118', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like G ecko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich', 'SERVER_NAME': '10.1.2.20', 'REMOTE _ADDR': '10.1.2.5', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'SDK_VERSION': '1.5.2' , 'PATH_TRANSLATED': '/home/ost/dev/gae/google/appengine/ext/mapreduce/main.py', 'SERVER_PORT': '8000', 'AUTH_DOMAIN ': 'gmail.com'} DEBUG 2011-09-28 18:30:54,830 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" INFO 2011-09-28 18:30:54,841 dev_appserver.py:4248] "GET /mapreduce/status HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:54,843 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:54,890 dev_appserver.py:589] Matched "/mapreduce/base.css" to CGI dispatcher with path $PY THON_LIB/google/appengine/ext/mapreduce/main.py DEBUG 2011-09-28 18:30:54,894 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': 'text/css,*/*;q=0.1', 'HTTP_CONNECTION': 'keep-alive', 'CONTENT_TYPE': 'application/x-www-form-urlen coded', 'HTTP_REFERER': 'http://10.1.2.20:8000/mapreduce/status', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q =0.3', 'CURRENT_VERSION_ID': '1.1', 'SERVER_SOFTWARE': 'Development/1.0', 'SCRIPT_NAME': '', 'USER_ORGANIZATION': '' , 'REQUEST_METHOD': 'GET', 'HTTP_HOST': '10.1.2.20:8000', 'PATH_INFO': '/mapreduce/base.css', 'SERVER_PROTOCOL': 'HT TP/1.0', 'QUERY_STRING': '', 'TZ': 'UTC', 'USER_EMAIL': 'test@example.com', 'USER_IS_ADMIN': '1', 'CONTENT_LENGTH': '', 'USER_ID': '185804764220139124118', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (K HTML, like Gecko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich', 'HTTP_COOKIE': 'dev_app server_login="test@example.com:True:185804764220139124118"', 'SERVER_NAME': '10.1.2.20', 'REMOTE_ADDR': '10.1.2.5', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'SDK_VERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/dev/gae/google/appengine/ext/mapreduce/main.py', 'SERVER_PORT': '8000', 'AUTH_DOMAIN': 'gmail.com'} DEBUG 2011-09-28 18:30:54,895 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" INFO 2011-09-28 18:30:54,902 dev_appserver.py:4248] "GET /mapreduce/base.css HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:54,903 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:54,911 dev_appserver.py:589] Matched "/mapreduce/jquery.js" to CGI dispatcher with path $P YTHON_LIB/google/appengine/ext/mapreduce/main.py DEBUG 2011-09-28 18:30:54,915 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': '*/*', 'HTTP_CONNECTION': 'keep-alive', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'HTTP_R EFERER': 'http://10.1.2.20:8000/mapreduce/status', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'CURRENT _VERSION_ID': '1.1', 'SERVER_SOFTWARE': 'Development/1.0', 'SCRIPT_NAME': '', 'USER_ORGANIZATION': '', 'REQUEST_METH OD': 'GET', 'HTTP_HOST': '10.1.2.20:8000', 'PATH_INFO': '/mapreduce/jquery.js', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUER Y_STRING': '', 'TZ': 'UTC', 'USER_EMAIL': 'test@example.com', 'USER_IS_ADMIN': '1', 'CONTENT_LENGTH': '', 'USER_ID': '185804764220139124118', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gec ko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich', 'HTTP_COOKIE': 'dev_appserver_login=" test@example.com:True:185804764220139124118"', 'SERVER_NAME': '10.1.2.20', 'REMOTE_ADDR': '10.1.2.5', 'GATEWAY_INTER FACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'SDK_VERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/de v/gae/google/appengine/ext/mapreduce/main.py', 'SERVER_PORT': '8000', 'AUTH_DOMAIN': 'gmail.com'} DEBUG 2011-09-28 18:30:54,916 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" INFO 2011-09-28 18:30:54,924 dev_appserver.py:4248] "GET /mapreduce/jquery.js HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:54,931 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:54,938 dev_appserver.py:589] Matched "/mapreduce/status.js" to CGI dispatcher with path $P YTHON_LIB/google/appengine/ext/mapreduce/main.py DEBUG 2011-09-28 18:30:54,942 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': '*/*', 'HTTP_CONNECTION': 'keep-alive', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'HTTP_R EFERER': 'http://10.1.2.20:8000/mapreduce/status', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'CURRENT _VERSION_ID': '1.1', 'SERVER_SOFTWARE': 'Development/1.0', 'SCRIPT_NAME': '', 'USER_ORGANIZATION': '', 'REQUEST_METH OD': 'GET', 'HTTP_HOST': '10.1.2.20:8000', 'PATH_INFO': '/mapreduce/status.js', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUER Y_STRING': '', 'TZ': 'UTC', 'USER_EMAIL': 'test@example.com', 'USER_IS_ADMIN': '1', 'CONTENT_LENGTH': '', 'USER_ID': '185804764220139124118', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gec ko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich', 'HTTP_COOKIE': 'dev_appserver_login=" test@example.com:True:185804764220139124118"', 'SERVER_NAME': '10.1.2.20', 'REMOTE_ADDR': '10.1.2.5', 'GATEWAY_INTER FACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'SDK_VERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/de v/gae/google/appengine/ext/mapreduce/main.py', 'SERVER_PORT': '8000', 'AUTH_DOMAIN': 'gmail.com'} DEBUG 2011-09-28 18:30:54,943 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" INFO 2011-09-28 18:30:54,951 dev_appserver.py:4248] "GET /mapreduce/status.js HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:54,953 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:54,972 dev_appserver.py:589] Matched "/mapreduce/command/list_configs" to CGI dispatcher w ith path $PYTHON_LIB/google/appengine/ext/mapreduce/main.py DEBUG 2011-09-28 18:30:54,976 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': 'text/plain, */*', 'HTTP_CONNECTION': 'keep-alive', 'USER_IS_ADMIN': '1', 'HTTP_COOKIE': 'dev_appser ver_login="test@example.com:True:185804764220139124118"', 'CURRENT_VERSION_ID': '1.1', 'SERVER_SOFTWARE': 'Developme nt/1.0', 'SCRIPT_NAME': '', 'USER_ORGANIZATION': '', 'USER_ID': '185804764220139124118', 'REQUEST_METHOD': 'GET', 'H TTP_HOST': '10.1.2.20:8000', 'PATH_INFO': '/mapreduce/command/list_configs', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_S TRING': '', 'TZ': 'UTC', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'USER_EMAIL': 'test@example.com', 'CONTENT_LENGT H': '', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WO W64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich' , 'HTTP_REFERER': 'http://10.1.2.20:8000/mapreduce/status', 'SERVER_NAME': '10.1.2.20', 'REMOTE_ADDR': '10.1.2.5', ' CONTENT_TYPE': 'application/x-www-form-urlencoded', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,e n;q=0.8', 'SDK_VERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/dev/gae/google/appengine/ext/mapreduce/main.py', 'SE RVER_PORT': '8000', 'AUTH_DOMAIN': 'gmail.com'} DEBUG 2011-09-28 18:30:54,977 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" INFO 2011-09-28 18:30:54,991 dev_appserver.py:4248] "GET /mapreduce/command/list_configs HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:54,992 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:54,999 dev_appserver.py:589] Matched "/mapreduce/command/list_jobs" to CGI dispatcher with path $PYTHON_LIB/google/appengine/ext/mapreduce/main.py DEBUG 2011-09-28 18:30:55,003 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': 'text/plain, */*', 'HTTP_CONNECTION': 'keep-alive', 'USER_IS_ADMIN': '1', 'HTTP_COOKIE': 'dev_appser ver_login="test@example.com:True:185804764220139124118"', 'CURRENT_VERSION_ID': '1.1', 'SERVER_SOFTWARE': 'Developme nt/1.0', 'SCRIPT_NAME': '', 'USER_ORGANIZATION': '', 'USER_ID': '185804764220139124118', 'REQUEST_METHOD': 'GET', 'H TTP_HOST': '10.1.2.20:8000', 'PATH_INFO': '/mapreduce/command/list_jobs', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_STRI NG': '', 'TZ': 'UTC', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'USER_EMAIL': 'test@example.com', 'CONTENT_LENGTH': '', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64 ) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich', ' HTTP_REFERER': 'http://10.1.2.20:8000/mapreduce/status', 'SERVER_NAME': '10.1.2.20', 'REMOTE_ADDR': '10.1.2.5', 'CON TENT_TYPE': 'application/x-www-form-urlencoded', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q =0.8', 'SDK_VERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/dev/gae/google/appengine/ext/mapreduce/main.py', 'SERVE R_PORT': '8000', 'AUTH_DOMAIN': 'gmail.com'} DEBUG 2011-09-28 18:30:55,003 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" INFO 2011-09-28 18:30:55,012 dev_appserver.py:4248] "GET /mapreduce/command/list_jobs HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:55,013 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:55,019 dev_appserver.py:589] Matched "/favicon.ico" to CGI dispatcher with path main.py DEBUG 2011-09-28 18:30:55,022 dev_appserver.py:3022] Executing CGI with env: {'HTTP_ACCEPT': '*/*', 'HTTP_CONNECTION': 'keep-alive', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'HTTP_C OOKIE': 'dev_appserver_login="test@example.com:True:185804764220139124118"', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf- 8;q=0.7,*;q=0.3', 'CURRENT_VERSION_ID': '1.1', 'SERVER_SOFTWARE': 'Development/1.0', 'SCRIPT_NAME': '', 'USER_ORGANI ZATION': '', 'REQUEST_METHOD': 'GET', 'HTTP_HOST': '10.1.2.20:8000', 'PATH_INFO': '/favicon.ico', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_STRING': '', 'TZ': 'UTC', 'USER_EMAIL': 'test@example.com', 'USER_IS_ADMIN': '1', 'CONTENT_LENGT H': '', 'USER_ID': '185804764220139124118', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535. 2 (KHTML, like Gecko) Chrome/15.0.874.24 Safari/535.2', 'APPLICATION_ID': 'dev~domain-sandwich', 'SERVER_NAME': '10. 1.2.20', 'REMOTE_ADDR': '10.1.2.5', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'SDK_V ERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/dev/domain-sandwich/src/main.py', 'SERVER_PORT': '8000', 'AUTH_DOMAI N': 'gmail.com'} DEBUG 2011-09-28 18:30:55,022 dev_appserver.py:2721] Reusing main() function of module "main" INFO 2011-09-28 18:30:55,028 dev_appserver.py:4248] "GET /favicon.ico HTTP/1.1" 404 - DEBUG 2011-09-28 18:30:55,029 dev_appserver_index.py:172] No need to update index.yaml DEBUG 2011-09-28 18:30:56,662 dev_appserver.py:589] Matched "/mapreduce/command/start_job" to CGI dispatcher with path $PYTHON_LIB/google/appengine/ext/mapreduce/main.py DEBUG 2011-09-28 18:30:56,670 dev_appserver.py:3022] Executing CGI with env: {'HTTP_COOKIE': 'dev_appserver_login="test@example.com:True:185804764220139124118"', 'SERVER_SOFTWARE': 'Development /1.0', 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'POST', 'PATH_INFO': '/mapreduce/command/start_job', 'HTTP_ORIGIN': 'htt p://10.1.2.20:8000', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_STRING': '', 'CONTENT_LENGTH': '232', 'HTTP_ACCEPT_CHARSE T': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHT ML, like Gecko) Chrome/15.0.874.24 Safari/535.2', 'TZ': 'UTC', 'HTTP_REFERER': 'http://10.1.2.20:8000/mapreduce/stat us', 'SERVER_NAME': '10.1.2.20', 'REMOTE_ADDR': '10.1.2.5', 'SDK_VERSION': '1.5.2', 'PATH_TRANSLATED': '/home/ost/de v/gae/google/appengine/ext/mapreduce/main.py', 'SERVER_PORT': '8000', 'USER_IS_ADMIN': '1', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'CURRENT_VERSION_ID': '1.1', 'USER_ORGANIZATION': '', 'USER_ID': '185804764220139124118', 'HTTP_H OST': '10.1.2.20:8000', 'HTTP_CONNECTION': 'keep-alive', 'USER_EMAIL': 'test@example.com', 'HTTP_ACCEPT': 'text/plai n, */*', 'APPLICATION_ID': 'dev~domain-sandwich', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en; q=0.8', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'AUTH_DOMAIN': 'gmail.com'} DEBUG 2011-09-28 18:30:56,671 dev_appserver.py:2721] Reusing main() function of module "google.appengine.ext.mapr educe.main" DEBUG 2011-09-28 18:30:56,688 dev_appserver.py:2198] Could not import "_io": Disallowed C-extension or built-in m odule DEBUG 2011-09-28 18:30:56,689 util.py:105] Could not import BlobstoreLineInputReader from google.appengine.ext.ma preduce.input_readers. Will try recursively. Traceback (most recent call last): File "/home/ost/dev/gae/google/appengine/ext/mapreduce/util.py", line 90, in for_name result = __import__(module_name, None, None, [short_name]) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2503, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2375, in FindAndLoadModule description) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description) File "/home/ost/dev/gae/google/appengine/ext/mapreduce/input_readers.py", line 59, in <module> import zipfile File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2503, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2375, in FindAndLoadModule description) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description) File "/usr/lib/python2.7/zipfile.py", line 6, in <module> import io File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2503, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2375, in FindAndLoadModule description) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description) File "/usr/lib/python2.7/io.py", line 60, in <module> import _io ImportError: No module named _io DEBUG 2011-09-28 18:30:56,698 dev_appserver.py:2198] Could not import "_io": Disallowed C-extension or built-in m odule DEBUG 2011-09-28 18:30:56,698 util.py:105] Could not import input_readers from google.appengine.ext.mapreduce. Wi ll try recursively. Traceback (most recent call last): File "/home/ost/dev/gae/google/appengine/ext/mapreduce/util.py", line 90, in for_name result = __import__(module_name, None, None, [short_name]) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2503, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2375, in FindAndLoadModule description) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description) File "/home/ost/dev/gae/google/appengine/ext/mapreduce/input_readers.py", line 59, in <module> import zipfile File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2503, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2375, in FindAndLoadModule description) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description) File "/usr/lib/python2.7/zipfile.py", line 6, in <module> import io File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2503, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2375, in FindAndLoadModule description) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 1538, in Decorate return func(self, *args, **kwargs) File "/home/ost/dev/gae/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description) File "/usr/lib/python2.7/io.py", line 60, in <module> import _io ImportError: No module named _io ERROR 2011-09-28 18:30:56,702 base_handler.py:140] Error in JsonHandler, returning exception. Traceback (most recent call last): File "/home/ost/dev/gae/google/appengine/ext/mapreduce/base_handler.py", line 133, in _handle_wrapper self.handle() File "/home/ost/dev/gae/google/appengine/ext/mapreduce/handlers.py", line 762, in handle _app=mapper_params.get("_app")) File "/home/ost/dev/gae/google/appengine/ext/mapreduce/handlers.py", line 826, in _start_map mapper_input_reader_class = mapper_spec.input_reader_class() File "/home/ost/dev/gae/google/appengine/ext/mapreduce/model.py", line 408, in input_reader_class return util.for_name(self.input_reader_spec) File "/home/ost/dev/gae/google/appengine/ext/mapreduce/util.py", line 109, in for_name module = for_name(module_name, recursive=True) File "/home/ost/dev/gae/google/appengine/ext/mapreduce/util.py", line 117, in for_name short_name, module_name)) ImportError: Could not find 'input_readers' on path 'google.appengine.ext.mapreduce' (????) INFO 2011-09-28 18:30:56,710 dev_appserver.py:4248] "POST /mapreduce/command/start_job HTTP/1.1" 200 - DEBUG 2011-09-28 18:30:56,711 dev_appserver_index.py:172] No need to update index.yaml A: This may be the same problem I was having -- I was using the 2.7 version of the Python Interpreter in my local environment. When I switched to 2.5, it works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use Parallel Thread to sum up 1 billion consecutive numbers, return one single number? Faced this question in my interview. What I answerred is that: * *divide 1b numbers into 10 group *Use threadpool to create one thread for each group, 10 totally *each thread sum up the result for the group passed and retrun the value *use Barrier to sum up all results after 10 threads end, return the final value My doubt is what's the expected answer for this question ? And if it's running in single-cpu (no multi-thread mode), should single thread be faster than multi-thread ? Thanks a lot. A: A trick question, perhaps - to see if you can think outside the box you're given? If they're consecutive, as noted in the title, and they begin with n, then: final long BILLION = 1000000000; long answer = (BILLION * n) + ( BILLION*BILLION + BILLION ) / 2; This works for n up to somewhere around a billion - after that it will overflow. Needless to say, I don't see how multithreading would be of any benefit at all! A: I am extremely unimpressed with your answer. (Perhaps I am misunderstanding the question.) Would not a more approriate answer be: given parameters i and j where I want the sum of i, i+1, i+2, ..., j-2, j-1, j be * *in thread 1 calculate i*(i+1)/2 and *in thread 2 calculate j*(j+1)/2 *join the threads and calculate the sum Be sure to use BigInteger for the arithmetic. I would guess if i and j are extremely large numbers multithreading would be faster than single threading. But i don't see the advantage of more than 2 threads A: http://businessmajors.about.com/od/gmatpracticequestions/a/GMATtest1.htm I think faced with this question, I would have answered with "I would research the problem first, since I'm guessing there is a formulaic solution that would give me the answer faster than a brute force approach. Mathematicians have come up with formulas to solve all sorts of clever little questions. No shame in finding an expert to solve a problem quickly and efficiently." Of course, in an interview, who has time to frame an answer like that? UPDATE: Oops, I read your question again, and I see the interviewer was compelling you to use threads and such. Still, I might have pointed out that many brute force problems are solved far more elegantly with a bit o' math. Tell him to use the parallel thread to run a browser, call up Google, do a search, and solve the problem in about 20 seconds. A: In each thread, use a BigInteger to keep running totals. Have a centralized BigInteger that is properly protected (by Barrier or Synchronized). When a thread is done with its run, it gets a lock on the centralized BigInteger, adds in the threads sum, then releases lock. ..At least that's how I'd have done it. But Andrey is right, the 'answer' is only half of what they are looking for :) A: You should have said that you would add the numbers in each thread as BigDecimal objects. Once each thread is completed, add the numbers to an ArrayBlockingQueue. When there are 10 objects in the queue, dump the queue and iterate through each BigDecimal, adding each number. Multi-thread should be faster if you have multiple cores. If you have one core, it'll be slower. A: What do you mean by consecutive? If there is a regular gap between them and then you can use the average of the first and last values total = n*(last+first)/2. If the gap is not regular, then one method to group numbers by index and add them together that way. If they are big numbers, then you can split them up by every i digits and add together only that i digit in a single thread. Instead of keeping the whole thing in memory I would rather add together smaller chunks and save the partial result, so the process could be paused and continued. Having 10 cores does not necessary mean that using 10 threads is the optimal solution. The OS might use a core, your program that creates the groups might use one too (but I guess it is paused until the threads are working) and by hyperthreading you can use double the threads than cores.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use C code (libqrencode) in an iOS project I started coding about a year ago on iOS and have got to grips with writing Objective C and have managed to produce a few apps. I'm attending my first hack day next week and have come up with a quasi-treasure hunt idea that involves QR codes. I've managed to find ObjC classes to handle decoding a QR code but nothing to encode/generate them in the first place. I found links to a few objective C frameworks on git hub but all appeared to have outstanding issues. Then I found this thread on here: Is there any QR Encoding Library in Cocoa? That pointed me in the direction of libqrencode a C 'library' that I should be able to get to work in iOS being a superset of C. Unfortunately have no formal computer science background I haven't got a clue where to start on getting available in my project. Can anyone explain the basic steps of what I need to do so I can at least Google intelligently. So far I've read about setting search paths and creating static libraries but no idea if this is even the right route to follow. Any help appreciated - try and keep it simple my knowledge ends at writing basic VC's. A: Here's a blogpost from a guy who created a working XCode project with the library included and sample code. The sample code is the same that @conradev posted as one of the answers. I tested this in Xcode 4.3 and works beautifully. I tried including the original lib in one of my projects and failed miserably but then I included the ones in this project and it all worked without any tweaking so I'm positive he didn't change any settings in the Xcode project. Just create a new project, drag the qrencode lib files from this project into it, paste @conradev's code and it all works as expected. A: I would recommend the Objective C QR Encoder, which is an Apache Licensed QR encoder written in objective C. A: Have a look at this libqrencode xcode project. It only gives you a compiled lib though, no example of usage. A: Here's what you have to do generally for any C static library: * *include the library in an XCode project, go to the project then select the "build phases" tab, and in there open the "link binary with libraries" section - add your compile static libqrencode library there. *Go to the "Build Settings" tab of the project and search for "header", then add the path to the place the library keeps header files in "header search paths". Now you can include the header files in Objective-C files and call directly into the library. A general Google search starting point would be "add C library to XCode iPhone project". It's not really a CS skill, CS is more esoteric than search paths... A: libqrencode is licensed under the LGPL. For your code remain proprietary, it has to link to libqrencode in a manner that allows the user to replace the library with a modified version (1). This is impossible to do in the App Store. Your code would have to be licensed under the GPL to use libqrencode, and code licensed under the GPL is not allowed in the App Store (2). Therefore, you cannot use libqrencode in an App Store application. That said, here is some code that can be used in an iOS project to interface with libqrencode: #import <libqrencode/qrencode.h> void freeRawData(void *info, const void *data, size_t size) { free((unsigned char *)data); } - (UIImage *)quickResponseImageForString:(NSString *)dataString withDimension:(int)imageWidth { QRcode *resultCode = QRcode_encodeString([dataString UTF8String], 0, QR_ECLEVEL_L, QR_MODE_8, 1); unsigned char *pixels = (*resultCode).data; int width = (*resultCode).width; int len = width * width; if (imageWidth < width) imageWidth = width; // Set bit-fiddling variables int bytesPerPixel = 4; int bitsPerPixel = 8 * bytesPerPixel; int bytesPerLine = bytesPerPixel * imageWidth; int rawDataSize = bytesPerLine * imageWidth; int pixelPerDot = imageWidth / width; int offset = (int)((imageWidth - pixelPerDot * width) / 2); // Allocate raw image buffer unsigned char *rawData = (unsigned char*)malloc(rawDataSize); memset(rawData, 0xFF, rawDataSize); // Fill raw image buffer with image data from QR code matrix int i; for (i = 0; i < len; i++) { char intensity = (pixels[i] & 1) ? 0 : 0xFF; int y = i / width; int x = i - (y * width); int startX = pixelPerDot * x * bytesPerPixel + (bytesPerPixel * offset); int startY = pixelPerDot * y + offset; int endX = startX + pixelPerDot * bytesPerPixel; int endY = startY + pixelPerDot; int my; for (my = startY; my < endY; my++) { int mx; for (mx = startX; mx < endX; mx += bytesPerPixel) { rawData[bytesPerLine * my + mx ] = intensity; //red rawData[bytesPerLine * my + mx + 1] = intensity; //green rawData[bytesPerLine * my + mx + 2] = intensity; //blue rawData[bytesPerLine * my + mx + 3] = 255; //alpha } } } CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, rawData, rawDataSize, (CGDataProviderReleaseDataCallback)&freeRawData); CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; CGImageRef imageRef = CGImageCreate(imageWidth, imageWidth, 8, bitsPerPixel, bytesPerLine, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); UIImage *quickResponseImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); CGColorSpaceRelease(colorSpaceRef); CGDataProviderRelease(provider); QRcode_free(resultCode); return quickResponseImage; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting a users IP when cURL'd? On some of my sites I have cURL pulling a script from another one of my domains - that script needs to get access to the IP of the person visiting the site, but I'm stumped at how to do that. Because I'm using cURL, the REMOTE_ADDR variable is the server's IP address. How can I collect the user's IP address? A: You could simply grab it before you send your CURL request and alter the URL to fetch by appending a URL encoded version of the user's IP (or you could do a POST request rather than GET and just have it as a posted field).
{ "language": "en", "url": "https://stackoverflow.com/questions/7587684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash RegExp Problem I am use RegExp. This code give sş. I want to make ss. How can I do this. Thanks for answers. import RegExp.as; var pattern:Array = new Array(); pattern[0] = new RegExp("ş","s"); var patternReplace:Array = ["s"]; function decomposeUnicode(str:String):String { str = "şş" for (var i = 0; i < pattern.length; i++) { str = str.replace(pattern[i], patternReplace[i]); } return str; } trace(decomposeUnicode()); A: All you have to do is define the global flag "g" when creating you're RegExp. I don't know if you really want to define dotall (indicates if . matches new line characters) but that's what you're doing by setting "s" in the second parameter. I'll let it there for the example. pattern[0] = new RegExp("ş","s","g"); A: Here's a shorthand version: str = str.replace(/ş/g, "s");
{ "language": "en", "url": "https://stackoverflow.com/questions/7587688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Newbie: Checking to see if radio button is checked on form initialization. What does this code mean? I am a javascript novice. I'm trying to build a complex form whilst simultaneously learning JS and JQ... not an easy task. This code works, but I don't know what two lines do, so I thought I'd ask here. What this code does is loop through an array to see if a radio button checkbox has been checked as yes or no. It runs at initialization when a user revisits the form he/she is filling out. The code is attached to a textfield element which unhides if myRadioButton is yes, stays hidden if no. I do not know what lines 5 and 6 do (beginning with the second if statement). Would some knowledgable person please be so kind as to transcribe those lines into a couple of sentences, kind of like they do in tutorials? I would really appreciate it! var rbVal = ""; var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); for (var i = 0; i < rbBtn.length; i++) if (rbBtn[i].checked) { if (rbVal != "") rbVal += ","; rbVal += rbBtn[i].value; } if( rbVal != "yes" ){ doSomething; } else { doSomethingElse; } A: That code is checking all radio buttons with a shared name myRadioButton[], to make sure that if one is checked its value is added to rbVal string seperated by a comma. var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); <- gets an array of radio buttons for (var i = 0; i < rbBtn.length; i++) <- loops through every button in that array. if (rbBtn[i].checked) { <- if the button is selected it then checks to see if rbVAl is already set. <-- Either you are missing something here or it is faulty program A: Line 5 compares the value of rbVal to an empty string (""). If rbVal is not equal (!=) to an empty string, a string containing a comma character is appended to rbVal. So for example, if rbVal contains the string "hello", after the execution of that line, it will contain "hello,". Line 6 then appends the value of rbBtn[i].value to rbVal. rbBtn is an array-like object (in fact, it appears to be an instance of jQuery containing whatever was matched by the selector), and when you access a jQuery object with array syntax like that, you get the actual DOM element rather than another jQuery object, so the value property is the actual value property of the DOM element (by the look of it, that will be a radio button). So, if you have a radio button like this: <input type="radio" value="someVal"> then your loop would result in rbVal == "someVal". If you have two radio buttons: <input type="radio" value="someVal"> <input type="radio" value="anotherVal"> then you would end up with rbVal == "someVal,anotherVal". You can see from that what the overall purpose of that loop is - to build up a comma-separated string of the values of all the radio buttons matched by the jQuery selector. A: Curiously, this is using jQuery to grab radio buttons and some vanilla JavaScript to see if the returned radio buttons are checked or not. * *var rbVal = ""; initalises a new variable with an empty string "". *var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); fetches all elements from the document that are called myRadioButton[]. *for (var i = 0; i < rbBtn.length; i++) loops through each of the returned elements (there might be more than one as myRadioButton[] is an array of radio buttons hence the [] at the end). i is the current index in the array of returned elements. *if (rbBtn[i].checked) sees whether the radio button is "checked" ("on", if you like). *rbVal += rbBtn[i].value;: If the current radio button is checked (remember, for() loops through them all), fetch it's value attribute and append it (add it onto) whatever is currently in rbVal. For example, if rbVal contains Hello and the radio button's value is world then rbVal would end up containing Hello world. *if( rbVal != "yes" ) If the value in rbVal doesn't equal (!=) yes, then we call the doSomething function. *If rbVal does contain yes, then we want to call the doSomethingElse function: else { doSomethingElse; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: find what variables changed per value of another variable Given the following data.frame: t x y --------- 1 1 3 1 1 3 1 1 2 2 1 2 2 2 2 I would like output of the form t cnt cux cuy --------------- 1 3 1 2 2 2 2 1 where cnt is the count of all rows with a particular value t, cux/cuy is the count of all unique rows of x/y The other constraint is that the answer must work for a variable number of columns. Thanks. A: What you describe in words and what you show in expected output do not agree. In particular, counting unique values of y would be 2 and 1, not 3 and 2 based on your input. Going with the written description: DF <- data.frame(t=c(1,1,1,2,2), x=c(1,1,1,1,2), y=c(3,3,2,2,2)) library("plyr") ddply(DF, .(t), function(DF) { data.frame(cnt=length(DF$t), colwise(function(x) {length(unique(x))})(DF)) }) Or if you want something really functional looking: library("functional") ddply(DF, .(t), function(DF) { data.frame(cnt=length(DF$t), colwise(Compose(unique, length))(DF)) }) Or going completely overboard with the functional paradigm: merge(ddply(DF, .(t), summarise, cnt=length(t)), ddply(DF, .(t), colwise(Compose(unique, length)))) None of these give the column names you asked for; instead of cux it is x. However, they can be changed afterward. res <- merge(ddply(DF, .(t), summarise, cnt=length(t)), ddply(DF, .(t), colwise(Compose(unique, length)))) names(res)[-(1:2)] <- paste("cu", names(DF)[-1], sep="") which gives > res t cnt cux cuy 1 1 3 1 2 2 2 2 2 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7587691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best portable DB engine that supports Linq I need to know what is the best portable db, for this situation I've an application base on sql server db, we use both LINQ TO SQL, and ADO.NET, in this application. Now we need to make a portable version of it, but the fact we are using Linq To Sql, preventing us from using MS Access, as there is not out of the box solution for that (other than some 3rd parties, and we don't want to use them). So I need to a db engine that is: * *Portable *Have Linq support. if it is not completely portable, is there is a one that can be easily attached & deattached, from client PC. A: Did you check out SQL Compact Edition? Downloadable for free and a list of reasons why to use it It seems the latest and greatest version (4) does not support LINQ-to-SQL, but the previous version (3.5) does. A: Check this code project article: LinqToSQL: Comprehensive Support for SQLite, Microsoft Access, SQServer2000/2005 Hope this helped.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the := operator called in VB.NET? In VB.NET, you can invoke methods (or add attributes) with optional parameters like so: DoSomething(FirstName:="Bob", LastName:="Smith") ... <MyAttribute(SomeParam:=400)> Public MyClass ... I was trying to find out the name of the := operator, so I looked within MSDN's VB.NET 2010's Operators section and couldn't find it listed. Maybe it's not actually an operator, but instead something else? I keep calling it the "colon equals operator" or the "parameter assignment notation" when talking to co-workers, but it would be nice to know what it is technically called. For example, I would call the << operator the "left bit-shift operator" and the <= operator the "greater-than-or-equal comparison operator." So then, what should := be called? A: It's not an operator - it's just the syntax for named arguments. A: Those are Named Arguments. http://msdn.microsoft.com/en-us/library/dd264739.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7587695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WordPress plugin is not work properly A WordPress plugin that has always worked OK in the past suddenly isn’t working, why do this type of error in wordpress? A: You've probably upgraded your Wordpress version and the plugin is no longer compatible. Another possibility is that you've installed a conflicting plugin or changed some settings. You could also have used the plugin incorrectly inadvertently. It would help if you explained what plugin you're using, what error you're getting, and what you're trying to do with it. A: If a wordpress plugin stops working it could be for a number of reasons: * *It was relying on a web service which no longer exists/returns and is not handling this case gracefully *Someone has upgraded to the latest version which no longer plays nice with the version of WP you're running or the version of PHP you have installed. *Another plugin that you have installed is now conflicting with the plugin. Have you enabled wp-debug in the wp-config file? A: Make sure that you’ve downloaded the latest version of the plugin. New releases of plugins add features, but they also often fix bugs, including the one you might be having. To check for new versions of your plugins, just click Administration and Plugin. WordPress should list all of your plugins, along with notifications of any that have upgrades available. Click Upgrade Automatically, and you’ll have the latest version. (In fact, checking for the latest versions of all of your plugins is something you probably should do on a regular basis, perhaps two to four times per year.) If that doesn’t work, you have a few other options. You can try reinstalling the plugin from scratch; perhaps the plugin software became corrupted. Try to remember if you made any other software changes or installed other plugins between the time the problematic plugin was working correctly and the time that it failed. You could have an incompatibility issue between the malfunctioning plugin and the software changes you made. See if the author of the plugin has a blog where you can report your problem. It’s possible others are having the same issue, and the plugin author will create a fix or knows a workaround. Occasionally, if you upgrade your version of WordPress, you could end up with multiple plugins that stop working correctly. You’ll just have to deactivate the malfunctioning plugins until the author comes up with a new release that will be compatible with the new version of WordPress. if you want more details click here. Link A: if you plugin stop working first question you have to ask yourself is: 1.- Did I install another plugin so it's having conflict with jquery (for example) 2.- Did I recently upgraded WordPress. (perhaps that plugin doesn't work with the new version) and then you could have more answers depending on which plugin is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to render (fast) text on path? How to render (to image) text on path with any renderer working on linux? Like this: text on path. Performance is important. A: Short answer: I'm on a Debian Squeeze system with the python-cairo package installed. If I run the warped text example it provides (85 lines of Python): python /usr/share/doc/python-cairo/examples/warpedtext.py it produces a warpedtext.png file like this: I imagine it'd be fairly easy to modify/adapt/port the example. Long answer: There are two things you need to do this. * *The ability to generate the transforms which will place individual letters with the correct position and orientation along the path. This is basic 2D transform geometry. *The ability to render transformed characters/font glyphs with a decent level of quality (sub-pixel precision, antialiasing etc). For the latter, I'd be looking at one of * *Qt's QPainterPath (this example seems to be exactly what you want, but see also this one). *Cairo (another example). *Anti-Grain Geometry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# COM Interop and Application.DoEvents() I found the following code and am trying to implement it in a COM module: public Bitmap GetThumbnail() { ThreadStart _threadstart = new ThreadStart(GenerateThumbnail); Thread _thread = new Thread(_threadstart); _thread.SetApartmentState(ApartmentState.STA); _thread.Start(); _thread.Join(); return _image; } private void GenerateThumbnail() { WebBrowser _browser = new WebBrowser(); _browser.ScrollBarsEnabled = false; _browser.ScriptErrorsSuppressed = true; _browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(_browser_DocumentCompleted); _browser.Navigate(_url); while (_browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } _browser.Dispose(); } void _browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser _browser = (WebBrowser)sender; _browser.ClientSize = new Size(this._pagewidth, this._pageheight); _browser.ScrollBarsEnabled = false; _image = new Bitmap(_browser.Bounds.Width, _browser.Bounds.Height); _browser.BringToFront(); _browser.DrawToBitmap(_image, _browser.Bounds); if (_imageheight != 0 && _imagewidth != 0) _image = (Bitmap)_image.GetThumbnailImage(_imagewidth, _imageheight, null, IntPtr.Zero); } However, I've discovered that the Application.DoEvents() and COM do not work together. The code works great in a C# application, but it hangs when called via COM. As you can tell, I'm trying to get a website thumbnail, and I can't seem to figure out a substitute for the DoEvents(). Any suggestions? Thanks, Kevin
{ "language": "en", "url": "https://stackoverflow.com/questions/7587704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Split a string on capitals and digits I'm currentl using thing.replace(/([a-z])([A-Z])/g, "$1 $2"); to split a string on capitals like so. HereAreSomeWords ====== Here Are Some Words SomeMoreStuff ====== Some More Stuff I'd like to update the regex so that it will split on groups of numbers as well. So the desired output would be: 123SomeWords ======== 123 Some Words Some1Words ======= Some 1 Words Some1234Words ======= Some 1234 Words Does anyone have any thoughts on how to do this? A: Try the pattern: /([a-z\d](?=[A-Z])|[a-zA-Z](?=\d))/g and replace it with this: "$1 " Here's a demo: var tests = new Array( "HereAreSomeWords", "SomeMoreStuff", "123SomeWords", "Some1Words", "Some1234Words" ); for (var i in tests) { print(tests[i] + " -> " + tests[i].replace(/([a-z\d](?=[A-Z])|[a-zA-Z](?=\d))/g, "$1 ")); } which prints: HereAreSomeWords -> Here Are Some Words SomeMoreStuff -> Some More Stuff 123SomeWords -> 123 Some Words Some1Words -> Some 1 Words Some1234Words -> Some 1234 Words as you can see on Ideone: http://ideone.com/KE64z edit Perhaps a more intuitive way would be to globally match the parts you're interested in (either numbers: \d+, or capitalized words: [A-Z][a-z]*) and join(' ') these together: for (var i in tests) { print(tests[i].match(/\d+|[A-Z][a-z]*/g).join(' ')); } which would result in the same output. Note that my examples only take ascii letters in account: words like café would not work because of the é!
{ "language": "en", "url": "https://stackoverflow.com/questions/7587711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any out of the box code to serialize a model to Key Value Pairs using ModelMetaData? I know that ModelMetadata is used to bind values from a model to fields. Is there any out of the box MVC code that will take a model and use it's ModelMetadata to generate KeyValuePairs for the values of all of it's properties? A: You could use the .ToDictionary() extension method from System.Linq? Dictionary<string, object> dictionary = ViewData.ModelMetadata.Properties.ToDictionary(key => key.PropertyName, value => value.Model);
{ "language": "en", "url": "https://stackoverflow.com/questions/7587713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Image does not have width at document.ready I have a function that I wish to use to resize images: http://jsfiddle.net/eUurB/ When I run it on document.ready, it has no effect; the image size returned is '0' (You may notice that it does work in the fiddle... I'm not sure what's causing this inconsistencty to be honest, but on my test site it's most definitely returning height and width of '0'. Is this expected behaviour? If so, how could I make a simple listener for when images have width? A: Here's an ultra-safe way to do it that doesn't require waiting for all the images to load, and takes care of situations where the image may be cached or finished loading before the DOM is ready. $('#my_img').one('load',function(){ resizeImgByArea('logo', 50); }) .filter(function(){ return this.complete; }) .load(); * *.one('load',...) removes the handler as soon as it is invoked. You only need it once. *.filter() will return the image if it was already loaded. If not, it returns no elements. *.load() will manually invoke the handler. This will only occur if the image was already loaded. So if the image was preloaded before the DOM was ready, we'll invoke its .load() handler manually. If not, its handler will be invoked when it is loaded. A: Images are not loaded at document.ready time. Instead use the .load() method of jQuery. $('#logo').load( function() { resizeImgByArea('logo', 500); }); A: From the jQuery docs on the jQuery(callback) method: This function behaves just like $(document).ready() And when we go to the docs on $(document).ready(), we find this: Description: Specify a function to execute when the DOM is fully loaded. So it's actually doing what it's supposed to. It isn't waiting for other resources (such as images) to load; it's executing your callback as soon as the DOM is ready. You could get that <img> element and attach a load event listener, but what if the image really did finish loading, before you could attach it? Your callback will never be executed. It's not pretty, but I think the safest thing you can do is just wait for the entire page to finish loading: $(window).load(function () { resizeImgByArea('logo', 50); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7587714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 2nd sound plays with less integrity? I want to press the button on the headset, play a sound via the speaker phone, then record a 10 second audio clip. Here is my code: SoundPool soundPool; HashMap<Integer, Integer> soundPoolMap; soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); soundPoolMap = new HashMap<Integer, Integer>(); soundPoolMap.put(SOUND_RECORD_ON, soundPool.load(context, R.raw.on, 1)); soundPoolMap.put(SOUND_RECORD_OFF, soundPool.load(context, R.raw.off, 1)); AudioManager mAudioManager = (AudioManager) context .getSystemService(Context.AUDIO_SERVICE); float streamVolumeMax = mAudioManager .getStreamMaxVolume(AudioManager.STREAM_MUSIC); if (recordStarted == false) { try { // start recording audioRecorder.start(); recordStarted = true; System.out.println(String.format("recording: %s", recordStarted)); mAudioManager.setMode(AudioManager.MODE_IN_CALL); mAudioManager.setSpeakerphoneOn(true); System.out.println("speaker on"); soundPool.play(soundPoolMap.get(SOUND_RECORD_ON), streamVolumeMax, streamVolumeMax, 1, 0, 1f); } catch (IOException e) { e.printStackTrace(); } } else { // stop recording try { audioRecorder.stop(); recordStarted = false; System.out.println(String.format("recording: %s", recordStarted)); mAudioManager.setMode(AudioManager.MODE_IN_CALL); mAudioManager.setSpeakerphoneOn(true); System.out.println("speaker on"); soundPool.play(soundPoolMap.get(SOUND_RECORD_ON), streamVolumeMax, streamVolumeMax, 2, 0, 1f); } catch (IOException e) { e.printStackTrace(); } The first sound plays on speaker fine, with very good integrity. However, when I press the button again to stop recording, the sound is nearly inaudible, despite using the same clip. Here is the logcat trace: ERROR/MediaButtonIntentReceiver(5290): <!> MediaButtonIntentReceiver 52<!> BUTTON PRESSED :D WARN/StagefrightRecorder(1466): Target duration (10000000 us) too short to be respected ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=2,mCurSndDevice=-1 ERROR/AudioHardwareMSM72XX(1466): [SKW]do_route_audio_rpc(2, 1, 0) ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=2,mCurSndDevice=2 ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=2,mCurSndDevice=2 ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=2,mCurSndDevice=-1 ERROR/AudioHardwareMSM72XX(1466): [SKW]do_route_audio_rpc(2, 1, 0) INFO/System.out(5290): recording: true ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): Routing audio to Speakerphone_conversation ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=7,mCurSndDevice=-1 ERROR/AudioHardwareMSM72XX(1466): [SKW]do_route_audio_rpc(7, 0, 0) ERROR/AudioService(1586): <!>android.media.AudioService 895<!> [BTUI] [SCO] ### setMode (2) ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): Routing audio to Speakerphone_conversation ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=7,mCurSndDevice=7 INFO/System.out(5290): speaker on WARN/AudioFlinger(1466): write blocked for 138 msecs, 71 delayed writes, thread 0xce08 ERROR/SUMAN-statusbarpolicy(1665): <!>com.android.systemui.statusbar.policy.StatusBarPolicy 1069<!> mServiceState.getRoaming()false DEBUG/StatusBarPolicy(1665): [BRIGHTHY] 0. mDataNetType: 8 DEBUG/StatusBarPolicy(1665): [BRIGHTHY] curNetwork=302880 curHPLMN=302220 WARN/KeyCharacterMap(5290): No keyboard for id 0 WARN/KeyCharacterMap(5290): Using default keymap: /system/usr/keychars/qwerty.kcm.bin ERROR/MediaButtonIntentReceiver(5290): <!> MediaButtonIntentReceiver 52<!> BUTTON PRESSED :D ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=2,mCurSndDevice=-1 ERROR/AudioHardwareMSM72XX(1466): [SKW]do_route_audio_rpc(2, 0, 0) ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): Routing audio to Speakerphone_conversation ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=7,mCurSndDevice=2 ERROR/AudioHardwareMSM72XX(1466): [SKW]do_route_audio_rpc(7, 0, 0) ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): Routing audio to Speakerphone_conversation ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=7,mCurSndDevice=-1 ERROR/AudioHardwareMSM72XX(1466): [SKW]do_route_audio_rpc(7, 0, 0) INFO/System.out(5290): recording: false ERROR/AudioHardwareMSM72XX(1466): [LGE] output devices :2 ERROR/AudioHardwareMSM72XX(1466): Routing audio to Speakerphone_conversation ERROR/AudioHardwareMSM72XX(1466): [doRouting]new_snd_device=7,mCurSndDevice=7 INFO/System.out(5290): speaker on Does anybody know why this is the case? I know that in the first portion I did not set the speaker phone back to false; if I do, the sound only gets played through the headset. I am suspecting it is the line that says "too short to be respected." Thank you very much! --------- UPDATE WITH MEDIAPLAYER CODE ------------- if (action == KeyEvent.ACTION_DOWN) { Log.e(TAG, "BUTTON PRESSED :D "); AudioManager mAudioManager = (AudioManager) context .getSystemService(Context.AUDIO_SERVICE); MediaPlayer playOn = MediaPlayer.create(context, R.raw.on); if (recordStarted == false) { try { // start recording audioRecorder.start(); recordStarted = true; System.out.println(String.format("recording: %s", recordStarted)); mAudioManager.setMode(AudioManager.MODE_IN_CALL); mAudioManager.setSpeakerphoneOn(true); System.out.println("speaker on"); playOn.start(); System.out.println("playing on tune"); } catch (IOException e) { e.printStackTrace(); } } else { // stop recording try { audioRecorder.stop(); recordStarted = false; System.out.println(String.format("recording: %s", recordStarted)); playOn.start(); System.out.println("playing off tune"); } catch (IOException e) { e.printStackTrace(); } finally { // mAudioManager.setSpeakerphoneOn(false); // System.out.println("speaker off"); // mAudioManager.setMode(AudioManager.MODE_NORMAL); } } // end else } // end key down action ok used this code to play the sound, but the 2nd sound is still very quiet (same problem as before)... more suggestions? :D A: Turns out, I wasn't supposed to play music in a BroadcastReceiver (detects the media button) because the music would only last for as long as onReceive is executed. Thus, a service had to be created to play before recording.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prefill a form with post data in ASP.NET I need to populate a form in the main page which on being submitted opens a lightbox which contains another form . I was planning to submit the form using Post as that seems to be the only way I can define which iframe to open in the lightbox .However my question is that how do I pre-populate the second form with the first forms data when I use the submission as POST I am using ASP.NET and C# I apologize for the naive question but I am still playing around with ASP.NET A: We dont have many details on items such as - is there a redirect? whats the second form? how are you handling controls.. etc Check this out to start. If you really need to send values across separate requests there are various ways to do this, but specify if this is what you are trying to do. http://msdn.microsoft.com/en-us/library/ms178139.aspx A: Use the Form collection in the Request object on the second form. The name in the collection is the same as the name in the name/value pair you're using in the post. TextBox1.Text = Request.Form["someName1"]; TextBox2.Text = Request.Form["someName2"]; Etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Content problem, any better solution? Currently i'm building an system that will let the user to create an small website inside their system. To access their website, user will type www.USERDOMAIN.mywebsite.com (just an example...) Well, USERDOMAIN will be their username on my database, and mywebsite will be the system domain. The user, (if he want's) can show his website on any domain, and i was thinking on how to link their domain with the information inside my database. I thought on two ideas: * *I can't give the main code to the final user, so I just thought I'd give him an HTML page with an iframe targeted to the original content, but it would be an bad idea because i would have too much trafic from many websites, and everything will be on my database causing it to be slow down. *Create some basic tables on the domain that my client has acquired, and some files to get the data and work with them, any change on the content would be made by the main system, them all chandged data would be sent to my client database I Think that the second solution would be better, but if you had an experience like it, something that you had think, it would be really great to share with me... if you had any idea, just let me know what of the two options above you chose. Thanks guys! A: I could be completely wrong here but if I understand right you want to do something like www.userdomain.com shows the content of www.userdomain.mywebsite.com Why not simply use CNAME records and create aliases that link the two? The user would need ot create the alias on their DNS settings but that would do it I'd think.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Android mutate() changes appearance of LayerDrawable I have a LayerDrawable defined in xml that I load from disk and reuse in a few parts of my application. To prevent an instance of my LayerDrawable from affecting other instances I call mutate like defined here. However calling mutate is also changing the appearance of the drawing. I can duplicate on tablets, phones, and the simulator. Anyone have experience with this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7587720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Links not taking to class for some reason my links aren't conforming to my class. What's going on? .greyBoxTxt { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; color:#7b7d7e; } a.greyBoxTxt { color:#0164a5; text-decoration:none; } <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="25%" valign="top" class="greyBoxTxt"> <b>Business Banking</b><br /> <a href="#">eBusiness Checking</a><br /> <a href="#">Business Checking</a><br /> <a href="#">Commercial Checking</a><br /> <a href="#">Non-Profit Checking</a><br /> <a href="#">Business Savings</a><br /> <a href="#">More... </a></td> <td width="25%" valign="top">&nbsp;</td> <td width="25%" valign="top">&nbsp;</td> <td width="25%" valign="top">&nbsp;</td> </tr> </table> A: I guess what you're trying to do is more this .greyBoxTxt { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; color:#7b7d7e; } .greyBoxTxt a { color:#0164a5; text-decoration:none; } <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="25%" valign="top" class="greyBoxTxt"> <b>Business Banking</b><br /> <a href="#">eBusiness Checking</a><br /> <a href="#">Business Checking</a><br /> <a href="#">Commercial Checking</a><br /> <a href="#">Non-Profit Checking</a><br /> <a href="#">Business Savings</a><br /> <a href="#">More... </a></td> <td width="25%" valign="top">&nbsp;</td> <td width="25%" valign="top">&nbsp;</td> <td width="25%" valign="top">&nbsp;</td> </tr> </table> The selector a.greyBoxTxt would select something like this, Commercial Checking A: Your selectors are wrong: a.greyBoxTxt targets anchor elements with the classname greyBoxTxt. Something like thie: <a class="greyBoxTxt" href="#">Lorem</a> What you want is an anchor element which is a descendant of an element with classname greyBoxTxt: .greyBoxTxt a { /* ... */ } Note that in this new selector, the space between the .greyBoxTxt and the a is actually the descendant combinator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android - Screen Event Can anyone tell me what event is fired when you come from Screen B to Screen A after pressing "BACK" button. Screen A = 1st screen Screen B = 2nd screen what event is fired when i come back to screen A from screen B. *By Screen i mean Activity A: No "events" are fired, just normal Activity lifecycle methods are called. A: If you actually want to know when you come back from another Activity you have to start Activity B using startActivityForResult(intent, REQUEST_CODE) And add this method to Activity A: protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_CODE) { } } In Activity B you can use setResult(RESULT_CODE) which you can then rad in onActivityResult using the resultCode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Like button counter is not changing I have had users click the like button on my website but the counter remains at one. I am using html5 version I have also tried the iframe version with same results My site is dvmark.com A: I was having the same problem, cleared my browser history and now it is showng the most updated number. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stopping renderer in springy.js library Is there anyone has used springy.js library? I would like to ask after I started a renderer by renderer.start();, how to stop it? Seems there is only start() function defined for the renderer object but there is no stop() function... A: There is a settimeout() function in the library, you just need to create a stop function, which is used to kill the settimeout() function with the given id.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble combining rows into one column using CAST( Ok SO, here's your time to shine! No really, I'm getting my butt kicked by an MS-SQL query that I can't seem to get to work. What I am trying to do is search on a patient name; but also return patients who have a similar first or last name to the querying patient's last name. So "John Smith" can return anyone named "John Smith" or anyone who has a first or last name like "smith". If the a patient has multiple disease states, then combine those disease states into a single column. I have the following tables (though of course there are many more columns, but these are the most imortant): Patient Table PatientID FirstName LastName UserIDFK 10000 John Smith 1 10001 Miss Smith 2 10002 Smith Bomb 3 10003 Bobby Smith 4 -- etc DiseaseStateForUser UserIDFK DiseaseStateRefId 1 1 1 2 2 2 3 1 3 2 4 1 GlobalLookUp RefId Ref_Code 1 HIV 2 HEPC The results I'm looking for are this: PatientID FirstName LastName DiseaseStates 10000 John Smith HIV|HEPC 10001 Miss Smith HEPC 10002 Smith Bomb HIV|HEPC 10003 Bobby Smith HIV I've taken the examples from these questions (and countless others): * *Is there a way to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field? *Simulating group_concat MySQL function in MS SQL Server 2005? As well as from this blog post Emulating MySQL’s GROUP_CONCAT() Function in SQL Server 2005 I came up with the following SQL procedure DECLARE @PatientID INT=null, @FirstName Varchar(15)= null, @LastName Varchar(15)= 'Smith', @Name Varchar(15) = 'John Smith', Select Patient.First_Name, Patient.Last_Name, patient.PatientID, (select CAST(GlobalLookUp.Ref_Code + '|' as VARCHAR(MAX)) from TBL_PATIENT patient ,TBL_GBLLOOKUP GlobalLookUp ,TBL_DiseaseStateForUser DiseaseStateForUser -- Try and make a collection of all the PatientIDs -- that match the search criteria -- so that only these are used to build -- the DiseaseStatesColumn ,(Select Patient.PatientID FROM TBL_PATIENT patient ,TBL_SITEMASTER SiteMaster ,TBL_USERMASTER UserMaster ,TBL_USERSINSITES UserInSites ,TBL_GBLLOOKUP GlobalLookUp ,TBL_DiseaseStateForUser DiseaseStateForUser WHERE (((patient.[Last_Name] like @LastName + '%') OR (patient.[Last_Name] Like @Name + '%' )) OR ((patient.[First_Name] Like @Name + '%' )) OR (patient.[First_Name] + ' ' + patient.[Last_Name] Like @Name + '%' )) AND UserMaster.User_Id = UserInSites.User_Id_FK AND UserInSites.Site_Id_FK = SiteMaster.Site_Id AND UserInSites.Is_Active = 'True' AND patient.[User_Id_FK] = UserMaster.[User_Id] AND (DiseaseStateForUser.User_Id_FK = patient.User_Id_FK AND DiseaseStateForUser.DiseaseState_RefId_FK = GlobalLookUp.Ref_Id) and DiseaseStateForUser.Is_Active='True' AND patient.[Is_Active] = 'TRUE' group by Patient.PatientID) as PATIENTIDs where patient.PatientID = PATIENTIDs.PatientID AND (DiseaseStateForUser.User_Id_FK = patient.User_Id_FK AND DiseaseStateForUser.DiseaseState_RefId_FK = GlobalLookUp.Ref_Id) For XML PATH('')) as MultiDiseaseState FROM TBL_PATIENT patient, TBL_SITEMASTER SiteMaster ,TBL_USERMASTER UserMaster,TBL_USERSINSITES UserInSites, TBL_GBLLOOKUP GlobalLookUp, TBL_DiseaseStateForUser DiseaseStateForUser WHERE (((patient.[Last_Name] like @LastName + '%') OR (patient.[Last_Name] Like @Name + '%' )) or ((patient.[First_Name] Like @Name + '%' )) OR (patient.[First_Name] + ' ' + patient.[Last_Name] Like @Name + '%' )) AND patient.PatientID = patient.PatientID AND UserMaster.User_Id = UserInSites.User_Id_FK AND UserInSites.Site_Id_FK = SiteMaster.Site_Id AND UserInSites.Is_Active = 'True' AND patient.[User_Id_FK] = UserMaster.[User_Id] AND DiseaseStateForUser.User_Id_FK = patient.User_Id_FK AND DiseaseStateForUser.DiseaseState_RefId_FK = GlobalLookUp.Ref_Id and DiseaseStateForUser.Is_Active='True' AND patient.[Is_Active] = 'TRUE' group by PatientID, patient.First_Name, patient.Last_Name, GlobalLookUp.Ref_Code order by PatientID Unfortunately, this query nets me the following: PatientID FirstName LastName MultiDiseaseState 10000 John Smith HIV|HEPC|HEPC|HIV|HEPC|HIV 10001 Miss Smith HIV|HEPC|HEPC|HIV|HEPC|HIV 10002 Smith Bomb HIV|HEPC|HEPC|HIV|HEPC|HIV 10003 Bobby Smith HIV|HEPC|HEPC|HIV|HEPC|HIV In other words, the select CAST(GlobalLookUp.Ref_Code + '|' as VARCHAR(MAX)) call is building up the MultiDiseaseState column with all of the disease states for ALL of the selected patients. I know there is something fundamentally wrong with the most inner SELECT statement, but I'm having a hard time figuring out what it is and how to write the query so that it builds only the disease states for a given patient. Kind of a long post, but are there any suggestions people can make given the code snippets I've provided? A: You should be able to use the Stuff function (I think it's only on SQL 2005 and higher) to make this work, I took your example data and wrote a demonstration off of that SET NOCOUNT ON CREATE TABLE #Patient ( PatientID INT, FirstName varchar(25), LastName varchar(25), UserIDFK INT ) INSERT INTO #PATIENT SELECT 10000,'John','Smith',1 INSERT INTO #PATIENT SELECT 10001,'Miss','Smith',2 INSERT INTO #PATIENT SELECT 10002,'Smith','Bomb',3 INSERT INTO #PATIENT SELECT 10003,'Bobby','Smith',4 CREATE TABLE #DiseaseStateForUser ( UserIDFK int, DiseaseStateRefId int ) INSERT INTO #DiseaseStateForUser SELECT 1,1 INSERT INTO #DiseaseStateForUser SELECT 1,2 INSERT INTO #DiseaseStateForUser SELECT 2,2 INSERT INTO #DiseaseStateForUser SELECT 3,1 INSERT INTO #DiseaseStateForUser SELECT 3,2 INSERT INTO #DiseaseStateForUser SELECT 4,1 CREATE TABLE #GlobalLookUp ( RefId int, Ref_Code varchar(10) ) INSERT INTO #GlobalLookUp SELECT 1,'HIV' INSERT INTO #GlobalLookUp SELECT 2,'HEPC' SELECT PatientID, UserIDFK, FirstName, LastName, STUFF( (SELECT '|' + l.Ref_Code FROM #DiseaseStateForUser u with (Nolock) JOIN dbo.#GlobalLookUp l with (nolock) ON u.DiseaseStateRefId = l.RefId WHERE u.UserIDFK = p.UserIDFK FOR XML PATH('') ) , 1, 1, '') FROM #PATIENT p with (Nolock) GROUP BY PatientID, FirstName, LastName, UserIDFK
{ "language": "en", "url": "https://stackoverflow.com/questions/7587733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Find the least element in an array, which has a pattern An array is given such that its element's value increases from 0th index through some (k-1) index. At k the value is minimum, and than it starts increasing again through the nth element. Find the minimum element. Essentially, its one sorted list appended to another; example: (1, 2, 3, 4, 0, 1, 2, 3). I have tried all sorts of algorithm like buliding min-heap, quick select or just plain traversing. But cant get it below O(n). But there is a pattern in this array, something that suggest binary search kind of thing should be possible, and complexity should be something like O(log n), but cant find anything. Thoughts ?? Thanks A: No The drop can be anywhere, there is no structure to this. Consider the extremes 1234567890 9012345678 1234056789 1357024689 It reduces to finding the minimum element. A: Do a breadth-wise binary search for a decreasing range, with a one-element overlap at the binary splits. In other words, if you had, say, 17 elements, compare elements 0,8 8,16 0,4 4,8 8,12 12,16 0,2 2,4 etc., looking for a case where the left element is greater than the right. Once you find such a range, recurse, doing the same binary search within that range. Repeat until you've found the decreasing adjacent pair. The average complexity is not less than O(log n), with a worst-case of O(n). Can anyone get a tighter average-complexity estimate? It seems roughly "halfway between" O(log n) and O(n), but I don't see how to evaluate it. It also depends on any additional constraints on the ranges of values and size of increment from one member to the next. If the increment between elements is always 1, there's an O(log n) solution. A: It can not be done in less then O(n). The worst case of this kind will always keep troubling us - An increasing list a1,a2,a3....ak,ak+1... an with just one deviation ak < ak-1 e.g. 1,2,3,4,5,6,4,7,8,9,10 And all other numbers hold absolutely zero information about value of 'k' or 'ak' A: The simplest solution is to just look forward through the list until the next value is less than the current one, or backward to find a value that is greater than the current one. That is O(n). Doing both concurrently would still be O(n) but the running time would probably be faster (depending on complicated processor/cache factors). I don't think you can get it much faster algorithmically than O(n) since a lot of the divide-and-conquer search algorithms rely on having a sorted data set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Filtering data based on data through multiple relationships So I have this in my DB: CommodityCategories ------------------- CommodityCategoryID (PK) Name Commodities ------------------- CommodityID (PK) CommodityCategoryID (FK) Name VendorsCommodities ------------------- VendorID (PK, FK) CommodityID (PK, FK) Vendors ------------------- VendorID Name Basically, a Commodity has a Commodity Category, and a Vendor has multiple Commodities. I'd like to display the name of each Commodity Category, and underneath display the name of each Vendor that has a Commodity related to that Commodity Category. Here's what I have: @foreach (var commodityCategory in Model.CommodityCategories) { <h3><a href="#">@commodityCategory.Name</a></h3> <div> @foreach (var vendor in Model.Vendors) { <span>@vendor.Name</span> } </div> } I need to filter Model.Vendors by the current Commodity Category that I'm looping through. I tried Model.Vendors.Where(v => v.Commodities.CommodityCategories.Contains(commodityCategory)), but CommodityCategories isn't a property of v.Commodities. Is there any way for me to do this? A: This could work: Model.Vendors.Where(v => v.Commodities.Any(c => c.CommodityCategory.Id == commodityCategory.Id)) A: I recreated your db schema and this is what worked for me ... @foreach (var catagory in Model) { <h3><a href="#">@catagory.Name</a></h3> if (catagory.Commodities.Any(commodity => commodity.Vendors.Count > 0)) { <div> @foreach (var vendor in catagory.Commodities.SelectMany(c => c.Vendors).Distinct()) { <span>@vendor.Name</span><br /> } </div> } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting isEqualToString: unrecognized selector sent to instance error I'm getting this error when clicking the same UIButton twice, it crashes the second time only when the request to the server is not able to go through. -[SendHelloFax isEqualToString:]: unrecognized selector sent to instance 0x12b49150 Update: I used breakpoints and found that the line it is crashing at is: if (!errorMessage || [errorMessage isEqualToString:@""]) { errorMessage = @"Failed to send fax. Please check your WiFi or 3G connection and try again."; } Methods: - (IBAction)sendFaxButtonClicked:(id)sender { NSString *errorMessage; int rcode = [MyDataSource sendFax:self.appointment phone_call_id:self.phone_call_id document_url:self.document_url targetId:self.contact_id targetName:self.name.text targetNumber:self.faxNumber.text coverSheetMessage:self.coverSheetMessage.text errorMessage:&errorMessage]; if (rcode) { if (!errorMessage || [errorMessage isEqualToString:@""]) { errorMessage = @"Failed to send fax. Please check your WiFi or 3G connection and try again."; } UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"Error" message:errorMessage delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil]; [someError show]; [someError release]; return; } if (!rcode) { [self dismissModalViewControllerAnimated:FALSE]; } } +(int)sendFax:(int)appointment_id phone_call_id:(int)phone_call_id document_url:(NSString*)document_url targetId:(int)contactId targetName:(NSString*)targetName targetNumber:(NSString*)targetNumber coverSheetMessage:(NSString*)coverSheetMessage errorMessage:(NSString**)errorMessage { NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/ichrono/20110715/60b88126/fax_send/", [self getMyHost]]]; ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease]; [self addCurrentUserLoginToPostRequest:request]; [request setPostValue:[NSString stringWithFormat:@"%d", contactId] forKey:@"fax_contact_id"]; [request setPostValue:[NSString stringWithFormat:@"%d", appointment_id] forKey:@"appointment_id"]; [request setPostValue:[NSString stringWithFormat:@"%d", phone_call_id] forKey:@"phone_call_id"]; [request setPostValue:document_url forKey:@"url_to_fax"]; [request setPostValue:targetNumber forKey:@"fax_number"]; [request setPostValue:targetName forKey:@"full_name"]; [request setPostValue:coverSheetMessage forKey:@"coversheet_message"]; [request startSynchronous]; NSError *error = [request error]; NSString *responseString; if (!error) { responseString = [request responseString]; } else { return -1; } NSMutableDictionary *temp = [responseString JSONValue]; *errorMessage = [temp valueForKey:@"errors"]; if ([[temp valueForKey:@"status"] isEqualToString:@"ok"]) { return 0; } else { return -1; } } A: Best bet is that errorMessage is not initialized and not set to a NSString even though rcode is not 0. Try: NSString *errorMessage - nil; and checking to insure errorMessage is set in this instance. A: When, at the beginning of your method, you define - without initialization -: NSString *errorMessage; you're in fact defining an id which has not been set to a valid value (that is a valid string using alloc-init or simply nil) so the memory area content pointed by errorMessage is not valid, that is it can be anything: an invalid area (which will lead to EXC_BAD_ACCESS) or another area previously taken by a now dealloc'd class (like in your case: this will raise an invalid selector exception) or in the worst case an area taken by another now dealloc'd NSString (difficult to debug!). Later you call sendFax:phone_call_id:... method which returns rcode and has as side effect to update the errorMessage pointer by let it point to a valid address (or nil). It doesn't and then when you check errorMessage you get one of the errors above. I suppose from your code that when rcode is set some error occurred. In such case this method must assign something to errorMessage, even a nil or an empty string, to avoid this error. So probably the sendFax: method is missing this detail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems comparing two arrays in Ruby In ruby, I am trying to compare a list of URLs with a previous list of URLs, and get only the new ones. I put the old list in a text file with one URL per line. I am reading the text file into an array like so: oldLines = File.open('logfile.txt', 'r').readlines I have an array of new values populated using the exact same method as the old list, and will probably have some overlap with the old list called 'newLines'. I am trying to get only values that don't match with the old list. Let's say 'newList'.length = 100 and 'oldlist'.length = 95, and I know through visual inspection that something like 90 elements overlap between them. Things I have tried: newList = newList - oldList #(newList | oldList) returns 195 #(newList & oldList) returns 0 newList.delete_if { |x| oldList.include?(x) } In both scenarios, nothing gets deleted from newList. I know I am missing something here. Thanks. A: I did the following: a.txt http://yahoo.com http://google.com http://bing.com b.txt http://bing.com http://yahoo.com test.rb a = File.open('a.txt', 'r').readlines.map!(&:chomp) b = File.open('b.txt', 'r').readlines.map!(&:chomp) p a-b #=> ["http://google.com"] Without the chomp it fails because in a.txt I have http://yahoo.com\n while on b.txt I simply have http://yahoo.com without the \n at the end. A: All you need to do is invoke the subtract method for arrays, which you did. ['1', '2', '3', '4', '5'] - ['2', '3', '4'] # => ["1", "5"] Not sure why this isn't working for you. Post some url sample data for your two arrays, problem probably lies there, and I'll update my answer accordingly. A: I couldn' figure out what's wrong with your code so I got it on irb. And still I don't have any answers. What is newList and oldList. How are these data structures populated? Are they array? irb(main):003:0> oldLines = File.open('/Users/pprakash/old', 'r').readlines => ["http://www.google.com\n", "http://yahoo.com\n", "http://slideshare.net\n"] irb(main):004:0> newLines = File.open('/Users/pprakash/new', 'r').readlines => ["http://www.google.com\n", "http://yahoo.com\n", "http://slideshare.net\n", "http://great.com\n", "http://example.com\n"] irb(main):005:0> x = newLines - oldLines => ["http://great.com\n", "http://example.com\n"] irb(main):006:0> newLines => ["http://www.google.com\n", "http://yahoo.com\n", "http://slideshare.net\n", "http://great.com\n", "http://example.com\n"] irb(main):007:0> oldLines => ["http://www.google.com\n", "http://yahoo.com\n", "http://slideshare.net\n"] irb(main):008:0> newLines = newLines - oldLines => ["http://great.com\n", "http://example.com\n"] irb(main):009:0> newLines => ["http://great.com\n", "http://example.com\n"] irb(main):010:0> A: I was not able to reproduce your problem. Here is what I did urls.txt http://www.google.com http://www.digg.com http://www.slashdot.com http://www.yahoo.com urls2.txt http://www.google.com http://www.digg.com http://www.slashdot.com http://www.yahoo.com http://www.dzone.com http://www.digit.com http://www.digitaldreams.com Code first = File.open('urls.txt', 'r').readlines second = File.open('urls2.txt', 'r').readlines disjoint = second - first Update: Upon attempting a few other things I flubbed my code by chomping the '\n' some of the URLs, and subtracted URLs with '\n' from URLs without '\n' and it didn't remove anything. So I imagine why you aren't seeing anything removed is some sort of error like that. Try printing out the two URLs before you subtract them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Incrementing a global static int in main Here's my code: File DataTypes.h static int count=0; File TreeOps.h #include"DataTypes.h" void printTree(Tree* ptr) File TreeOps.c #include"TreeOps.h" void printTree(pointer){ count++; // incrementing the count; printf("%d",counter); } File TreeMain.c #include"TreeOps.h" printTree(pointer); // all the necessary declarations are done. printf("%d",count); If in printTree function the printf gives count=1; while in main function it gives me 0. Why? A: static variable in this context means: every c file has its own variable instance. Remove static definition in h-file: extern int count; and add this to one of c files: int count = 0; extern means: this is forward declaration. By defining a variable as extern, you tell to compiler that count has int type, and this variable is created somewhere. Actually, this variable is created in one and only one c file. You can use it in any c file where DataTypes.h is included. In the file where this variable is created, compiler uses it. In all other file this variable becomes external reference, which is resolved later by linker. A: First off, defining data or functions in header files is a bad practice in C programming. In DataTypes.h you don't just declare the count variable, but you define it. What actually happens is that the count is defined separately in each translation unit and you end up with two variables after linking. The linker doesn't merge them because they are marked static, that means they should be local to the translation unit. If you want the count variable to be shared between the TreeOps.c and TreeMain.c translation units, you must use extern in the header file which only declares it: extern int count; And then define it globally as int count in either of TreeOps.c or TreeMain.c. A: You don't have a "global static int" in your program. Entities declared as static cannot possibly be "global". The whole point of declaring something static is to make it local to a specific translation unit. This is exactly what you've done: you have declared two completely independent static variables in two different translation units. Each variable is local to its own translation unit. Then you are modifying one of these variables and printing the other. No wonder that the other remains unchanged. In this case you have to decide what it is exactly you want. You can either have your variable as a global variable or as a static variable, but not both at the same time. "Global variable" and "static variable" are mutually exclusive concepts. So, what is it you want: global or static?
{ "language": "en", "url": "https://stackoverflow.com/questions/7587745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Text in TextView not shown in multiple lines - it gets truncated in a single line Below is an outline of my layout. I have my ScrollView inside another LinearLayout because I would be adding more views to it in runtime. Anyway, the problem is - the text in the TextView is always truncated to a single line, and is never shown in multiple lines. Is there any way to make it display a multilined TextViw without having to set an arbitrary number of lines using android:lines or android:maxLines? Thanks. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@drawable/background" android:id="@+id/XyzLayout" android:paddingRight="10dp"> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/background" android:fillViewport="true"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginBottom="0dip" android:layout_marginTop="1dip"> <TextView android:id="@+id/textView1" android:text="@string/String1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginTop="20dip" android:layout_marginRight="10dip" android:textSize="18dip" android:typeface="sans" android:textStyle="bold" android:layout_marginBottom="4dip" android:inputType="text|textMultiLine"/> <TextView android:id="@+id/textView2" android:text="@string/String2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginTop="20dip" android:layout_marginRight="10dip" android:textSize="16sp" android:typeface="sans" android:textStyle="bold" android:layout_marginBottom="4dip" android:inputType="text|textMultiLine"/> </LinearLayout> </ScrollView> </LinearLayout> A: Try deleting the setting android:inputType="text". Just had the same problem. I had android:multiLines="2", then I tried android:lines="2", then tried adding android:singleLine="false", but still my EditText would only show one line. I could scroll horizontally to get to the end of my line. What ended up working was deleting the setting android:inputType="text" . This allowed me to type in a long line that would wrap around to a second line. A: i've got this problem with a i5800 with CM7(2.3.7) and the emulator and works fine on a SGS-i9000 with CM9 (4.0.3). The problem was setting the theme at the manifest: <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.DeviceDefault" > I put " android:theme="@android:style/Theme.Holo " and if the device doesn't have it, the textview doesn't allow MultiLine. You can use the library " holoeverywhere " to port the holo theme to all devices. Regards. A: It could be false by default but did you try to add this in your TextView android:singleLine="false" -serkan A: To add to @KNU's answer... Here's a good related answer showing that you can use a different theme depending on the version of Android it is running on - just create a versioned styles folder. Answer here: TextView won't break text A: Set input type as inputType="text|textMultiLine". This made to resolve my issue. <TextView android:id="@+id/itemTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text|textMultiLine" android:textSize="@dimen/text_size_12" android:layout_gravity="center" android:gravity="center" android:text="Your Text Here"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7587746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where should I display or store data that is imported from a file? When I do an import of data from a file, such as csv or text file, I would like to display on a summary page (table view) about what is going to be imported to the database, and user can select or deselect what will be imported into the database. I would like to find out what is the best way of temporary storing these data to be displayed onto the summary page? To give a clearer understanding about what i am talking about, for example: * *I have a csv file that holds a list of products. *I would do an importation to read the csv file and display onto a summary page with table view and checkboxes to select/deselect some of the data. *After the selection, I would click the confirm button to store those checked data So between the process of getting the csv data to the summary page for display, where should I store the data, in the database as a tbl_temp data and clean off when done, or just read directly from the csv file? Thanks. A: I would think an array would do the trick unless you think your environment is really unstable or, for user interface reasons, then just store to a temp file. Temp db table seems a bit much. A: I would just display it in the browser, and stored? It's already stored, the uploaded CSV file! Unless you don't run into an actual problem with that approach, why care? A: Just use HTML to display the data read from the file in a web browser. Use standard HTML Form and form controls. Use PHP scripting logic to control what happens when the form is submitted. You could have the submit button hand off to a service or some other php file that could handle writing it to the db. Why bother writing to a temp table, to just read back out and display in a form to be then written back to a perm. table. If this were a process that you would be performing a lot, i might give it a little more consideration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I make a singleton bookmark in my org file? I have an org-mode task list that I keep in version control. I would like to press a key and turn the current position into a bookmark target that I will be able to access anywhere I have the list checked out, regardless of other changes that have been made to the document. This is why (bookmark-set) will not work. Additionally I would like to ensure that this target only occurs once in the file. If I put the target at a different position I want the original target to go away. Essentially, I want to combine features of Emacs bookmarks (the singleton aspect), and org-mode links (more robust persistence). What's the best way to do this? A: You want to read up about Markers: M-: (info "(elisp) Markers") RET This feature is what allows the mark ring to retain its relative locations regardless of buffer changes, for example. If you want the marker to be stored within the file itself, then you might want to include it as a local variable in the file itself, and use before-save-hook to update that to the current value. The local variable may need to be an integer, in which case you would need to translate it on loading and saving. (This is a little speculative, but I suspect it will do the trick.) A: The best solution I've been able to come up with is to use the text <<<BOOKMARK>>>, and to search for it when necessary. At some point I might write some functions that place this bookmark and delete it from elsewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Node.js listen to MongoDB change Is there a way for Node.js to listen to a change in a particular data in a collection of MongoDB, and fire an event if a change happens? A: MongoDB apparently now supports triggers and watch, this answer is outdated. [Original] I believe you are looking for a database trigger. Unfortunately, MongoDB has no support for them yet, so I don't think you can listen for changes directly from the database. You'll need to setup some sort of notification system (e.g. pub/sub) that alerts interested parties when a collection has changed. A: MongoDB 3.6 introduced change streams, which are designed to solve precisely this problem. Here's an example: https://github.com/thakkaryash94/mongodb-change-streams-nodejs-example const pipeline = [ { $project: { documentKey: false } } ]; const db = client.db("superheroesdb"); const collection = db.collection("superheroes"); const changeStream = collection.watch(pipeline); // start listen to changes changeStream.on("change", function (change) { console.log(change); }); A: Well, this is an old question, but I was struggling with the same thing. I found a number of tidbits that helped me put together a solution, and I've published it as a library: https://github.com/TorchlightSoftware/mongo-watch The library is written in coffeescript. Here's an example in javascript, for those that prefer. var MongoWatch = require('mongo-watch'), watcher = new MongoWatch({parser: 'pretty'}); watcher.watch('test.users', function(event) { return console.log('something changed:', event); }); A: Well, kind of late. But still, if someone looking to notify the MongoDB changes to the node.js then they can use mubsub library. This is active library and very easy to integrate with nodejs. It uses Mongo's tailable cursors and capped collections. It works in pub/sub fashion to notify the subscriber when the document inserted into the MongoDB. Check on Github for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to fix warning MIME type text/html How to fix Resource interpreted as Script but transferred with MIME type text/html. What can cause it and how to fix ? A: I assume you're looking at the Chrome console. The message means that you're loading a .js file, but the server is saying that the file is a HTML file. You could configure the server to send JavaScript files as text/javascript, but you can also safely ignore the message. I'm pretty sure any browser will accept the script even as text/html.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Creating a simple rule to rewrite a friendly URL to the physical URL I cannot wrap my head around URL rewriting. What I want to do seems very simple but I am having problems getting the results I want. I would like allow users to type www.mysite.com/search/real with an optional / at the end. This would take them to www.mysite.com/content/search_real_property.asp That's it. Here is the rule I have right now. The problem with this is it will keep stacking. RewriteRule ^(search) content/search_real_property.asp So this would work /search/real but so would search/real/search/real/search/real/ and others. A: Assuming there are no other issues, you've turned the rewrite engine on (RewriteEngine On) and that you're either adding the rewrite in httpd-vhosts.conf or an .htaccess file in the root of the web tree (so that any path issues are resolved)... then the issue is merely one of Regular Expression pattern matching. Though I'm a bit perplexed by ASP running on what appears to be an Apache server (assuming this IS mod rewrite we're talking about). So, all you really want is to terminate the match - something like: RewriteEngine On RewriteRule ^search/real/?$ /content/search_real_property.asp That will fix it to /search/real (with or without a trailing slash, the ? means match the preceding character 0 or 1 times) to /content/search_real_property.asp. As the $ sign denotes the line terminator (EOL effectively) there must be nothing after "real" (except perhaps that 1 forward slash). For greater flexibility you might want to look at what you can actually do with regular expressions, for instance... RewriteEngine On RewriteRule ^search/([^/]*)/?$ /content/search_real_property.asp?query=$1 Which would allow you to take any string and pass it in the address bar as a variable called query (Request.QueryString('query') IIRC). Try: http://www.regular-expressions.info/ for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VideoView / MediaPlayer Error (1, -18) I have an application that is built to API level 2.2. This application contains a video that starts playing as soon as it is launched. The video is played inside a VideoView and the actually video file is stored in my internal storage (files directory for my apps package). Most of the time it starts up just fine. But occasionally I get an error pop - up that says "Sorry, this video cannot be played." and has an Ok button. As soon as I press the ok button the video starts playing correctly. I need to figure out what is causing this error, or at the very least how I can catch whatever error it is and have it try again since it always works perfect after I hit ok. Inside the logs when this error box is shown I see these messages: ERROR/PVOMXAudDecNode(21215): Ln 2232 OMX_EventError nData1 -2147479547 nData2 0 ERROR/PlayerDriver(21215): Command PLAYER_PREPARE completed with an error or info -18 ERROR/MediaPlayer(9282): message received msg=100, ext1=1, ext2=-18 ERROR/MediaPlayer(9282): error (1, -18) ERROR/MediaPlayer(9282): callback application ERROR/MediaPlayer(9282): back from callback ERROR/MediaPlayer(9282): Error (1,-18) DEBUG/VideoView(9282): Error: 1,-18 Where can I find a reference as to what exactly error code -18 indicates? And does anyone have any suggestions I could try to prevent it from happening in the first place. I have only observed This error on the Sprint Epic 4g. Edit: well as far as I can tell no exceptions are getting thrown to me. I assume what is happening is that the video view knows to catch whatever exception is causing and it throws up the pop-up. Inside my log there is no exception stack trace just this reference to error -18. As for how I am calling prepare. I use this: mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); and this: mVideoView.setVideoPath(file.getAbsolutePath()); it calls prepare as part of setVideoPath (I assume it does anyway, but this method is undocumented). which causes onPrepared to get called in my listener. Edit 2: for now i've just added an onErrorListener like so: EDIT IMORTANT! this code will infinte error loop on ICS. For ICS devices I took out the setPath call, and returned false instead. It tries again by itself once and it succeeds. mVideoView.setOnErrorListener(new OnErrorListener(){ @Override public boolean onError(MediaPlayer arg0, int arg1, int arg2) { Log.i(myTag, "MP ERROR: "+ arg1 + " - " + arg2); mVideoView.setVideoPath(file.getAbsolutePath()); return true; } }); this catches the error and I can see in my logs that arg2 = -18 when this error happens. I just have it retry and return true so it doesn't throw up the dialog. So far i've never seen it fail twice in a row so this always starts the video correctly and doesn't make infinite loop. I am still very interested if anyone can tell me exactly what error code -18 indicates though. A: How do you catch potential exceptions thrown by prepare()? Do you catch IOException specifically and then retry calling the prepare()? Try using prepareAsync() instead, which does not block and calls listener when player is ready. Also it does not throw IOException. A: If you are running it on Froyo or Gingerbread the problem might be your device is not supporting playback of the file. Lower versions do not support videos encoded with formats other than baseline format. You may use some tools like video info on pc and check if the files are baseline formatted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to make JSON out of PHP and display it in my jQuery success case? I have this code in jQuery: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $("input[type=submit]").click(function() { var name = $("#problem_name").val(); var problem_blurb = $("#problem_blurb").val(); var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb; if(name=='' || problem_blurb == '') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "/problems/add_problem.php", data: dataString, success: function() { $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); // Here can update the right side of the screen with the newly entered information alert (dataString); } }); } return false; }); }); </script> And I have an AJAX call that I want to make JSON so I can unpack the JSON in the success case of the call to the AJAX. What I don't understand is how to create the JSON and how to make the front end detect it, and how to unpack it and display it. Any advice with that? My backend return will be simple. Just a name and description for every item returned. A: In add_problem.php use PHP's json_encode() on the object/array/scalar you want to return. In your javascript, use jQuery's .getJSON() to make your AJAX call. Alternatively, you can use jQuery's .ajax() function and specify dataType: 'json'. Here's documentation on jQuery's .getJSON(): http://api.jquery.com/jQuery.getJSON/ and here's some documentation on the PHP json_encode() function: http://www.php.net/manual/en/function.json-encode.php A: Make an array of what you want to return in php, preferably an associative array but it could be integer indexed and it will work just as well. $arr = array(); // Fill array with return data with PHP. $arr['name'] = 'John'; echo json_encode($arr); That will render your array as output in JSON format, which your jQuery success function will pick up in a parameter. Below, I name the parameter json but you can name it whatever you like. ... success: function(json) { var ob = $.parseJSON(json); // At this point, ob is a JavaScript object that should look pretty much the same // as the PHP object you created. alert(ob.name); // In this example, will alert 'John' } ... Also note that $.parseJSON was not introduced in jQuery until version 1.4.1. Please see: PHP Manual: json_encode()
{ "language": "en", "url": "https://stackoverflow.com/questions/7587765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Could not force hibernate to go to the database to get new object Session Factory: hibernate.current_session_context_class=jta hibernate.cache.use_second_level_cache=false Transaction: - UserTransaction is used. getCurrentSession() of SessionFactory is used to get Session. The problem is that I could not force the hibernate to access database to get the new values using Session.get(...) (it is updated outside) although I used Session.clear() or Session.evict(…) or Session.refresh(…), SessionFactory.evict(...). It always kept the old values. Do you have any idea? A: session.flush() --- will flush your memory update in db. session.clear() will clear session. Now query again will fire on database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Air App very large on install? I have just developed a new Android Air application using Adobe Flashbuilder and I am having the issue that when it is installed on a device it is 10mb in size which is huge. I dont understand why this is as when I look at the size of the entire App Folder in Flashbuilder it only ammounts to 1.6mb. Is there something that I should have done within Flashbuilder in order to compress the size? Can anyone please help with this as I really want to release this app but dont want to at this install size. A: 10 MB is really not that much. But it's probably because you're using a third party library and that's not inside your folder but it needs to be compiled within your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Which thread pattern to choose Say we have an interface method A, which is reentrant capable and for every entry in the method the current thread shall wait until an event occurs specifically for this thread: void interfaceMethodA() { doSomething(); waitHandle.WaitOne(); } Now, there will be set()-calls for the waitHandle, so that the method will be exited. But those set() calls must release a specific thread of the (possible) thread queue and not neccessarily the first one. What is a best practise for this pattern, maybe wait() and pulse() in combination with a thread id vector? To me this seems a bit like a mess... Thanks in advance, Juergen A: You could use a ThreadLocal<WaitHandle> ThreadLocal<WaitHandle> waitHandle = new ThreadLocal<WaitHandle>(() => new ManualResetEvent(false)); void interfaceMethodA() { doSomething(); waitHandle.Value.WaitOne(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access Css of Asp:Button So I want all buttons on my site to look the same and I need to edit a CSS file for them. I was just wondering how you can access the css style of all controls named -asp:button. Ie. Button { Font-size: 10px; } or #Button { Font-size: 10px; } So far this is not working. A: ASP.NET Button controls render as: <input type="submit"> You will need to give them a css class name that you can control in your css file. In server side code: myButton.CssClass = "myClass" OR in ASPX markup: <asp:Button CssClass="myClass" runat="server" ... /> CSS: .myClass { width: 100px } Edit having seen your comment: To modify all buttons across the site you need to use Javascript, the jQuery library is extremely effective at this. If you were using jQuery you would just have this script on your Master page: $(document).ready(function() { // Select all "input" controls with the type of "submit" and add your class to them $(input[type="submit"]).addClass('myClass'); }); A: Most newer browsers support Attribute Selectors, so you could do something like input[type="submit"] { //styles here } You'll get better all around support by applying a class though as others have suggested. A: You can inclue CSS class in your asp:button code to give them a class and control their style: <asp:button CssClass="mybuttons" /> Then you can use this class to style those buttons: .mybuttons{ font-size:10px; } If you had more buttons that are not ASP.NET generated then this class only applies to buttons that are ASP.NET generated not others. A: In .NET you need to provide a CSS class for your buttons. If you call it "Button1" for example, your CSS declaration would be: .Button1 { ... } A: An ASP button is rendered in HTML as an INPUT of type="submit"... you can access all the buttons by using INPUT, but of course there are other INPUTS as well... input { font-weight: bold; font-size: larger; background-color: Red; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem accessing sql server database 2008 r2 over network I've just finished my c# application with sql database built in 2008 r2 version I wanted to share this database over LAN and my connection string is : ConnectionString = @"Data Source=192.168.0.1,1433\SQLEXPRESS;user id=Rula; password=marojo;AttachDbFilename=\\192.168.0.1\Release\WEPA.mdf;Connection Timeout=30;Integrated Security=SSPI;user instance=true"; where 192.168.0.1 is the IP of the computer hosting the sqlexpress instance when I connect to database locally from the hosting computer I get no errors, but when I try to connect to the database from the shared application I get the following error: User doesn't have permission to perform this action. while I mapped the GUEST user to my database on the hosting machine since I knew that if a computer try to connect to database remotly, it connect as guest. notice: I have my application and database shared over network in the same folder, and again locally everything is ok Please what can I do to solve this problem ???? thanks in advance =-) A: If the 2 machines are not on the same domain this will fail. You might want to use sql logins A: The guest account would not be used in an trusted connection. The integrated connection uses the user account attached to the process using the connection string. http://forums.asp.net/t/822604.aspx/1 If you wanted to use integrated security, the web server would need to be configured to digest logins and then you would need to grant access to all (potential) authenticated users access to the database. This is typically not done due to the unnecessary complexity you are adding to the process. Just use sql links like Ali stated and be done with it. A: Okay, I see a couple things that are wrong in your connection string. Namely, you have defined a user id and password... then you go on to set the Integrated Security flag. These are mutually exclusive. Either it connects as the same user that the app is executing under (most likely the app pool user account) OR it connects as the user defined in your connection string. The reason you see a difference between 7 and XP is simply that one is defaulting to using the user id / password, the other is defaulting to using integrated security. I suggest that you visit http://www.connectionstrings.com/ in order to build a proper connection string. Update: Other things I see. First, AttachDbFilename can only work with integrated security. Obviously that isn't a possibility, so you need to get rid of that parameter and configure sqlexpress directly on the server to target that database file. Second, User Instance is for desktop deployments.. not servers. Get rid of it as well because it's going to be a huge memory hog. Third, read this: http://msdn.microsoft.com/en-us/library/ms247257(v=VS.100).aspx A: There are quite a few reasons this could be happening: * *SQL Browser service not turned on *Connection string using a trusted connection and you are not set up as that user (check what user your code is using by getting User from the current context) *You do not have the same protocols set up on the client (less likely) Since it is a permissions issue, you will most likely have to set up your windows domain account in the database to use it. If that is not an option for the application users, then you may desire to move to a sql account rather than windows accounts. A: problem solved !! there was just attaching problem when the database is attached to sql server management studio it's attached as an old name or related to the computer it's copied from Thank you everyone for your effort : )
{ "language": "en", "url": "https://stackoverflow.com/questions/7587779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Local property Should Be Explicitly Provided I cannot see the share in my facebook wall through a like button on my site I used https://developers.facebook.com/tools/debug I have a warning: " Warnings That Should Be Fixed The Property INFERRED og: local property Should Be Explicitly Provided, Even if a value INFERRED Can Be From Other tags. " Og: local, I found info here : https://developers.facebook.com/docs/beta/opengraph/internationalization/ So I've added : <meta property="og:locale:alternate" content="fr_FR" /> But that does not solve the problem :/ PS: i have a problem also with google +1, when i press the button he change the color to red A: About locale property: you must add primary, not alternate locale. I've added <meta property="og:locale" content="en_US" /> to my site <head> and it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is std::cout not printing the correct value for my int8_t number? I have something like: int8_t value; value = -27; std::cout << value << std::endl; When I run my program I get a wrong random value of <E5> outputted to the screen, but when I run the program in gdb and use p value it prints out -27, which is the correct value. Does anyone have any ideas? A: This is because int8_t is synonymous to signed char. So the value will be shown as a char value. To force int display you could use std::cout << (int) 'a' << std::endl; This will work, as long as you don't require special formatting, e.g. std::cout << std::hex << (int) 'a' << std::endl; In that case you'll get artifacts from the widened size, especially if the char value is negative (you'd get FFFFFFFF or FFFF1 for (int)(int8_t)-1 instead of FF) Edit see also this very readable writeup that goes into more detail and offers more strategies to 'deal' with this: http://blog.mezeske.com/?p=170 1 depending on architecture and compiler A: Because int8_t is the same as signed char, and char is not treated as a number by the stream. Cast into e.g. int16_t std::cout << static_cast<int16_t>(value) << std::endl; and you'll get the correct result. A: Most probably int8_t is typedef char int8_t Therefore when you use stream out "value" the underlying type (a char) is printed. One solution to get a "integer number" printed is to type cast value before streaming the int8_t: std::cout << static_cast<int>(value) << std::endl; A: It looks like it is printing out the value as a character - If you use 'char value;' instead, it prints the same thing. int8_t is from the C standard library, so it may be that cout is not prepared for it(or it is just typedefd to char).
{ "language": "en", "url": "https://stackoverflow.com/questions/7587782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How can I dynamically link to a directory that doesn't exist (yet)? I have an InstallScript project that I'm looking at manually recreating as a Basic MSI project. For the InstallScript project, we have several components that utilize dynamic file linking, and link to a location specified in a path variable. However, when I attempt to do this in the Basic MSI project, I receive an error: "The folder name you have entered is not a valid folder name on your system." This is completely correct - the specified directories don't exist, but they will be created at build time, before the installer is compiled. The InstallScript project seemed to have no qualms about dynamically linking to a directory that does not currently exist. The Basic MSI refuses to do it. Is there any way to link to directories that don't exist (yet)? Do I need to create dummy folders in these locations to appease InstallShield? A: Not the I endorse dynamic linking at all, but if you must, just create the empty directory where the build automation will create it and then setup your dynamic links. ( Design by contract. ) Course that's the problem with dynamic file linking...... there isn't much of a contract as compared to actually describing which files get installed where. YMMV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript, ajax loading external page, redirect breaks links I am building a chrome extension that loads a real preview of links you click in your search results. I analyze the links that come up, and add a <base> url element that handles all relative urls. However, when I do an ajax request for a pages html, but that page ultimately redirects, my <base> element is incorrect because it does not take into account the redirect that happened. To re-iterate, A user clicks a search result, I send an ajax GET request to that url to receive the pages html. I analyze the link that was clicked, and add an appropriate <base> element when I insert the pages html. (There isn't anything else in the DOM other than an iframe of the search results, so the <base> element doesn't alter anything else.) For any situation that doesn't have a redirect, the <base> element is always correct and works great. When I search 'ty' on google, www.ty.com redirects to world.ty.com. How can I detect the response came from world.ty.com?  My <base> element ends up with www.ty.com I am looking at attaching a window.onerror event that detects a 404 and somehow, I have no idea, corrects the <base> element. A: You cannot retrieve the final, redirected URL through the XMLHttpRequest object. You can however, create a workaround for this (replace your current <base> tag by the following code): <!--BEFORE linking any content (at the beggining of HEAD / document--> <script> document.write('<base href="'+location.href.replace(/"/g,"%22")+'" />'); </script> If you embed your script in the document, either use CDATA sections, or add a \ before the script tag, to prevent your page from incorrectly parsing the JavaScript code. Example of an implementation: function handleAjaxResponse(html){ //Searching for `<head>` or `<html>` to insert your HTNL is not reliable: // The web master may practice: // .. (without html/head tags)..<body> <input value="<head>" /> .... html = "<script>" + "document.write('<base href=\"'+location.href.replace(/\"/g,'%22')+'\" />')" + "<\/script>" + html; //Notice <\/script> ! //...output html... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moodle Installation When I install Moodle using Fantastico I cant seem to create courses. Does anyone know if there is a problem with Moodle 2.0.2 when installed through fantastico? I have tried uninstalling and reinstalling but I am going around in circles. Thanks for the help! A: Use the following bash commands to change permissions of the two moodle dirs. 777 is a little bit unsafe, but it's a fast way to check if the permissions are your problem. sudo chmod 777 -Rvf moodle sudo chmod 777 -Rvf moodledata A: Moodle-2.0.2 doesn't seems to have any issues. Can you post the error messages you got when creating the courses? Several security issues(not related to course creation) were resolved in Moodle-2.1.1 so it's highly recommended to use the latest stable build. Installing Moodle from source is easy and straight forward process, so give it a try. A: Your problem sounds more like a permissions issue than a moodle version issue. Ensure you are in either the admin, manager or teacher role, and you should be able to create new courses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to hide number button on UIKeyboard? Is there a way to hide number button and space button? Mantaining UIKeyboard transparency?? I need a keyboard with only letters, backspace and NEXT button, nothing else. I need compatibility from iOS 3.1+! thanks. A: Apart from making your own keyboard (it's not that difficult) use UITextField and the delegate method to filter the input. A: This page has a great tutorial about customizing a keyboard. Looks like you might be able to use this to hide the buttons you don't want, or change the current buttons. Basically, you should register as an observer for the UIKeyboardWillShowNotification: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; and do customization inside your keyboardWillShow: notification handler: - (void)keyboardWillShow:(NSNotification *)notification { // locate keyboard view UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; UIView* keyboard; for(int i=0; i<[tempWindow.subviews count]; i++) { keyboard = [tempWindow.subviews objectAtIndex:i]; // keyboard view found; add the customization to it if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) UIView *customView = [[UIView alloc] init]; // do stuff to customView here [keyboard addSubview:customView]; } } The prefix @"<UIKeyboard" in this line if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) might be different. So you should loop through once using NSLog to print out all the subview descriptions to see what string you need to check for. And here is some info about the default keyboards that are provided (non-customized) UIKeyboardType - The type of keyboard to display for a given text-based view. Check out this UIKeyboardType page for images of each keyboard type. Here are some definitions from UITextInputTraits Protocol Reference typedef enum { UIKeyboardTypeDefault, UIKeyboardTypeASCIICapable, UIKeyboardTypeNumbersAndPunctuation, UIKeyboardTypeURL, UIKeyboardTypeNumberPad, UIKeyboardTypePhonePad, UIKeyboardTypeNamePhonePad, UIKeyboardTypeEmailAddress, UIKeyboardTypeDecimalPad, UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable } UIKeyboardType; * *UIKeyboardTypeDefault Use the default keyboard for the current input method. Available in iOS 2.0 and later. * *UIKeyboardTypeASCIICapable Use a keyboard that displays standard ASCII characters. Available in iOS 2.0 and later. * *UIKeyboardTypeNumbersAndPunctuation Use the numbers and punctuation keyboard. Available in iOS 2.0 and later. * *UIKeyboardTypeURL Use a keyboard optimized for URL entry. This type features “.”, “/”, and “.com” prominently. Available in iOS 2.0 and later. * *UIKeyboardTypeNumberPad Use a numeric keypad designed for PIN entry. This type features the numbers 0 through 9 prominently. This keyboard type does not support auto-capitalization. Available in iOS 2.0 and later. * *UIKeyboardTypePhonePad Use a keypad designed for entering telephone numbers. This type features the numbers 0 through 9 and the “*” and “#” characters prominently. This keyboard type does not support auto-capitalization. Available in iOS 2.0 and later. * *UIKeyboardTypeNamePhonePad Use a keypad designed for entering a person’s name or phone number. This keyboard type does not support auto-capitalization. Available in iOS 2.0 and later. * *UIKeyboardTypeEmailAddress Use a keyboard optimized for specifying email addresses. This type features the “@”, “.” and space characters prominently. Available in iOS 2.0 and later. * *UIKeyboardTypeDecimalPad Use a keyboard with numbers and a decimal point. Available in iOS 4.1 and later. * *UIKeyboardTypeAlphabet Deprecated. Use UIKeyboardTypeASCIICapable instead. Available in iOS 2.0 and later.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android how many threads can I have going? I have an Android app that has separate things going on but are all basically threads (and definitely are threads to the Android debugger) There are multiple animation listeners that loop and call each other There is a countdown timer that is always counting down to zero after it is initiated Now I need to consider adding more countdown timers. How many of these kind of looping processes can I have going on? In this particular implementation I am not concerned about performance, efficiency, etc, until it becomes apparent. Insight appreciated A: I would be very surprised to learn that you exhausted the number of threads you can use safely in an android application, as long as you are properly managing their lifetime and prevent "busy loops"and the like from occuring. One thing I did learn though, I am pretty sure you can only have 5 asynctasks operational at any time, and they will arbitrarily continue to exist and get killed or respawned by themselves if you start new ones...ie if i turned an asynctask on then off five times the debugger will say 5 async threads operational, but I can continually toggle on and off as much as I want because the resource pool will kill the oldest dead asynctask. A: There is no maximum that I know of. I can tell you, however, that you most likely don't NEED that many threads. You can keep countdown listeners in a single thread using Android's Handler, specifically the postDelayed() method. Start a Looper in a separate thread, and use a Handler to manage the timeouts -- don't busy wait, or sleep-loop. A: I don't believe countdown timer will create threads--it should simply add your task to a queue on your main thread from the looks of it. All your listeners should take place on the same thread as well (there is a single thread that manages all listeners (for visible objects anyway). So you probably aren't using anywhere near as many threads as you think you are. If you were creating a lot of threads I'd be worried--they are really hard to keep synchronized and may cost you a lot more than you'd gain, but with the structures listed I'd go ahead and allocate as many as you feel appropriate (but test for performance on a cheap device of course)
{ "language": "en", "url": "https://stackoverflow.com/questions/7587808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: invalid types ‘float[int]’ for array subscript error and passing variables to scipy.weave.inline I've been playing with Scipy's inline tool (via weave) for fun, but I'm running into some trouble. My C is rusty and I have a feeling that I'm missing something simple. The function below is designed to take a 3D float32 numpy array. I'm using a massive set of gridded atmospheric data, but this should work with any 3D array. This then takes the grid and gets the arithmetic mean across axis i, for each point j,k (i.e. if i is the time axis, j and k are lat/lon, then I'm averaging across time for each grid point). I hope that my code is doing this and avoiding numpy NaNs (I believe that isnan() works in inline C/C++...?). But, whether it does this or not, I'm having trouble getting the code to compile without errors such as: tools.py: In function ‘PyObject* compiled_func(PyObject*, PyObject*)’: tools.py:93:45: error: invalid types ‘float[int]’ for array subscript tools.py:95:51: error: invalid types ‘float[int]’ for array subscript tools.py: In function ‘PyObject* compiled_func(PyObject*, PyObject*)’: tools.py:93:45: error: invalid types ‘float[int]’ for array subscript tools.py:95:51: error: invalid types ‘float[int]’ for array subscript I think I'm declaring and initializing properly, so perhaps something isn't being passed to weave in the way I think it is? I would love it if someone could help me out with this. Here is the function: from scipy.weave import inline def foo(x): xi = np.shape(x)[0] xj = np.shape(x)[1] xk = np.shape(x)[2] code = """ #line 87 "tools.py" int n; float out[xj][xk]; for (int k = 0; k < xk; k++) { for (int j = 0; j < xj; j++) { n = 0; for (int i = 0; i < xi; i++) { if (!isnan(x[i][j][k])) { n += 1; out[j][k] += x[i][j][k]; } } out[j][k] = out[j][k]/n; } } return_val = out; """ awesomeness = inline(code, ['x', 'xi', 'xj', 'xk'], compiler = 'gcc') return(awesomeness) A: you can create the out array in python first, and pass it to C++. In C++ you can get the shape of x by Nx[0], Nx[1], Nx[2]. And you can use macros defined for array to access it's elements. For example: X3(k,j,i) is the same as x[k,j,i] in python, and OUT2(j,i) is the same as out[j,i] in python. You can view the automatic created C++ code to know what variables and macros you can use for the arrays. To get the folder of C++ code: from scipy import weave print weave.catalog.default_dir() My compiler doesn't support isnan(), so I use tmp==tmp to check it. # -*- coding: utf-8 -*- import scipy.weave as weave import numpy as np def foo(x): out = np.zeros(x.shape[1:]) code = """ int i,j,k,n; for(i=0;i<Nx[2];i++) { for(j=0;j<Nx[1];j++) { n = 0; for(k=0;k<Nx[0];k++) { double tmp = X3(k,j,i); if(tmp == tmp) // if isnan() is not available { OUT2(j,i) += tmp; n++; } } OUT2(j,i) /= n; } } """ weave.inline(code, ["x","out"], headers=["<math.h>"], compiler="gcc") return out np.random.seed(0) x = np.random.rand(3,4,5) x[0,0,0] = np.nan mx = np.ma.array(x, mask=np.isnan(x)) avg1 = foo(x) avg2 = np.ma.average(mx, axis=0) print np.all(avg1 == avg2) You can also use blitz converter to access array in C++. For the detail, try google: weave.converters.blitz A: C doesn't support dynamic array sizing like out[xj][xk]. you either have to hardcode the sizes or use malloc or something supported by Weave to dynamically allocate the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to make PUT/POST/DELETE HTTP Call using CORS in JQuery 1.6.4 So, I can successfully make a GET call to my service using CORS. However, something must be going wrong at the preflight level for the POST, PUT, and DELETE operations. However, from what I can tell, the header responses my server is returning in response to the OPTIONS query are correct and match those described in Here is my javascript code, using $.ajax in JQuery 1.6.4. $.ajax({ url: 'http://myhome:8080/TaskApproval/resources/tasks/2', context: this, data: '<?xml version="1.0" encoding="UTF-8"?> <task> <description>Get carrots from the grocery store</description><originator>Chris</originator><subject>Get Carrots !!</subject><taskId>2</taskId> </task> ', timeout: 30000, type: 'PUT', contentType: 'application/xml', success: function(response) { alert(response); result = response; }, error: function(xhr) { alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText); } }); Now, this is what my HTTP Trail looks like, courtesy of Firebug. Request: OPTIONS /TaskApproval/resources/tasks/2 HTTP/1.1 Host: widgethome:8080 User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Origin: http://localhost:8080 Access-Control-Request-Method: PUT Access-Control-Request-Headers: content-type Response: HTTP/1.1 200 OK X-Powered-By: Servlet/3.0 Server: GlassFish v3 Allow: OPTIONS,GET,DELETE,HEAD,PUT, POST Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE Access-Control-Max-Age: 1000 Access-Control-Allow-Headers: * Content-Type: application/xml Content-Length: 2792 Date: Wed, 28 Sep 2011 18:21:11 GMT There is then no PUT (or POST or DELETE), I just get that annoying non-helpful xhr object that looks like this: readyState 0 responseText "" status 0 statusText "error" I'm very mystified that if I then remove the contentType in my Ajax call, and it sends an invalid content type per my application, the browser actually sends my PUT request, which fails because the Content-Type is not application/xml. See below: $.ajax({ url: 'http://myhome:8080/TaskApproval/resources/tasks/2', data: '<?xml version="1.0" encoding="UTF-8"?> <task> <description>Get carrots from the grocery store</description><originator>Chris</originator><subject>Get Carrots !!</subject><taskId>2</taskId> </task> ', timeout: 30000, type: 'PUT', //contentType: 'application/xml', success: function(response) { alert(response); result = response; }, error: function(xhr) { alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText); } }); Leads to this HTTP Trail, again courtesy of Firebug: Options Request: OPTIONS /TaskApproval/resources/tasks/2 HTTP/1.1 Host: myhome:8080 User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Origin: http://localhost:8080 Access-Control-Request-Method: PUT Options Response: HTTP/1.1 200 OK X-Powered-By: Servlet/3.0 Server: GlassFish v3 Allow: OPTIONS,GET,DELETE,HEAD,PUT, POST Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE Access-Control-Max-Age: 1000 Access-Control-Allow-Headers: * Content-Type: application/xml Content-Length: 2792 Date: Wed, 28 Sep 2011 18:26:23 GMT Put Request: PUT /TaskApproval/resources/tasks/2 HTTP/1.1 Host: myhome:8080 User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Accept: */* Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: http://localhost:8080/TaskApproval/crossdomain.html Content-Length: 197 Origin: http://localhost:8080 Put Response: HTTP/1.1 415 Unsupported Media Type X-Powered-By: Servlet/3.0 Server: GlassFish v3 Content-Type: text/html Content-Length: 1069 Date: Wed, 28 Sep 2011 18:26:23 GMT The 415 makes sense because I don't support content application/x-www-form-urlencoded, only application/xml. What I don't understand is why does setting the Content-Type correctly prevent the PUT? Thanks for any insight! I've been searching the internet for quite some time, and can't find a solution for this problem. A: You need to include CORS headers in both the preflight and the actual response. So try including the following headers in the PUT response from your server: Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Headers: Content-Type One other thing to note is that the CORS spec does not list '*' as a valid value for Access-Control-Allow-Headers: http://www.w3.org/TR/cors/#access-control-allow-headers-response-he Instead, you should try explicitly listing all the request headers like so: Access-Control-Allow-Headers: Content-Type You must include Content-Type because the Content-Type is not considered a simple header when its value is not application/x-www-form-urlencoded, multipart/form-data, or text/plain (See the CORS spec for more details on simple headers). A: Don't forget to make sure your prefight Options request also responded with: Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Headers: Content-Type
{ "language": "en", "url": "https://stackoverflow.com/questions/7587812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: mediaelement.js with GWT I have a problem for integrate mediaelement in my GWT Integration. You know in GWT application you have only one HTML page and I need in DialogBox to integrate a video player, video works good but I don't have controls like fullscreen, duration time. That seems that javascript function doesn't work. I use a HTML widget for integrate video tag. Code : HTML myHTML = new HTML("<body onload='displayPlayer()'>"+ "<video width='640' height='360' src='vp8.webm' type='video/webm' "+ "id='player1' "+ "controls='controls' preload='none'></video>"+ "<span id='player1-mode'></span>"+ "</body>"); > function displayPlayer() { $('audio,video').mediaelementplayer({ success: function(player, node) { $('#' + node.id + '-mode').html('mode: ' + player.pluginType); } }); } I added scripts and CSS in my HTML page <script type="text/javascript" language="javascript" src="displayplayer.js"></script> <script type="text/javascript" language="javascript" src="jquery.js"></script> <script type="text/javascript" language="javascript" src="mediaelement.min.js"></script> <script type="text/javascript" language="javascript" src="mediaelementplayer.min.js"></script> <script type="text/javascript" language="javascript" src="mediaelement-and-player.min.js"></script> Do you any ideas ? thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help creating a simple regex in Perl I'm still useless when it comes to creating regex patterns. This one has got to be really easy. Given the string: /home/users/cheeseconqueso/perl.pl I want to place the string ./ right in front of the very last / in the original string to produce: /home/users/cheeseconqueso/./perl.pl Thanks in advance - I'm sure this simple example will help me for a lot of other stupid stuff that shouldn't be up here! A: my $variable = "/home/users/cheeseconqueso/perl.pl"; $variable =~ s/(.*\/)([^\/]+)$/$1\.\/$2/; A: Here's my solution based on what I was thinking of when I left the comment to your question: use strict; use warnings; my $str = '/home/users/cheeseconqueso/perl.pl'; my @arr = split('/',$str); my $newstr = join('/', @arr[0..(@arr-2)], '.', $arr[-1]); Edit: If you're really keen on using a regex, this is the simplest one I've found: $str =~ s|(.*/)(.*)|$1./$2|; It takes advantage of the greediness of the initial * in the first group to take every character up to the last /, then matches everything else in the second group. It's a little easier to read with the | delimiters so you avoid leaning toothpick syndrome. A: this is using File::Basename not with regex, you can use this cpan module if you find hard to write regex. use File::Basename; $path = '/home/users/cheeseconqueso/perl.pl'; $newpath = dirname($path) . './'.basename($path); A: You actually don't need a regex, you can just split the string: my $str='/home/users/cheeseconqueso/perl.pl'; #Array: ('','home','users','cheeseconqueso','perl.pl') my @arr=split(/\//,$str); my $output=join('/',@arr[0..($#arr-2)]); # '/home/users/cheeseconqueso' $output.='/./' . $arr[$#arr]; #Pops on the '/./' and the last element of @arr. A: s/(.*)\/(.*)/\1.\/\2/ As noted by CanSpice, split works fine here too. A: Try this: my $str = "/home/users/cheeseconqueso/perl.pl"; if($str =~ /^(.*)(\/)(\w+\.\w+)$/) { $str = $1.'/.'.$2.$3; } A: Regex? We don't need no stinkin' regex. l-value substr() to the rescue! #!/usr/bin/perl use warnings; use strict; $_ = "/home/users/cheeseconqueso/perl.pl\n"; substr($_, rindex($_, '/'), 0) = '/.'; print;
{ "language": "en", "url": "https://stackoverflow.com/questions/7587821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Opencart .htaccess - allows access to specified folder I've got an OpenCart site, but need to create an addtional /test directory which is accessible. By default, all requests are sent to OpenCart. I'm trying to make it send all except /test. I've tried a few suggestions on this site already, but either nothing happens, or I get a 500 Internal Server Error. This is the rewrite part of the OpenCart provided .htacccess: RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA] I think I need a line like the following after RewriteBase, but can't get anything working yet. RewriteCond %{REQUEST_URI} !^/test Thanks! A: I think RewriteCond %{REQUEST_URI} !^test/(.*) should do it A: RewriteBase /YOUR_SUB_DIR/ replace 'YOUR_SUB_DIR' with yours
{ "language": "en", "url": "https://stackoverflow.com/questions/7587826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: autostorage email attachment file I was recently asked by my boss to create... something i find nearly impossible without human intervention The thing is, to have our users send a xml with some data via email, but my boss wants it to * *That the attached file be stored on a specific folder on a specific server whenever a new email arrives with the attachment *The process will verify that there's a attached file on the email and thats its correct, meaning that its xml structure is as we asked it and has all the data stored on it *Some of the xml file data be stored on a database (filename, file path, main id) for it to be searched on a little app which displays the xml data and so be able to download a copy of the file My main problem is, having this process that keeps on cheking new received mails, retrieves the attachments, checks it and store it, i don't know if its possible, or where to start. For once, the email server needs to have some kind of programability processes, but still, looks like the one in charge of our mail server doesn't have any idea if there's something like that. Any one can give me an idea on where to start with this? I suggested we had a upload option on our main webpage, and we will have it, but they really want the email option and that all the process its automated A: There are a couple of ways to do this. I would start by looking into programatically retrieving the emails via IMAP or POP. This seems like the approach with the least amount of friction involved for you. The person in charge of your email server could just set you up an account that all the messages are forwarded into. Alternatively you can write something to forward all of the emails to another mail server and use that to pipe the emails into a script or have it forward to a service like cloudmailin.com (which can also send the attachments to S3) so that you can obtain the message programatically. Once you have the message you then just need to parse out the attachment and copy it over to the folder that you need. A: If you have shell access on the mail server, you could use Procmail. It (or whatever you have in your .forward or equivalent) will be fired with each incoming message as its standard input. If not all incoming messages are interesting, having Procmail as a wrapper would certainly make sense. Anyway, the task to validate and detach the incoming attachment is then "just a simple matter of programming", but I hope this should at least be enough to get you started. :0B * ^Content-type: application/x-perimental-xml or what have you | validate-and-store-and-extract-some-data-to-sql You could certainly make it more elaborate than this (and most likely you will have to) but this essential recipe is not very complicated. ... Your "almost impossible" characterization sounds like you're on Windows (oops, sorry, couldn't resist) but perhaps your mail server is a Unix server nevertheless.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I manage WCF log file sizes programatically? We're having a bit of trouble managing the file size of the WCF logs at my organization. The logs are getting large, really large. Multiple gigabytes of data. I am a bit of a WCF rookie, but I realize that there are options to turn down the level of information being logged. However, what I'd prefer to do is setup some sort of automatic archiving process for the logs, so that on a certain frequency (maybe every night) the logs are automatically archived into a separate folder for up to 5 days. This way we can have fresh and manageable log sizes in the morning when we discover an issue with one of our services. I don't really know what the best approach to this would be. Are there .NET classes that give me access to the SVC log files? Or, would I need to write a service that specifically turns off the service, renames and moves the logs on the file system, then turns the service back on? Any help is appreciated! A: There is a nice CodeProject for rolling your WCF service logs: Ever had the problem of growing svclog files after configuring tracing in a productive WCF environment? Did not want to restart the application just for deleting or moving the trace files? Then, you will like the RollingXmlWriterTraceListener, which is a specialized XmlWriterTraceListener, and is completely compatible with the WCF tracing facility. Does the trick nicely ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7587836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to get all the element from HTML who having same class attribute? I developing one asp.net application in that I using htmlagility dll to get all <div> tags which is same class attributes.. How to get all elements who have same class from whole html page, I getting top 1 div who having class='myclass' but in, my case I want to all div tags who have 'myclass' class. var vardoc = web.Load("<any website url>"); var varmyclass = doc.DocumentNode.SelectSingleNode("//div[@class='myclass']"); when I used above method then I getting inner html content of the 'myclass' but in my html contents there are many div tags who have class 'myclass'. I want to get all <div> who have same class using HTMLagility or other A: Don't select a single node in that case. You are using SelectSingleNode, which will return only one node. Use SelectNodes instead: var varmyclass = doc.DocumentNode.SelectNodes("//div[@class='myclass']"); A: You're pretty much searching an XML document for these nodes. First off, you're selecting a single node which will only return 1. You need to use SelectNodes. example: var varmyclass = doc.DocumentNode.SelectNodes("//div[@class='myclass']"); Update - Removed my Xpath suggestion as it didn't work as I thought it would... A: Two issues, first one is that you should be using SelectNodes() instead as the other answers have pointed out since you want to select multiple nodes. Also, your XPath is a bit restrictive. It will only get div elements which has only one class, myclass but doesn't include those that have multiple classes. I suspect you want to include those as well. Rather than checking if the class is equal, check if it contains it. var xpath = "//div[contains(@class,'myclass')]"; var query = doc.DocumentNode.SelectNodes(xpath);
{ "language": "en", "url": "https://stackoverflow.com/questions/7587840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }