text
stringlengths
8
267k
meta
dict
Q: Emacs mmm-mode not highlighting a ruby submode (ERB) without a newline? Elisp advice? I'm trying to get ERB templates 'working' in Emacs 22 and 23 (two different servers). I've found several examples online that use almost exactly this snippet. Note that I don't want any background colors, as I'm working in a terminal over SSH. This is correctly detecting where the first region begins, as the mode line changes when the point moves. But something is not right, since it doesn't highlight my ruby code unless I clear it with at least two blank lines, and it also seems to consider everything below the first segment of ruby code to be ruby code, even after the closing tags. I can only assume that the patterns are not correct, and I'd like to understand the syntax so I can debug it better myself. Can anyone tell me what all the @ symbols mean here? Moreover, has anybody actually gotten ERB templates working in mmm-mode? (require 'mmm-mode) (require 'mmm-auto) (setq mmm-global-mode 'maybe) (setq mmm-submode-decoration-level 0) (mmm-add-group 'fancy-html '((html-erb :submode ruby-mode :match-face (("<%#" . mmm-comment-submode-face) ("<%=" . mmm-output-submode-face) ("<%" . mmm-code-submode-face)) :front "<%[#=]?" :back "%>" :insert ((?% erb-code nil @ "<%" @ " " _ " " @ "%>" @) (?# erb-comment nil @ "<%#" @ " " _ " " @ "%>" @) (?= erb-expression nil @ "<%=" @ " " _ " " @ "%>" @))))) (add-to-list 'mmm-mode-ext-classes-alist '(html-mode nil fancy-html)) A: I have a similar setup, which might even have been the basis for what you're trying. Executing font-lock-fontify-buffer even with the newlines missing causes the correct highlighting to be displayed, so the problem presumably lies in mmm-mode. The main benefit of the mmm-mode setup has been that I can easily see the ERB regions; the setup has never syntax-highlighted embedded code perfectly for me, and although I've been updating mmm-mode for compatibility with recent emacsen, it might be worth you exploring alternatives if you really want that detailed sub-region highlighting. Like you, I've been unwilling to resort to nxhtml because it's very heavy-weight, and I believe it also has display quirks. I'll also point out that haml-mode does quite a nice job of syntax-highlighting embedded code blocks natively (just ruby code originally, until I contributed javascript and css support), and that's one of several reasons why I prefer haml to html+erb these days. A: Firstly, if you have SSH access to the box, use tramp. I have no deep MMM-mode magic for ERB. However, I use Rinari with nxhtml and it all just works. Ask questions about rinari and nxhtml if you need help getting that going. A: It's fixed now. Update to the latest mmm-mode from git repo or MELPA.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: LinqDataSource class example Just starting to look into using LinqDataSource for a GridView and I’m looking for a few more examples on how to set up my data source. I am hoping later on to use it against a SharePoint List but for now I’m simply after some detailed examples for a class that I can retrieve data from and update. Here is an example class from MS. I just after more than one example so i have better idea how this work. A Simple example that is known to work and is a little more complicated would be great public class MovieLibrary { string[] _availableGenres = { "Comedy", "Drama", "Romance" }; public MovieLibrary() { } public string[] AvailableGenres { get { return _availableGenres; } } } Cheers A: I'm using LinqDataSource with SPGridView here is my code. <SharePoint:SPGridView runat="server" ID="spgvUserTrainingLists" AutoGenerateColumns="false" DataSourceID="linqDsEmployeeTrainingLists" DataKeyNames="RowId" OnRowDataBound="spgvUserTrainingLists_RowDataBound" AllowSorting="true" AllowPaging="true" PageSize="15" AllowFiltering="true" FilteredDataSourcePropertyName="Where" FilteredDataSourcePropertyFormat='{1} == "{0}"' FilterDataFields=",TrainingType,,Trainer,Status"> <Columns> <SharePoint:SPBoundField HeaderText="Ref #" SortExpression="RefNo" DataField="RefNo" /> <SharePoint:SPBoundField HeaderText="Type" SortExpression="TrainingType" DataField="TrainingType" /> <asp:TemplateField HeaderText="Training" SortExpression="TrainingTitle"> <ItemTemplate> <asp:HyperLink ID="hlTrainingDetail" runat="server" Text='<%# Eval("TrainingTitle") %>' NavigateUrl="#" /> </ItemTemplate> </asp:TemplateField> <SharePoint:SPBoundField HeaderText="Trainer" SortExpression="Trainer" DataField="Trainer" /> <SharePoint:SPBoundField HeaderText="Status" SortExpression="Status" DataField="Status" /> <asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="imgDelete" ImageUrl="~/_layouts/images/DELITEM.GIF" runat="server" UseSubmitBehaviour="false" CommandValue='<%# Eval("RowId") %>' OnClientClick="javascript:DeleteTraining(this);" /> </ItemTemplate> </asp:TemplateField> </Columns> <EmptyDataTemplate> No training yet. </EmptyDataTemplate> </SharePoint:SPGridView> <SharePoint:SPGridViewPager ID="SPGridViewPager1" runat="server" GridViewId="spgvUserTrainingLists" /> <aspweb:LinqDataSource runat="server" ID="linqDsEmployeeTrainingLists" OnSelecting="linqDs_Selecting" /> In the LinqDataSource Selecting event is where the data binding happened protected void linqDs_Selecting(object sender, LinqDataSourceSelectEventArgs e) { object parameter = null; if (e.SelectParameters.TryGetValue("employee", out parameter)) { e.Result = DefaultBLL.GetEmployeeTrainingLists(parameter.ToString()); } } Hope this help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble with properties in Objective-c I'm having trouble assigning an instance of a class to the following UITableViewController subclass: @interface MyTableViewController : UITableViewController </*usual protocols*/> @property (nonatomic, retain) MyClass *myClass; @end I'm currently assigning a non-null instance of MyClass to an instance of MyTableViewController like this: MyTableViewController *myTableViewController = [[MyTableViewController alloc] init]; MyClass *nonNullInstanceOfMyClass = [[MyClass alloc] init]; myTableViewController.myClass = nonNullInstanceOfMyClass; [self.navigationController pushViewController:myTableViewController animated:YES]; [nonNullInstanceOfMyClass release]; [myTableViewController release]; The problem is that myClass is null in MyTableViewController's viewDidLoad. Why is this happening? Edit #1: I check that nonNullInstanceOfMyClass is not null by NSLogging it. Edit #2: Provided more code. Also viewDidLoad seems to be called before I push the view controller (which could cause the problem... although it seems odd). Edit #3: Fixed by moving self.tableView.delegate = nil; and self.tableView.dataSource = nil; from init to viewDidLoad. A: Are you doing anything between instantiating the view controller and assigning to the property? viewDidLoad doesn't necessarily get called when you push the view controller onto the navigation stack - it gets called whenever it needs to load the view. So, for example, NSLog(@"%@", myTableViewController.view); would trigger viewDidLoad, and if you did this before assigning to the property, that would explain this behaviour. Could you post actual code instead of an approximation please? There could be important details you are leaving out. A: viewDidLoad is fired when the View is loaded from xib. You have a couple options here. Easiest is the viewDidAppear: method - (void)viewDidAppear:(BOOL)animated { // Handle what you want for when your view has become visible. // This may happen more then once. So a flag for the first time will // give you a sufficient Limit for Initialization } alternatively there is the viewWillAppear: Another option is to have IB load the Class for you this way it is not null. And will be available in viewDidLoad: Your MyClass will need to be a UIView. You place a UIView (as a placeholder) into the TableViewController's View where you want it. Then you set its class type in Interface Builder in the Identity Inspector under Custom Class. Finally you drag a connection from the IBOutlet @property (nonatomic, retain) IBOutlet MyClass *myClass; to your Custom Class UIView in interface builder Then when Interface builder initializes your class it will populate that property with a blank instance of that class. A third option would be a lazy load property Here is how I do lazy load //we will take for granted that your @property is in the header //and the following Synthesize is on the class @synthesize myClass=_myClass; // setting instance variable to avoid confusion - (MyClass*) myClass { if (_myClass == nil) _myClass = [[MyClass alloc] init];//Create a default instance and retain it return _myClass; } then you use self.myClass and your getter method will create one for you. EDIT: I added the =_myClass to the @synthesize to change the instance variable away from the property this way using myClass will generate an error and you will be forced to use self.myClass to get the property accessor. A: Change the following line from: @property (nonatomic, retain) MyClass *myClass; to: @property (nonatomic, assign) MyClass *myClass;
{ "language": "en", "url": "https://stackoverflow.com/questions/7522897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: abbreviations in mysql select, what do they mean? i have a problem to understand what happens in this query: $db->select("select r.id, m.mailing_id, r.email, m.done from lp_relations r, lp_mailings_relations m where m.relation_id=r.id and m.mailing_id=? order by r.name", $rs[$i]["id"] its about the letters r. and m. before the fieldnamesthese, these aren't tablenames, but i suspect abbreviations of some kind of joins, but i have never seen them before this way. I can rewrite my own query to get the job done, but i like to know what this means, so i can tackle the problem itself (mailing sent twice) Thanks in advance for any help! A: They're "aliases" of table names. Note how in your query you say "from lp_relations r..."? The "r" at the end of that is aliased to lp_relations now. So you can refer to lp_relations in that query with just "r.". It's a shorthand to make things a bit more readable. A: Look at FROM lp_relations r, lp_mailings_relations m. After real table names you find a new name, used to make SELECT part shorter and easy to read. So table lp_relations becomes r and table lp_mailings_relations becomes m! You could write: SELECT r.id, r.email, m.mailing_id, m.done FROM lp_relations r INNER JOIN lp_mailings_relations m ON m.relation_id=r.id WHERE m.mailing_id=? ORDER BY r.name A: r stands for the lp_relations table and m stands for the lp_mailings_relations table. The aliases help you do joins by separating out the fields. For instance if you had a users table that had the same field name found in a products table, the aliases help separate that out (non-ambiguous).
{ "language": "en", "url": "https://stackoverflow.com/questions/7522899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Reasoning behind having to specify L for long, F,D for float, double A few related questions here. As per the title, why is it a requirement if we are specifying the variable type as long or float, double? Doesn't the compiler evaluate the variable's type at compile time? Java considers all integral literals as int - is this to lessen the blow of inadvertent memory waste? And all floating-point literals as double - to ensure highest precision? A: This becomes important when you do more than a simple assignment. If you take float x = 0.1 * 3.0; it makes a difference if the computer does the multiplication in double precision and then converts to single precision or if it converts the numbers to single precision first and then multiplies. edit: Not in this explicit case 0.1 and 3.0, but if your numbers become complex enough, you will run into precision issues that show differences between float and double. Making it explicit to the compiler if they are supposed to be doubles or float avoids ambiguity. A: When you have a constant there are subtle differences between value which look the same, but are not. Additionally, since autoboxing was introduce, you get a very different result as less. Consider what you get if you multiply 0.1 by 0.1 as a float or as a double and convert to a float. float a = (float) (0.1 * 0.1); float b = 0.1f * 0.1f; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b)); prints a= 0.00999999977648258209228515625 b= 0.010000000707805156707763671875 a == b is false Now compare what you get if you use either float or int to perform a calculation. float a = 33333333f - 11111111f; float b = 33333333 - 11111111; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b)); prints a= 22222220 b= 22222222 a == b is false Compare int and long long a = 33333333 * 11111111; // overflows long b = 33333333L * 11111111L; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b)); prints a= -1846840301 b= 370370362962963 a == b is false compare double with long double a = 333333333333333333L / 333333333L; double b = 333333333333333333D / 333333333D; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b)); prints a= 1000000001 b= 1000000000.99999988079071044921875 a == b is false In summary its possible to construct a situation where using int, long, double or float will produce a different result compared with using another type. A: I believe it's simply to avoid confusion. How will the compiler know that 1.5 is meant to be a float or double if there's no default for it to fall back on? As for evaluating variables, please note that variables != literals. Edit 1 Regarding some comments, I believe that there are times when you wouldn't want the compiler to automatically translate the literal on the right to variable type on the left. Edit 2 And of course there's public void foo(int bar) { //... } public void foo(long bar) { //... } //... some other method foo(20); // which foo is called?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Removing 'http://' from link via REGEX What I would like to do is remove the "http://" part of these autogenerated links, below is an example of it. http://google.com/search?gc... Here are the regexes I am using in PHP to generate these links from a URL. $patterns_sp[5] = '~([\S]+)~'; $replaces_sp[5] = '<a href=\1 target="_blank">\1<br/>'; $patterns_sp[6] = '~(?<=\>)([\S]{1,25})[^\s]+~'; $replaces_sp[6] = '\1...</a><br/>'; When these patterns are run on a URL like this: http://www.google.com/search?gcx=c&ix=c1&sourceid=chrome&ie=UTF-8&q=regex the REGEX gives me: <a href="http://www.google.com/search?gcx=c&ix=c1&sourceid=chrome&ie=UTF-8&q=regex" target="_blank">http://google.com/search?gc...</a> Where I am stuck: There is no obvious reason why I cannot modify the fourth line of code to read like this: $patterns_sp[6] = '~(?<=\>http\:\/\/)([\S]{1,25})[^\s]+~'; However, the REGEX still seems to capture the "http://" part of the address, thus making a long list of these very redundant looking. What I am left with is the same thing as in the first example. A: Replace... $patterns_sp[5] = '~([\S]+)~'; ...with... $patterns_sp[5] = '~^(?:https?|ftp):([\S]+)~'; Then you can access the protocol-less version with $1 and the whole link with $0. Optionally, you can remove a leading protocol with something like... preg_replace('/^(?:https?|ftp):/', '', $str); A: I suggest not writing your own regex, instead have a look at http://php.net/manual/en/function.parse-url.php Retrieve the components of the URL, then compose a new version that only contains the parts you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DirectX multiple DLL versions? I see that DirectX 9 has multiple DLL versions, like * *d3d9.dll *d3d9_25.dll *d3d9_42.dll *d3d9_43.dll I'm wondering what the differences are, and how I can detect it? I have always been using GetModuleHandle("d3d9.dll");, but if an application has d3d9_43.dll, then my code will not detect that the application is using DirectX, will I? How would I go about detecting it without hardcoding all the DLL versions? A: If code uses D3D9, it will always use d3d9.dll at some point. Typically this is in the import table, but it can be dynamically linked (LoadLibrary). d3d9.dll provides the init code for D3D (and COM, when needed), and exports Direct3DCreate9 to create a new IDirect3D9Object. d3d9.dll is used regardless of version, the version is specified by passing D3D_SDK_VERSION to Direct3DCreate9 as the only parameter. This indicates what version should be used, not any DLL names. The numbered files most often seen are D3D X files. These are versioned, with _43 referring to the June 2010 SDK (each SDK release has one, I believe). If a program needs the helper functions provided in D3DX, the latest version from the SDK is typically linked against, with the numbers keeping them separate. The D3D9_[number] files which are not part of D3DX follow the same system (and likely have the same SDK version to number relation) and similarly provide version-specific features. This is not say d3d9.dll is not used; a vast supermajority of software uses that file (in fact, I've not personally seen a D3D9 app which didn't). Linking against D3D9.dll and passing the SDK version is the proper and recommended method for using D3D9. Testing for it is safe and reliable, and the simplest way to check the version is to intercept the call to Direct3DCreate9.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inserting a date/time value in Access using an OleDbParameter I'm trying to do an insert in oledb(ms access database) the field called objectdate is date/time the code i use to add the parameter is this, but i'm getting error. OleDbParameter objectdate = new OleDbParameter("@objectdate", OleDbType.DBDate); objectdate.Value = DateTime.Now; cmd.Parameters.Add(objectdate); the error: Data type mismatch in criteria expression. A: OleDB doesn't like milliseconds in the datetime parameters. If you remove the milliseconds it will go ok. See also: How to truncate milliseconds off of a .NET DateTime. A: You could use. OleDbParameter objectdate = new OleDbParameter("@objectdate", DbType.DateTime); objectdate.Value = DateTime.Now; cmd.Parameters.Add(objectdate); or use the Ole Automation version of the date. OleDbParameter objectdate = new OleDbParameter("@objectdate", DbType.DateTime); objectdate.Value = DateTime.Now.ToOADate(); cmd.Parameters.Add(objectdate); Or you could enter the datetime as a literal since the Datetime.ToString() removes the milliseconds that access can't work with. cmd.Parameters.AddWithValue("@objectdate", DateTime.Now.ToString()); this should work. A: The sentence: OleDbParameter objectdate = new OleDbParameter("@objectdate", DbType.DateTime); is not acepted in visual basic 2008, I use like this: ordeen.Parameters.Add(New OleDb.OleDbParameter("objectdate", DbType.DateTime)) ordeen.Parameters("objectdate").Value=object.text 'but its not run the next sentence only functional in sqlserver: cmd.Parameters.AddWithValue("@objectdate", DateTime.Now.ToString()); the problem in Access continued yet A: When using OleDb in .netstandard2.0 you can add using the .AddWithValue with just a key value pair. The type is inferred from the value object: cmd.Parameters.AddWithValue("@objectdate", DateTime.Now) Do not convert to string because that would destroy the ability to infer type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ASP.NET MVC: How do I display multiline text? View Model: public class Note { [DataType(DataType.MultilineText)] public string Text { get; set; } } Default editor template renders a <textarea> element with the newlines preserved. The default display template renders the text as a single string with the newlines removed. I tried this, but it doesn't work: ~/Views/Shared/EditorTemplates/MultilineText.cshtml @model string @Html.Raw(Model.Replace(System.Environment.NewLine, "<br />")) I can do something silly like @Html.Raw(Model.Replace("e", "<br />")) and it will work but of course I only want to replace the newline characters the <br /> element! I also tried using @"\n" and that didn't work either. Any ideas? Thanks! A: Try @Html.Raw(Model.Replace("\r\n", "<br />")) A: <pre>@myMultiLineString</pre> OR <span style="white-space:pre">@myMultiLineString</span> No need to do Html.Encode, as it's done by default A: The answer is that you'd do none of this. That's the job of your stylesheet. Basically, render the content any way you want, into a <p>, for example, and use CSS to control how white space is preserved. For example: (in your style tag, or in your CSS) p.poem { white-space:pre; } (in your HTML markup) <p class="poem"> There is a place where the sidewalk ends And before the street begins, And there the grass grows soft and white, And there the sun burns crimson bright, And there the moon-bird rests from his flight To cool in the peppermint wind. </p> A: You could try this: @Html.Raw("<pre>"+ Html.Encode(Model) + "</pre>"); This will preserve your content and show it as-is. A: i would recommend formatting the output with css instead of using consuming server side strings manipulation like .replace, just add this style property to render multiline texts : .multiline { white-space: pre-line; } then <div class="multiline"> my multiline text </div> newlines will render like br elements. A: [DataType(DataType.MultilineText)] public your_property {set; get;} and it will work if your using EditorFor()
{ "language": "en", "url": "https://stackoverflow.com/questions/7522925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to clean & optimise code generated by WCF OData service? I have an OData web service that is mostly OOTB in terms of how it accesses and returns data from the database. The problem we're seeing is that the code being generated is incredibly - and unnecessarily - complex and is causing huge delays when executing against the server. For example: SELECT [Extent1].[Id] AS [Id], N'ODATAModel.LatestFiguresView' AS [C1], N'EntityType,Name,RegistrationNumber,OfficeNumber,DateRegistered,...,Id' AS [C2], [Extent1].[EntityType] AS [EntityType], [Extent1].[Name] AS [Name], [Extent1].[RegistrationNumber] AS [RegistrationNumber], [Extent1].[OfficeNumber] AS [OfficeNumber], ... Loads of other columns ... , N'' AS [C12] FROM (SELECT [LatestFiguresView].[Id] AS [Id], [LatestFiguresView].[EntityType] AS [EntityType], [LatestFiguresView].[Name] AS [Name], [LatestFiguresView].[RegistrationNumber] AS [RegistrationNumber], [LatestFiguresView].[OfficeNumber] AS [OfficeNumber], ... Loads of those same columns ... FROM [dbo].[LatestFiguresView] AS [LatestFiguresView]) AS [Extent1] WHERE (N'Registered' = [Extent1].[RegistrationStatus]) AND ((1 = [Extent1].[Reservation]) OR (1 = (CASE WHEN ([Extent1].[Name] LIKE N'%White%') THEN cast(1 as bit) WHEN ( NOT ([Extent1].[Name] LIKE N'%White%')) THEN cast(0 as bit) END)) OR (1 = (CASE WHEN ([Extent1].[Sectors] LIKE '%Business%') THEN cast(1 as bit) WHEN ( NOT ([Extent1].[Sectors] LIKE '%Business%')) THEN cast(0 as bit) END)) OR ((1 = (CASE WHEN ... etc, etc ... END)))) As you can see, there are unnecessary nested selects and the WHERE clause contains loads of redundant checks on values (e.g. "CASE WHEN MyColumn LIKE '%Value%' THEN 1 WHEN NOT MyColumn LIKE '%Value%' THEN 0") Surely there's a way to tidy this mess up before it hits the database? A: When you select a large object graph from your database using Entity Framework you receive - as you're seeing - a huge swathe of data formed by joining a number of queried tables together. Then the 'magic' happens back in your application as this oversized result set is stripped and shredded back into entities. Every column that you've mapped will be selected from the database. This is only natural - you can't select half of an entity. If you're selecting the LatestFiguresView then every column in that View will be in your select statement - and if you're retrieving Products on an Order then every mapped column on Product & Order will be in the result set. Yes, Entity Framework always does SELECT [Column] FROM (SELECT [dbo].[Column] AS [Column]). I couldn't tell you why, but I'll guess that it either helps with code safety around some edge case where selecting directly from a table causes problems, or it allows the query generator to be more efficient. You're right that these are 'unnecessary' but I don't think they cost anything. I can run SELECT * FROM MyTable and SELECT * (SELECT * FROM MyTable) t in the same time. Finally, the WHERE and CASE statements are determined by your query - without seeing it, or the full WHERE clause, it's hard to comment (note: I don't really want to see your query, I'm sure it's not pretty). If you have if x or y or (a & b) then things will get messy. I don't normally worry about CASE statements as they are blindingly fast in SQL. I'd again assume that this is either a code-safety decision, or it allows for a more efficient (more generic?) query-generator. I'd suggest you run this in Query Analyser to benchmark it and identify any problems, and then write your own SQL and do the same. There are plenty of cases where it's more efficient to write Stored Procs than to have Entity Framework compile your queries, but I'd be surprised if selecting directly from a View with a number of conditions would be one of those cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting a radio button based on jquery autocomplete value I have a form that directors fill out when they add an event to my database. Since the particular type of event is likely to happen more than once, I am trying to make it as easy as possible for them. Using autocomplete, I get the text values to work just fine. Having problems with radio buttons. Example: there are 3 types of formats available - handicap, scratch, or both. Handicap is value 1, scratch is value 2 and both is value 3. I am able to add the correct value to the table when they first enter their event. How do I set the radio button that corresponds (format_1 for handicap, format_2 for scratch, format_3 for both) using autocomplete? $('#format').val(ui.item.f); will return the value from the table if I use text instead of radio button I tried to make a variable ( i.e. var f = $(".format").val();) which didn't work. What I was thinking about was something similar to setting a variable (f, for example), that would set a radio button (format_f = checked, for instance), but haven't been able to figure out how to mechanize it. Haven't been able to find any direction from my books or on the Internet. Can someone please point me in the right direction? A: You need to inject this into the select function of your autocomplete. It's possible your instantiation of autocomplete does not have one, as it's not necessary for default behaviour. Obviously you need to have the mapping of the autocomplete options and formats available, and you can have this sent back by whatever generates the autocomplete data. (It's not clear in your example whether your autocomplete is AJAX or local, but it doesn't matter.) Ultimately you want your autocomplete to have entries like this: [ { "id":"foo", "value":"bar", "f":"1" }, { "id":"baz", "value":"quux", "f":"2" } ] Then your select function at the end of your autocomplete will look like: select: function(event, ui) { if (ui.item) { $('#format').val(ui.item.f); } } I wrote a complete example in a similar question a few days back.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I capture this warning message when the query is blocking? When I do a query with isql I get the following message and the query blocks. The transaction log in database foo is almost full. Your transaction is being suspended until space is made available in the log. When I do the same from Python: cursor.execute(sql) The query blocks, but I would like see this message. I tried: Sybase.set_debug(sys.stderr) connection.debug = 1 I'm using: * *python-sybase-0.40pre1 *Adaptive Server Enterprise/15.5/EBF 18164 EDIT: The question is, "How do I capture this warning message in the python program?" A: Good question and I'm not sure I can completely answer it. Here are some ideas. Sybase.py uses logging. Make sure you are using it. To "bump" the logging out I would do this: import logging logging.basicConfig(level = logging.INFO, format = "%(asctime)s %(levelname)s [%(filename)s] (%(name)s) %(message)s", datefmt = "%H:%M:%S", stream = sys.stdout) log = logging.getLogger('sybase') log.setLevel(logging.DEBUG) And apparently (why is beyond me??) to get this working in Sybase.py you need to set a global DEBUG=True (see line 38) But then if we look at def execute we can see (as you point out) that it's blocking. We'll that sort of answers your question. You aren't going to get anything back as it's blocking it. So how do you fix this - write a non-blocking excute method;) There is some hints in examples/timeout.py. Apparently someone else has run up on this but hasn't really fixed it. I know this didn't probably help but I spent 15 minutes looking - I should at least tell you what I found.. You would think that execute would give you some result -- Wait what is the value of result in line 707?? while 1: status, result = self._cmd.ct_results() if status != CS_SUCCEED: break If status != CS_SUCCEED (which I'm assuming in your case is True) can you simply see what "result" is equal to? I wonder if they just failed raise the result as an exception? A: The reason is obvious, transaction log is full, you can check the blocikng queries in sybase MDA table monSysStatement .. here u can check sql statement which is taking high Io, time, number of row affecting etc. A: Your query may be large which is overflowing the transaction log (e.g. you are inserting large binary files). Or you may not be truncating your transaction logs often enough if that's an option. During runtime you will want to have an except statement that catches the exception Error. See the Sybase Python documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why is a non UI thread able to modify UI control in WinForm & TPL? I was testing a piece of TPL code I wrote below. The two ManagedThreadId's display different numbers. The new task therefore, I am assuming, is running on a non UI thread. My question is how is the task able to display a message and change a UI control? I am missing something. I thought I needed to get a reference to the UI's SynchronizationContext and use it to make UI changes from other threads. //var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString()); Task testTask = new Task(() => { MessageBox.Show( Thread.CurrentThread.ManagedThreadId.ToString()); lblTest.Text = "Test"; }); testTask.Start(); Addition: Download VS solution here Addition 2 Can someone test the solution and mention if they get an exception or not? A: This will not work unless you use the Control.CheckForIllegalCrossThreadCalls property to instruct the runtime not to validate that the calling thread matches the thread that the control was created on. Your test code does crash for me in a brand new WinForms project (InvalidOperationException: Cross-thread operation not valid: Control 'lblTest' accessed from a thread other than the thread it was created on). Is it possible that CheckForIllegalCrossThreadCalls(false) is being applied in your environment?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does this simple LINQ query syntax statement not translate to method syntax? Here's the query syntax version: DataGridViewRowCollection mydgvrs = new DataGridView().Rows; IEnumerable<DataGridViewRow> a = from DataGridViewRow row in mydgvrs where row.Height > 0 select row; which is fine, and the method syntax version: IEnumerable<DataGridViewRow> a2 = mydgvrs.Where(row => row.Height > 0); which the complier rejects - "no extension method Where ... could be found"? What's up? A: Because you have the type specified in the query syntax version. (The DataGridViewRow in from DataGridViewRow row). To translate this, you'll need a Cast<T>: IEnumerable<DataGridViewRow> a2 = mydgvrs.Cast<DataGridViewRow>() .Where(row => row.Height > 0); This is required since mydgvrs implements IEnumerable, but not IEnumerable<DataGridViewRow>.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getline() error. no instance of overloaded function matches argument list. Hi i am trying to use getline() function by giving two arguments to it. but it is giving error as no instance of overloaded function matches argument list. Here is my code snippet: string equation; cout<<"Enter the string"; getline(cin, equation); can anyone please tell me if i am missing something. Thanks. A: There is probably another function called getline which takes different arguments. To use the one you want, you have to #include <iostream> #include <string> and either use using namespace std; or explicitly put std:: before string, cout, cin and getline.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Pseudo-elements and images Can an image have pseudo-elements? In my testing I have not been able to use :before or :after with image elements, but I would love some more information. EDIT: W3C isn't clear either unfortunately: Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification. A: It wouldn't really make any sense. The :before and :after insert the extra content inside the matched element, and img doesn't have an inside.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to add the French language package and use it in Tinymce package? We are using Moxiecode.tinyMCE.dll in one of our project. This project is a ASP.net website using C#. We added one text area. All the controls are working as expected in English. Please let me know the steps to add another text area in the same page which must be able to take the French characters as input? How to change the language of the ribbon items to French using for this new text area?. I am having normal English keyboard. Can I make some programmatic changes so that I can type the French characters using my current keyboard? A: You will need to change the tinymce init/configuration for that second editor. There is a parameter called language. Make sure you got the correct language pack. You can get it here: http://www.tinymce.com/i18n/index.php?ctrl=lang&act=download&pr_id=1 If it is propperly installed set in your tinymce configuration language: 'fr', Keyboard settings can be changed via your system settings. You can even edit the language files to your needs. Language files are stored under tiny_mce/plugins/'plugin_name'/lang/'language_code'.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7522944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FB.getLoginStatus does not fires callback function I have a difficult problem. Difficult means I searched through the net and StackOverflow as well the whole FBJS SDK documentation and haven't find answer. I am building a Page Tab application where I'd like to let fans to rsvp events. So I have to check if the user is logged in and if it doesn't I have to login. That sounds pretty easy, but FB.getLoginStatus doesn't fires callback function. This is the code excerpt: FB.init({ appId: window.appID, status: true, xfbml: true, cookie: true, oauth: true, channelUrl: 'http://example.com/fb/channel.html' }); and then I simply - of course after the user clicks on a button - call FB.getLoginStatus, but it seems it doesn't do anything. I've already checked sandbox mode, FB.init success, URLs in application settings and developing environment. I can call FB.ui, although FB.ui with method: 'oauth' I get an error message saying " The "redirect_uri" parameter cannot be used in conjunction with the "next" parameter, which is deprecated.". Which is very weird because I didn't used "next" parameter. But when I set next to undefined, it works fine, I get the window, but it says "Given URL is not allowed by the Application configuration.". Expect from that, I can login, then I've got the access_token. But in the new window, getLoginStatus still doesn't do anything. So any advices are welcome. Thanks, Tamas UPDATE: function onBodyLoad() { //on body onload FB.init({ appId: window.appID, status: true, xfbml: true, cookie: true, oauth: true, channelUrl: 'http://example.com/fb/channel.html' }); } ... function getName() { // on button onclick FB.getLoginStatus(function(response){ if (response.authResponse) { window.loggedIn = true; debugString('Logged in'); } else { window.loggedIn=false; debugString('Not logged in'); } }, true); if (window.loggedIn === undefined) { debugString('getLoginStatus did not exec'); // I always get this message } } UPDATE 2: I created a new App on a different URL, which is configured as a standalone website. There these codes work perfectly, I can getLoginStatus, I can login, etc. Is there any difference working in the context of FB, and in a standalone website, using FB JavaScript SDK? A: I just had the same problem, though it only happened to some users. I finally found out that if your app is sandbox mode, none-developer users can still see your app as a pagetab. But calling getLoginStatus will fail silently (even logging turned on). Took a while to figure that one out, I hope this can save someone else some time. A: FB.getLoginStatus does not fire the callback when you are running the website on a different domain than the one that you registered the app with. I usually find myself in this situation when I am developing locally or on a staging server. For example, if you registered the site with example.com and your staging server is example.mystagingserver.com, the callback wont fire. In this case, you need to create a second application in Facebook and use the Application ID and Secret for the new app. A: I'm using this code, successfully. I'm not quite sure where the differences are.. but I'm using the ASYNC FB Loader. window.fbAsyncInit = function() { FB.init({ appId: 'XXXXXX', //change the appId to your appId status: true, cookie: true, xfbml: true, oauth: true}); function authEvent(response) { if (response.authResponse) { //user is already logged in and connected FB.api('/me', function(info) { login(response, info); }); } else { //user is not connected to your app or logged out button.onclick = function() { FB.login(function(response) { if (response.authResponse) { FB.api('/me', function(info) { login(response, info); }); } else { //user cancelled login or did not grant authorization } }, {scope:'email,rsvp_event,status_update,publish_stream,user_about_me'}); } } } // run once with current status and whenever the status changes FB.getLoginStatus(updateButton); FB.Event.subscribe('auth.statusChange', updateButton); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }()); function login(response, info){ if (response.authResponse) { accessToken = response.authResponse.accessToken; userid = info.id; userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name+"<br /> Your Access Token: " + accessToken; } } A: You can use the following code to check if the user is logged in: FB.getLoginStatus(function(response) { if (response.authResponse) { // logged in and connected user, someone you know } else { // no user session available, someone you dont know } }); From FB JS SDK Documentation. You can wrap the whole code in jQuery ready : $('document').ready(function(){ ... above code }) Also you may want to check this question StackOverflow. A: I had the same problem. I was working on the facebook login process of our website. During development the "FB.getLoginStatus" did not return a response. I fixed it in the settings of the app on facebook: -In facebook go to "manage apps" -Go to the "facebook login" settings of your app -Add your development url (for example "https://localhost") to the "Valid OAuth Redirect URIs" (Don't forget to remove the "https://localhost" from the OAuth Redirect URIs when you are finished with developping.) A: Something common that causes this is that a browser is blocking cookies, this will cause the event not to fire. Also, make sure that if you or your user have and ad blocker that it is not blocking third party cookies. Example of warning: A: For me after extensive testing can confirm the dialog to log the user will not show unless you use a valid Application ID These can be found in https://developers.facebook.com/apps/{{Application__Id}}/settings/ Just make sure you call the api with the correct ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Macro that accept new object In my code, I have: #define EV( event ) SendEvent( new event ); EV( evFormat ); But I want to pass a created object in the EV macro, like: CEvent *ev = new CEvent(); EV( ev ); Is this possible? Because there is no way I will modify the EV macro. A: #define EV( event ) SendEvent( new event ); // Can't be changed. The macro enforces that each call to SendEvent should create a new dynamic object. Your problem is not just that using a macro for that is stupid and e.g. reduces the readability of your source code. It is also that the macro does not allow you to create the object earlier than the call, and that you can't change the macro; in your words "there is no way I will modify the EV macro". The solution is therefore simple: Don't use the macro, use SendEvent directly, and remember to not delete. A: The way EV is currently written, it will generate a new object on each call. But that creation doesn't have to be of an object of the same type as what is ultimately passed to SendEvent. That's because the textual nature of preprocessor macros and more complex expressions adds some tricks. Consider this: class dummy { private: static dummy* freeme; public: dummy() { freeme = this; } static bool dofree() { delete freeme; return true; } }; dummy* dummy::freeme; CEvent *ev = new CEvent(this); EV( dummy && dummy::dofree() ? ev : NULL ); That will expand out so that the new you're running is not of a CEvent, but of a dummy class...which you then free, and then the whole expression evaluates to your event: SendEvent( new dummy && dummy::dofree() ? ev : NULL ); (Note: Using ?: is not as nice as the comma operator, so there's a wasted NULL branch here that never actually happens. The comma operator would be nice, but preprocessor macros treat commas specially and this is one of the cases where it can't be used. Making it thread-safe is left as an exercise for the reader.) To make it "cleaner" but still express it in terms of EV...without explicitly mentioning SendEvent at all, you could make your own macro: #define EV2(event) EV( dummy && dummy::dofree() ? event : NULL ) ...or you could just use SendEvent since it seems to do exactly what you want. But where's the fun in that? ;-P UPDATE: As @AlfPSteinbach points out, a more esoteric but lightweight way of turning your new into a no-op is with placement new: int dummy; CEvent *ev = new CEvent(this); EV( (&dummy) int ? ev : NULL ); So now you're expanding into: SendEvent( new (&dummy) int ? ev : NULL ); You're executing a new, but this time without needing to worry about freeing the result! Because I wasn't entirely sure if this was kosher esp. in threading cases, I made its own question: Is it well-defined/legal to placement-new multiple times at the same address? A: Totally doable without altering the macro. It's just risky. Note that you'll have to delete [] #include <memory> struct CEvent {}; void SendEvent(CEvent*) {} #define EV( event ) SendEvent( new event ); int main() { char *cev = new char[sizeof(CEvent)]; CEvent* ev = (CEvent*)cev; EV( (ev)CEvent ); ev->~CEvent(); delete [] cev; } http://ideone.com/ A: If there is no way you will modify the EV macro, then it isn't possible. Can't you create your own macro that does SendEvent( event ); instead? Update: Would it be a possibility to #undef the original macro, and provide your own definition of it? Assuming you only want the new behavior, you could do #undef EV #define EV( event ) SendEvent( event ); but now you will need to replace the original kind of call with EV( new event ). A: You might be leaking memory, unless SendEvent manages it from inside, something like void SendEvent(const Event *ev) { doSendEvent(ev); delete ev; } That aside, have you tried this, it should work EV(CEvent) If not, you could redefine operator new for the class CEvent so the above call would work. But your question is really unusual. Are you sure you there you are going down the right path ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7522949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flash 5.5 video player error: undefined property PLAYHEAD_UPDATE I'm getting this error: Access of possibly undefined property PLAYHEAD_UPDATE through a reference with static type Class in an AIR app of mine, ever since upgrading to 5.5 (from 5). There's an adobe forum thread that addresses this but no solution is offered (as per usual). Has anyone else encountered this and were you able to get around it? A: Well... I guess no one is going to chime in with thoughts, so, I'll just point to the forum thread that suggests an alternative (it doesn't actually say how to fix the bug, or that this is even deemed a bug), but I'm not sure that any better idea is going to come along.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery form validation questions? I am new to jQuery and javascript and I am used mainly to php. I am upgrading my site so it contains a little ajax to improve usability and to keep me busy! I am using this simple little script I threw together for the login page. All works well at the minute but I have a couple of questions I'd like to ask! $('#loginForm .submit').click(function(event) { $('.error').hide(); event.preventDefault(); var errors = 0; var loginEmail = $('#loginEmail').val(); var loginPassword = $('#loginPassword').val(); if (loginEmail.length == 0) { $('#loginEmail').after('<div class="error"></div>'); errors++; } if (loginPassword.length == 0) { $('#loginPassword').after('<div class="error"></div>'); errors++; } if (!errors) { $('.submit').submit(); } }); You will notice that the first line of code within the function is; $('.error').hide(); Now in php I would normally use; if (isset(........)) { Is there a simliar way to do this in javascript as when the user first activates the function there will be no html with the class .error? Also I am trying to add a new parameter to the function as well as the event parameter, how would I do this? I have tried the following? $('#loginForm .submit').click(function(event, var) { $('#loginForm .submit').click(function(event var) { $('#loginForm .submit').click(function('event', 'var') { And all seem not to work. Then again I am going by php, jQuery/javascript is not my strong point! Thanks A: Before performing an action, you can check if the function $() selected element by using the following syntax: if ($('.error').length) { // actions } A: If the .error - div exists in the DOM by default and is just hidden, you can't just check the length of $('.error'), because even if it's empty, length will return 1. You could do something like this: if($('.error').html().length !== 0){ //do something } This will check the containing string of the error-div, so if it's empty, length will return 0. Still I would recommend setting a boolean var. If errors occur, it gets set to false and you can check the var and you do not have to query for DOM-elements for such a simple task. To your second question, try something like this: $('#loginForm .submit').bind("click", {variable1: var}, handleSubmit); function handleSubmit(event){ var passedVar = event.data.variable1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7522952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: opencv face detection (real-time) on iPhone Camera Is there any suggestion where I can find some source codes or a place to start at ? Thanks A: You can try to follow this post Also I recommend this blog to start with OpenCV on iPhone
{ "language": "en", "url": "https://stackoverflow.com/questions/7522953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can we apply a non-vararg function over a va_list? Backstory I'm porting the QuickCheck unit test framework to C (see the working code at GitHub). The syntax will be: for_all(property, gen1, gen2, gen3 ...); Where property is a function to test, for example bool is_odd(int). gen1, gen2, etc. are functions that generate input values for property. Some generate integers, some generate chars, some generate strings, and so on. for_all will accept a function with arbitrary inputs (any number of arguments, any types of arguments). for_all will run the generators, creating test values to pass to the property function. For example, the property is_odd is a function with type bool f(int). for_all will use the generates to create 100 test cases. If the property returns false for any of them, for_all will print the offending test case values. Otherwise, for_all will print "SUCCESS". Thus for_all should use a va_list to access the generators. Once we call the generator functions, how do we pass them to the property function? Example If is_odd has the type bool f(int), how would we implement a function apply() that has this syntax: apply(is_odd, generated_values); Secondary Issue See SO. How can we intelligently print the arbitrary values of a failing test case? A test case may be a single integer, or two characters, or a string, or some combination of the above? We won't know ahead of time whether to use: * *printf("%d %d %d\n", some_int, some_int, some_int); *printf("%c\n" a_character); *printf("%s%s\n", a_string, a_struct_requiring_its_own_printf_function); A: The C language is a statically-typed language. It does not have the powers of runtime reflection that other languages do. It also does not provide ways to build arbitrary function calls from runtime-provided types. You need to have some way of knowing what the function signature of is_odd is and how many parameter it accepts and what the types of those parameters is. It doesn't even know when it has reached the end of the ... argument list; you need an explicit terminator. enum function_signature { returns_bool_accepts_int, returns_bool_accepts_float, returns_bool_accepts_int_int, }; typedef bool (*function_returning_bool_accepting_int)(int); typedef int (*function_generates_int)(); void for_all(function_signature signature, ...) { va_list ap; va_start(ap, signature); switch (function_signature) { case returns_bool_accepts_int: { function_returning_bool_accepting_int fn = va_arg(ap, function_returning_bool_accepting_int); function_generates_int generator; do { generator = va_arg(ap, function_generates_int); if (generator) fn(generator()); } while (generator); } break; ... etc ... } } Your problem is that QuickCheck was designed to take advantage of JavaScripts high dynamic programmability, something missing from C. Update If you allow arbitrary function signatures, then you need a way to make it static again, say, by making the caller provide the appropriate adapters. typedef void (*function_pointer)(); typedef bool (*function_applicator)(function_pointer, function_pointer); void for_all(function_applicator apply, ...) { va_list ap; va_start(ap, apply); function_pointer target = va_arg(ap, function_pointer); function_pointer generator; do { generator = va_arg(ap, function_pointer); if (generator) apply(target, generator); } while (generator); } // sample caller typedef bool (*function_returning_bool_accepting_int)(int); typedef int (*function_returning_int)(); bool apply_one_int(function_pointer target_, function_pointer generator_) { function_returning_bool_accepting_int target = (function_returning_bool_accepting_int)target_; function_returning_int generator = (function_returning_int)generator_; return target(generator()); } for_all(apply_one_int, is_odd, generated_values1, generated_values2, (function_pointer)0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7522954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why are modules explicitly named in files? From the D language reference: Modules have a one-to-one correspondence with source files. The module name is the file name with the path and extension stripped off. Module names are still specified in files explicitly, though. module foo; What's the point of this? If modules correspond to files, why can't the compiler infer what they're called from the file names? A: It can infer it. You don't have to give the module name. However, you can give the module name, which allows you to give it an entirely different name if you want to. A prime example of this is if the file name isn't a valid module name (e.g. my-module.d). In such a case, you can use the module declaration to give it a valid module name (e.g. my_module). It's common practice to put the module name at the top of the file, and usually the module name is the same as the file name, but making it possible to have the module name not exactly match the file name increases flexibility. Personally, I would generally consider it a bad idea to name the module anything other than the file name, and I'd argue that if the file isn't a valid module name, then the file name should be changed so that it is one, but apparently it was decided that the extra flexibility of making it possible for them not to match was worth having. So, it's in the language. A: same page a bit down (emph mine) The ModuleDeclaration sets the name of the module and what package it belongs to. If absent, the module name is taken to be the same name (stripped of path and extension) of the source file name. this means that if you want to put a module in a package you have to explicitly specify it is (like Java's package declaration) and given the strange propensity of people to use odd/foreign directory names you can't rely on checking for source/src/import in the path the reason that filename and module name don't have to be the same can be so you can use a .di for import and use several versions of the actual code using -c switch to create the .obj file for linking of the different versions (though fiddling with the import path is handier for that)
{ "language": "en", "url": "https://stackoverflow.com/questions/7522955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Strange character in fresh WAMP installation? I'm getting strange characters in my fresh local WAMP installation. I've just downloaded all .php files from ftp online and restored a backup on my local mysql server. The problem only happens when text contains symbols or special characters: PHP: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> MySQL collation: latin1_swedish_ci In this image of course there is a strange symbol "°" where "°" and "€" are needed. This has happened both in Opera and Firefox. Any idea? Thanks for helping, as always. A: I'll answer here because it's too long for a comment. You don't need to change your encoding, you should check your encoding. Keep in mind that encoding could be changed in a lot of different places: * *In your database with charset functions *In your apache configuration with AddDefaultCharset *With php header function *In your html with a <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> tag Any of these reasons could lead to wrong encoding displayed in the web browser. And if you do not specify it with one or more the previous methods, the corresponding layer will use its configured default. In your case since the text is coming from database and since often in WAMP/XAAMP/MAMP MySQL use a weird default encoding, I'd check for point one. Try to execute SET NAMES UTF-8 (or whatever encoding you use) query before retrieving data, just after your db connect function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple Jquery-UI Accordions on One Page I want to have multiple Jquery-UI accordions on the same page I assumed it would be as easy as changing the ID in the documentation to a class but only the first one shows up. //Default accordion $( ".accordion" ).accordion({ fillSpace: true, collapsible: true }); //Sortable accordion var stop = false; $( ".accordion-sort h3" ).click(function( event ) { if ( stop ) { event.stopImmediatePropagation(); event.preventDefault(); stop = false; } }); $( ".accordion-sort" ).accordion({ fillSpace: true, collapsible: true, header: "> div > h3", axis: "y", handle: "h3", stop: function() { stop = true; } }); <div class="accordion"> <h3><a href="#">First header</a></h3> <div>First content</div> <h3><a href="#">Second header</a></h3> <div>Second content</div> </div> <div class="accordion-sort"> <h3><a href="#">First header</a></h3> <div>First content</div> <h3><a href="#">Second header</a></h3> <div>Second content</div> </div> A: Change your second accordion() call to: $(".accordion-sort").accordion({ fillSpace: true, collapsible: true, header: "> div > h3" }); And it works for me. axis, handle, and stop are not valid configuration options. You may be thinking of draggable() (Tested with jQuery 1.6.4 and jQuery UI 1.8.16)
{ "language": "en", "url": "https://stackoverflow.com/questions/7522962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there another style for writing LIKE queries? I write some queries like this: SELECT * FROM Sample.dbo.Temp WHERE Name LIKE '%ab%' OR Name LIKE '%fg%' OR NAME LIKE '%asd%' OR ... OR ... OR Name LIKE '%kj%' Is there anyway I can rewrite this query like this: SELECT * FROM Sample.dbo.Temp WHERE Name LIKE ( '%ab%' OR '%fg%' OR '%asd%' OR ... OR ... OR '%kj%' ) Just looks more comfortable both from a readability point of view and manageability. If the column Name changes, I can always make one change instead of a hundred (or using Find and Replace). Any suggestions? A: No, you have to keep repeating the LIKE Although you could probably fool around a bit to make it work something like that, it won't be prettier or more readable. Perhaps you should generate the query programmatically instead of manually writing this? PS: perhaps a fulltext index is a better idea here? A: You can put the values in a table, perhaps a CTE, and semijoin to your table e.g. WITH params AS ( SELECT * FROM ( VALUES ('at'), ('fg'), ('asd'), ('kj') ) AS T (param) ) SELECT * FROM Sample.dbo.Temp T WHERE EXISTS ( SELECT * FROM params P WHERE T.Name LIKE '%' + P.param + '%' ); That looks long winded but if the CTE was instead a base table them the query could be data-driven i.e. if the list of parameter values need to change in the future then it would involve merely updating a table rather than amending hard-coded values (possibly in multiple objects).
{ "language": "en", "url": "https://stackoverflow.com/questions/7522964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to know when you finish receiving a TCP stream? I'm not sure how to tell in TCP when the sender finished sending me the information. For example if A needs to send 200 bytes to B, how will B know that A finished sending, and that the information is ready to be transferred to the application layer? There's the FIN flag, but as far as I know it's only there to symbolizes that your going to close the connection. Thanks. A: TCP has no obligation to tell the receiver when the sender has finished sending data on the connection. It can't because it has no understanding of the higher level protocol data it's transporting. However it will tell you if the connection closes (then you'll see a FIN, FIN-ACK) sequence in a network trace. From a programming perspective, assuming that you're using C the function recv will return 0 when the peer closes the connection. A: You define a protocol such as first sending a 4 byte int in a specified byte order which indicates how many bytes will follow in the message body. A: If you're on unix/linux, select and poll can signal you that the other end finished transfer (did a half/full close). read will also return with an error if you've read all the data and want to read from a closed connection. If you do multiple transfers on one connection and want to signal the end of a "package" you have to build that into your protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting HttpStatus from WCF Rest Client As i've mentioned in topic. I have WCF Rest Service, and ASP.NET MVC3 client. In ASP's controller i'm using IMyService serviceClient = new WebChannelFactory<IMyService>().CreateChannel(); to create client (channel) for my service. Is there any way to attach to this channel and get HttpStatusCode for each response from WebService? Btw should I close channel after each request-response? or it could be opened for next EndUser requests via ASP.NET MVC3 app? I'm setting HttpStatusCode in webService through WebOperationContext.Current.OutgoingResponse.StatusCode = <HttpStatusCode>; And i'd like to check it in MVC3 app and show proper hint. EDIT: Nevermind. I've found answers. http://msdn.microsoft.com/en-us/magazine/cc163302.aspx A: AnswerLink
{ "language": "en", "url": "https://stackoverflow.com/questions/7522970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP MVC 3.0 Complex View I am developing a application for Sales Order Management using ASP.NET MVC 3.0. I need to develop a page where Customer Details can be added. Customer Details Include public class Customer { public int ID { get; set; } public string Code { get; set; } public string Name { get; set; } public string Alias { get; set; } public int DefaultCreditPeriod { get; set; } public Accounts Accounts { get; set; } public IList<Address> Addresses { get; set; } public IList<Contact> Contacts { get; set; } } public class Accounts { public int ID { get; set; } public string VATNo { get; set; } public string CSTNo { get; set; } public string PANNo { get; set; } public string TANNo { get; set; } public string ECCNo { get; set; } public string ExciseNo { get; set; } public string ServiceTaxNo { get; set; } public bool IsServiceTaxApplicable { get; set; } public bool IsTDSDeductable { get; set; } public bool IsTCSApplicable { get; set; } } public class Address { public int ID { get; set; } public AddressType Type { get; set; } public string Line1 { get; set; } public string Line2 { get; set; } public string Line3 { get; set; } public string Line4 { get; set; } public string Country { get; set; } public string PostCode { get; set; } } public class Contact { public int ID { get; set; } public ContactType Type { get; set; } public string Name { get; set; } public string Title { get; set; } public string PhoneNumber { get; set; } public string Extension { get; set; } public string MobileNumber { get; set; } public string EmailId { get; set; } public string FaxNumber { get; set; } public string Website { get; set; } } Customer Requires a single page to fill all the customer details(General info, Account Info,Address Info and Contact Info). There will be multiple Addresses(Billing, Shipping, etc) and multiple Contacts (Sales, Purchase). I am new to MVC. How to Create the View for the above and Add multiple Address dynamically? A: I often create wrapper models to handle this kind of situation e.g. public class CustomerWrapperModel { public Customer Customer { get; set;} public Accounts Accounts { get; set;} public List<Address> AddressList { get; set} //Add public CustomerWrapperModel() { } //Add/Edit public CustomerWrapperModel(Customer customer, Accounts accounts, List<Address> addressList) { this.Customer = customer; this.Accounts = accounts; this.AddressList = addressList; } } then declare the View to be of type CustomerWrapperModel and use editors like so: @model MyNamespace.CustomerWrapperModel @Html.EditorFor(model => model.Customer) @Html.EditorFor(model => model.Accounts) @Html.EditorFor(model => model.AddressList) and have a controller to receive the post that looks like this: [HttpPost] public ActionResult(Customer customer, Accounts accounts, List<Address> addressList) { //Handle db stuff here } As far as adding addresses dynamically I found the best way to do this if you're using MVC validation and want to keep the list structured correctly with the right list indexes so that you can have the List parameter in your controller is to post the current Addresses to a helper controller like this: [HttpPost] public PartialResult AddAddress(List<Address> addressList) { addressList.Add(new Address); return PartialView(addressList); } then have a partial view that just renders out the address fields again: @model List<MyNamespace.Address> @{ //Hack to get validation on form fields ViewContext.FormContext = new FormContext(); } @Html.EditorForModel() make sure you address fields are all in one container and then you can just overwrite the existing ones with the returned data and your new address fields will be appended at the bottom. Once you have updated your container you can do something like this to rewire the validation: var data = $("form").serialize(); $.post("/Customer/AddAddress", data, function (data) { $("#address-container").html(data); $("form").removeData("validator"); $("form").removeData("unobtrusiveValidation"); $.validator.unobtrusive.parse("form"); }); NB. I know some people with have an issue with doing it this way as it requires a server side hit to add fields to a page that could easily just be added client side (I always used to do it all client side but tried it once with this method and have never gone back). The reason I do it this way is because it's the easiest way to keep the indexes on the list items correct especially if you have inserts as well as add and your objects have a lot of properties. Also, by using the partial view to render the data you can ensure that the validation is generated on the new fields for you out of the box instead of having to hand carve the validation for the newly added client side fields. The trade off is in most cases a minor amount of data being transferred during the ajax request. You may also choose to be more refined with the fields you send to the AddAddress controller, as you can see I just post the entire form to the controller and ignore everything but the Address fields, I am using fast servers and the additional (minor) overhead of the unwanted form fields is negligible compared to the time I could waste coding this type of functionality in a more bandwidth efficient manner. A: You pass your root model object to the View call in your controller like this: public ActionResult Index() { var customer = GetCustomer(); // returns a Customer return View(customer); } And then your view looks something like this: @model Customer <!DOCTYPE html> <!-- etc., etc. --> <h1>Customer @Model.Name</h1> <ul> @foreach (var address in Model.Addresses) { <li>@address.Line1</li> } </ul> One gets the picture. The code above depends on the @model directive, which is new in ASP.NET MVC 3 (see this blog post). A: Is a good question :D for normal navigation properties such as Accounts doing this is not to hard: @Html.EditorFor(model => model.Accounts.ID) @Html.EditorFor(model => model.Accounts.VATNo) will do something you want. But for collection navigation properties (Addresses and Contacts) you can't do this in one place by default. I suggest you use a different page for Addresses (and one for Contacts). Because it is the easiest way. But if you want to do this in one place (and also with out AJAX requests), you can create view by Customer, use scaffolding for model and it's simple navigation properties, and for lists (Addresses, Contacts) you must add them with JavaScript to the input fields (for example for each Address added, put it in an Array) and post fields to server. At server you can get main model and simple properties by default model-binder and for lists, you can 1) create your own model binder 2) parse them from inputted strings by yourself. Good lock
{ "language": "en", "url": "https://stackoverflow.com/questions/7522974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MAX not working as expected in Oracle I have an SQL query SELECT spt.paymenttype, MAX(nest.paytypetotal) total FROM sportpaymenttype spt INNER JOIN (SELECT spt.paymenttype, SUM(sod.detailunitprice * sod.detailquantity) paytypetotal FROM sportorderdetail sod INNER JOIN sportorder so ON so.orderid = sod.orderid INNER JOIN sportpaymenttype spt ON spt.paymenttype = so.paymenttype GROUP BY spt.paymenttype) nest ON nest.paymenttype = spt.paymenttype GROUP BY spt.paymenttype; I expect it to return one row (because of the MAX function) however, it returns 4 rows. I came up with a painful way to do it properly but I'm wondering, why the max function is behaving this way? Also, these are the results, where I only expect the first one PAYMENTTYPE TOTAL Loan 8640.95 Check 147.34 Credit Card 479.93 Cash 25.95 What I was wondering is if there was a better way to do this... SELECT spt.paymenttype, nest.paytypetotal total FROM sportpaymenttype spt INNER JOIN (SELECT spt.paymenttype, SUM(sod.detailunitprice * sod.detailquantity) paytypetotal FROM sportorderdetail sod INNER JOIN sportorder so ON so.orderid = sod.orderid INNER JOIN sportpaymenttype spt ON spt.paymenttype = so.paymenttype GROUP BY spt.paymenttype) nest ON nest.paymenttype = spt.paymenttype WHERE nest.paytypetotal = (SELECT MAX(nest.paytypetotal) FROM (SELECT spt.paymenttype, SUM(sod.detailunitprice * sod.detailquantity) paytypetotal FROM sportorderdetail sod INNER JOIN sportorder so ON so.orderid = sod.orderid INNER JOIN sportpaymenttype spt ON spt.paymenttype = so.paymenttype GROUP BY spt.paymenttype) nest); Thanks. A: It is behaving that way because you're telling Oracle to group by the paymenttype If you do a MAX(spt.paymenttype) and remove the GROUP BY than it will work as you want it. A: The MAX function is an aggregate. When you use a GROUP BY (in your case, the "GROUP BY spt.paymenttype" at the end), the aggregate applies to each group produced by the GROUP BY, not to the result set as a whole. You did get one result row per payment type, as GROUP BY is supposed to do in the absence of filters. To get one row, pick the single payment type you want, and add a HAVING spt.paymenttype = 'FOO' at the very end of the query. If you want the max value across all paytypetotal values, probably easiest (not necessarily best) to make this whole thing into a subquery and then select from it the largest payment value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Multiple user types - inheritence or composition? I have two "types" of Accounts in my site, with VERY different functionality, and a few different fields between them. These two types, however, share the same table of "basic account" fields. Is it better, in this case to utilize an inheritance design, where User and Company are simply children of Account, or is it better to use a composition design, where an Account can have either a "user" or a "company" (each with their own functionality) object in it? Note: the Account table contains the primary id that connects all the types together, and therefore is the way I will actually derive each user or company. ALSO I get that this is a fairly subjective question, but I know that there are common practices out there. It makes sense that there should be ideas on when it's right to do one and right to do another - therefore a right and wrong answer. A: If "User" and "Company" are kind of "Account" (like UserAccount and CompanyAccount), then use inheritance. If, on the other hand, User and Company are distinct entities that happen to have an Account, then use composition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mechanize and twitter How can I use mechanize and twitter? I used to send a twitter from su.pr but I would like to use mechanize to send it automatically for me! I know how to login but when I try to submit a post nothing happens I got this object: http://pastie.org/2576760 do you know if it is because the javascript or am I missing something?? please help me! A: See the twitter gem - the readme page contains everything you need, look for "Update your status". :) A: I wrote an example oauth/twitter script in ruby some time ago, perhaps it could help you: http://bitlong.org/articles/ruby_twitter
{ "language": "en", "url": "https://stackoverflow.com/questions/7522995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using jQuery to play/stop YouTube multiple iframe players I am trying to play/stop multiple YouTube iframe players on a single page. I can start the players automatically (i.e. through a custom method called loadYouTubeVideo(playerID)) upon clicking, but I am not sure how I can get access to the player objects again from another function call (i.e. through a custom method called unloadYouTubeVideo(playerID)) Here is the jsfiddle with what I am talking about: http://jsfiddle.net/iwasrobbed/9Dj8c/3/ So each player starts, but it continues to play even after the div containing it is hidden. By the way, I am using the iframe version of the player for a reason, so answers telling me to 'just use the flash object embed version' of the player are not acceptable for this question. Code here in case jsfiddle is not available: <html> <body> <script> $(document).ready(function(){ // YouTube Player API adapter $.getScript('http://www.youtube.com/player_api'); loadYouTubePlayer = function(playerID) { the_player = new YT.Player(playerID, { events: { 'onReady': playYouTubeVideo } }); }; unloadYouTubePlayer = function(playerID) { // This is the part that's broken $(playerID).stopVideo(); }; function playYouTubeVideo(event) { event.target.playVideo(); } $('.show_player').click(function() { var idType = 'data-video-id'; var id = $(this).attr(idType); $(this).fadeOut('fast', function() { $('.hidden_player['+idType+'='+id+']').fadeIn('fast', function() { loadYouTubePlayer('the_player'+id); $('.stop_player['+idType+'='+id+']').fadeIn('fast'); }); }); }); $('.stop_player').click(function() { var idType = 'data-video-id'; var id = $(this).attr(idType); $(this).fadeOut('fast', function() { $('.hidden_player['+idType+'='+id+']').fadeOut('fast', function() { unloadYouTubePlayer('the_player'+id); $('.show_player['+idType+'='+id+']').fadeIn('fast'); }); }); }); }); </script> <div class="hidden_player" data-video-id="0" style="display:none"> <iframe id="the_player0" width="640" height="360" frameborder="0" src="http://www.youtube.com/embed/2ktsHhz_n2A" type="text/html"></iframe> </div> <p><a href="#" class="show_player" data-video-id="0">Show video 0 and start playing automatically</a></p> <p><a href="#" class="stop_player" data-video-id="0" style="display:none">Stop video 0 from playing</a></p> <br/><br/> <div class="hidden_player" data-video-id="1" style="display:none"> <iframe id="the_player1" width="640" height="360" frameborder="0" src="http://www.youtube.com/embed/2ktsHhz_n2A" type="text/html"></iframe> </div> <p><a href="#" class="show_player" data-video-id="1">Show video 1 and start playing automatically</a></p> <p><a href="#" class="stop_player" data-video-id="1" style="display:none">Stop video 1 from playing</a></p> </body> </html> A: I have created a function which access framed YouTube videos through the ID of the parent of the iframe (as specified in the YT Frame API), and executes the functions defined at the JS API. See this answer for the code and a detailled Q&A section. My code would be implemented in this way: callPlayer(playerID, "stopVideo");
{ "language": "en", "url": "https://stackoverflow.com/questions/7522997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET UpdatePanel Timeout and 500 errors with custom errors I have a .net application that uses customerrors web.config module to display meaningful messages for errors. It works without any issues for 500 errors/exceptions caused by non-ajax and ajax components (updatepanel). However, in a scenario where updatepanel's asynchronous request times out, there is no error raised at all. I was able to see the timeout in firebug and come up with a solution that would at least display the error message as an alert and then redirect the user to the 500 error page using javascript but it's not quite doing what the rest of the application does in case of an unhandled errors like these. I basically just want everything to go through "LogEvent" mechanism so based on the severity of the error, it does the necessary work. Here are my questions: * *This 500 error page doesn't have anything in the Server.GetLastError() for these timeout scenarios. Is this an expected behaviour? *Can it be changed so I do have access to these timeouts in Server.GetLastError() OR maybe just run this error through "LogEvent" mechanism? *Is there a better/more graceful way to handle this issue? Below is my code to give you an idea, not exactly what I have in my application but pretty close. Web.Config <customErrors mode="On" defaultRedirect="~/Errors/ErrorUnknown.aspx" redirectMode="ResponseRewrite"> <error statusCode="500" redirect="~/Errors/Error500.aspx" /> </customErrors> Error500.aspx.vb Dim lastException As Exception = Server.GetLastError() If lastException IsNot Nothing Then LogEvent(LogLevel.Error, "UnHandled Error From 500 Error Page.", lastException) LblErrorMessage.Text = "Unknown error occured when processing your request." Session.Abandon() Page With UpdatePanel ASPX <asp:ScriptManager ID="AppScriptManager" AsyncPostBackTimeout="3" runat="server" AllowCustomErrorsRedirect="True" OnAsyncPostBackError="AppAsyncPostBackError" AsyncPostBackErrorMessage="There was an error processing your request!" /> Javascript on the Page with UpdatePanel ASPX <script type="text/javascript" language="javascript"> $(document).ready(function () { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler); }); function endRequestHandler(sender, args) { if (args.get_error() != undefined) { var errorMessage = "There was an error processing your request!"; errorMessage += '\nError message: ' + args.get_error().message; args.set_errorHandled(true); alert(errorMessage); window.location.replace('Errors/Error500.aspx'); } } </script> Page With UpdatePanel ASPX.VB Public Sub AppAsyncPostBackError(sender As Object, e As System.Web.UI.AsyncPostBackErrorEventArgs) Handles AppScriptManager.AsyncPostBackError LogEvent(LogLevel.Fatal, "Asyncpostback error from update panel.", e.Exception) End Sub Function to log events using NLog Private Sub LogEvent(level As LogLevel, logMessage As String, exception As Exception, ParamArray args() As Object) Try Dim appLogger As Logger = LogManager.GetCurrentClassLogger() If exception IsNot Nothing Then '# If it's an exception store it in a seperate file as fatal exception appLogger.LogException(level, String.Format(logMessage, args), exception) '# send an email SendErrorEmail(String.Format(logMessage, args), exception) '# Throw Exception as this was fatal If level = LogLevel.Fatal Then Throw Else '# Log the message appLogger.Log(level, logMessage, args) End If Catch ex As Exception End Try End Sub A: Yes, the server error 500 is something to do with the web server. Read this knowledge base from Microsoft: "How Web site administrators can troubleshoot an "HTTP 500 - Internal Server Error" error message on IIS 4.0 or on IIS 5.0" And please don't mess up with HTTP error messages. Error 500 is usually known when error happens at web server, not the application. Therefore, giving error 500 for your redirects is not recommended, it will confuse web administrator and also developers. This is the reason: "Description of Hypertext Transport Protocol error messages" Your best bet to handle this issue is having logging mechanism such as the one in Log4Net (log for .NET), or use logging in Microsoft's Enterprise Library 5.0. Before that, you can use custom error/exception pages but don't handle error 500.
{ "language": "en", "url": "https://stackoverflow.com/questions/7522998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jqgrid error Status: 'error'. Error code: 500 on add Ok, I know there are already questions on here about this but none are giving me an answer. I'm using jqgrid in MVC. In my View I have set up a jqgrid: jQuery(document).ready(function () { var invoiceId = @Model.Invoice.InvoiceId; jQuery("#list").jqGrid({ url: '/Invoice/InvoiceLineGridData/' + invoiceId, .... editurl: '/Invoice/SaveInvoiceLine/' + invoiceId, ... }); So my jqgrid is a list of invoiceLines that relate to an invoice. The edit works fine but when I try to do an add I get error Status: 'error'. Error code: 500. The method it's calling on the controller is like: public void SaveInvoiceLine(InvoiceLine invoiceLine, int id) { ... } So what's causing the error on the add is it's trying to assign a null to id. I don't want to make the id nullable because it never will (should) be. I've found the issue isn't with: var invoiceId = @Model.Invoice.InvoiceId; as I for an experiment changed to editurl: '/Invoice/SaveInvoiceLine/2', Even with this hardcoded on add I'm still getting the error with it coming through nullable. Any suggestions on how to fix this? A: This did it: http://blog.palelocust.com/?p=52
{ "language": "en", "url": "https://stackoverflow.com/questions/7522999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you read a specific line of a text file in Python? I'm having trouble reading an entire specific line of a text file using Python. I currently have this: load_profile = open('users/file.txt', "r") read_it = load_profile.readline(1) print read_it Of course this will just read one byte of the first line, which is not what I want. I also tried Google but didn't find anything. A: You can use Python's inbuilt module linecache import linecache line = linecache.getline(filepath,linenumber) A: load_profile.readline(1) specifically says to cap at 1 byte. it doesn't mean 1 line. Try read_it = load_profile.readline() A: What are the conditions of this line? Is it at a certain index? Does it contain a certain string? Does it match a regex? This code will match a single line from the file based on a string: load_profile = open('users/file.txt', "r") read_it = load_profile.read() myLine = "" for line in read_it.splitlines(): if line == "This is the line I am looking for": myLine = line break print myLine And this will give you the first line of the file (there are several other ways to do this as well): load_profile = open('users/file.txt', "r") read_it = load_profile.read().splitlines()[0] print read_it Or: load_profile = open('users/file.txt', "r") read_it = load_profile.readline() print read_it Check out Python File Objects Docs file.readline([size]) Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately. Note Unlike stdio‘s fgets(), the returned string contains null characters ('\0') if they occurred in the input. file.readlines([sizehint]) Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently. Edit: Answer to your comment Noah: load_profile = open('users/file.txt', "r") read_it = load_profile.read() myLines = [] for line in read_it.splitlines(): # if line.startswith("Start of line..."): # if line.endswith("...line End."): # if line.find("SUBSTRING") > -1: if line == "This is the line I am looking for": myLines.append(line) print myLines A: def readline_number_x(file,x): for index,line in enumerate(iter(file)): if index+1 == x: return line return None f = open('filename') x = 3 line_number_x = readline_number_x(f,x) #This will return the third line A: I managed to read an specific line by making a list out of the text, and asking what is the "n-th" element of the list. with open('filename') as xp: texto=xp.read() #This makes a string out of the text listexto=texto.splitlines() #This makes a list out of the string, making #every element of the list equal to each line #in the string. print(listexto[8]) #This prints the eight element of the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP: base64 image string to image reference How do I take an base64 string image and covert it to a image reference. The base64 string is sent via ajax. I'm not sure if image reference is the correct terminology so I'll provide an example. #original method $newImg = imagecreatefromjpeg($oImg); #new method $newImg = imagecreatefromjpeg($base64String); //THIS IS NOT CORRECT A: $data = base64_decode($base64String); $image = imagecreatefromstring($data); In this example, imagecreatefromstring() doesn't refer to an actual string of letters in the PHP sense, but rather a blob of data/bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++/CLI - URL Download to File I'm not entirely familiar with how CLI works, but I have a general idea. I have a function that takes 2 System::String variables, and uses those to download a file from a webpage. As far as the download goes, it works fine, and the file shows up in my directory with the necessary content. However, it gives me the error An unhandled exception of type 'System.AccessViolationException' occurred in ParseLinks.exe void downloadFile(System::String ^_URL, System::String ^_saveAs) { try { System::Net::WebClient ^webClient = gcnew System::Net::WebClient(); // Downloads the resource with the specified URI to a local file. webClient->DownloadFile(_URL, _saveAs); webClient->Dispose(); } catch (System::Exception ^_e) { // Error System::Console::WriteLine("Exception caught in process: {0}", _e); } } I did some digging and output testing, and found out that the exe is hitting a break point somewhere in the text file, as the entire webpage did not save to the txt file. Relevant code for that: if (myFile.is_open()) //if file open { while (!myFile.eof()) //before end of file { getline(myFile, ln); lines[count] = ln; count++; //count total lines to set loop length for later parsing //Error occurs somewhere in here } myFile.close(); } else cout<<"Error: Could not access file\n"; Brand New Error! :( An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in ParseLinks.exe The code after the file -> line array loop myFile.close(); //Close txt file //Loop through lines for (int i = 0; i < count; i++) { string temp = parseLinks(lines[i]); //parse links from each line The function for that: string parseLinks(string str) { const int len = str.length(); string link; bool quotes = false, islink = false; string compare[5] = {".htm",".html",".php",".asp",".pdf"}; //Parse all quoted text for (int i = 0; i != len; i++) { //Change bool if quote found if (str[i] == '"') { if (quotes == false) quotes = true; else quotes = false; } //If bool true, and char is not a quote, add to link string if (quotes == true && str[i] != '"') link += str[i]; } //Discard non-link text for (int i = 0; i < 5; i++) { //Link check for links given array of path filetypes if (link.compare((link.length() - compare[i].length()),compare[i].length(),compare[i]) == 0) islink = true; } //Link check for links with no path filetype (.html, .php, etc.) if (link.compare(0,7,"http://") == 0) islink = true; //If not a link, return empty string if (islink == false) link = ""; return link; } The error points to my large compare statement in this function. (Also, I'm clearly terrible at compressing my code) A: You're using getline wrong, and possibly that's causing your error. The correct idiom is this: std::string line; while (std::getline(myFile, line)) { // process `line` } There's no need to check myFile for openness separately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP multilanguage for front end I need to support about 20 languages (some are right to left). The database is all fine and we have that done properly but probem is the front end for the languages that are right to left. My dev team gave me a combo of these options: 1) Create seperate php view files for right to left and left to right 2) Create seperate CSS styles for right to left and left to right But i am not happy; I want to use only 1 view and CSS style set and be able to control these. Obiviously i need to change the text direction and also need to change the UI elements direction so flip the page for all page content/objects. How can this be achieved? I was reading on the two CSS properties: direction and unicode-bidi. Can the two alone achieve both needs of text direction and UI flip or do i absolutely have to use their option or some other way? Shoudn't make a diffrence but we are using codeignitor with hbase and mysql. A: Depends a bit on how you have built the page, I am not that familiar with arabic layouts but here are some thoughts: If you have made a proper html structure you should be able to flip the page with just a few css properties. In order to not having to maintain duplicate css documents I would recommend that you add a class to the body tag that indicates that it is a right to left design, and when that class is present new style rules are applied that adjust the page for a right to left direction layout. Made a small example: http://jsfiddle.net/PVhfR/ (uses a div with id #body instead of a real body element in the sample) A: For the structure, you should shape it using float: leftand float: right and margins; doing this, when you invert the directions in the right-to-left-CSS, the whole layout should flip. direction: rtl should be used for writing areas, like all the input elements, to flip the writing direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP How To Merge An Array Of Objects WIth An Array Of Arrays First, sorry for the lengthly explanation. I have two arrays in PHP. The first array is an array of objects. The second array is an array of arrays. Basically, I want to loop through, and merge the object with its matching array, and return a merged object. See the following print_r() of the array of objects structures: Array ( [0] => stdClass Object ( [gear] => helloworld [status] => running [started] => 40 Minutes Ago [start] => index.js [route] => 127.0.0.1:3000 [parameters] => Array ( ) ) [1] => stdClass Object ( [gear] => test [status] => stopped [started] => [start] => index.js [route] => [parameters] => Array ( ) ) [2] => stdClass Object ( [gear] => test2 [status] => stopped [started] => [start] => index.js [route] => [parameters] => Array ( [0] => first [1] => second [2] => third ) ) ) See the following print_r() of the array of arrays structures: Array ( [0] => Array ( [gear] => helloworld [machine_id] => E6z5ekvQ [created_by] => 10010 [modified_by] => 10010 [created] => 2011-09-22T16:30:11-07:00 [modified] => 2011-09-22T16:30:11-07:00 ) [1] => Array ( [gear] => test [machine_id] => E6z5ekvQ [created_by] => 10010 [modified_by] => 10010 [created] => 2011-09-22T16:44:25-07:00 [modified] => 2011-09-22T16:44:25-07:00 ) [2] => Array ( [gear] => test2 [machine_id] => E6z5ekvQ [created_by] => 10010 [modified_by] => 10010 [created] => 2011-09-22T16:45:43-07:00 [modified] => 2011-09-22T16:45:43-07:00 ) ) So basically the matching key for both is gear. So we should match the gear from the first object, with the second gear in the array, and return something like: stdClass Object ( [gear] => helloworld [status] => running [started] => 40 Minutes Ago [start] => index.js [route] => 127.0.0.1:3000 [parameters] => Array ( ) [machine_id] => E6z5ekvQ [created_by] => 10010 [modified_by] => 10010 [created] => 2011-09-22T16:30:11-07:00 [modified] => 2011-09-22T16:30:11-07:00 ) Notice, that the gear is merged into one property of the object, obviously gear does not appear twice. Ideas? A: If you could index the array by gear or some unique value, it would be a lot easier. $indexed = array(); // create an array using 'gear' as the index foreach($arrayValue as $value) { $indexed[$value['gear']] = $value; } // loop over each object foreach($objectArray as $obj) { $value = $indexed[$obj->gear]; // find the corresponding array foreach($value as $name => $val) { $obj->$name = $val; // assign each array index/value pair to the object } } If possible to get your code to return the array with the index by default, you can remove the first foreach loop. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: c string copy with strncpy I am really frustrated about strncpy function. I did something like this: char *md5S; //which has been assign with values, its length is 44 char final[32]; strncpy(final,md5S,32); but somehow the length of char final[] became more than 32 after. What should I do here? A: strncpy does not NUL-terminate the copied string if the source string is as long as or longer than n characters. If you have access to it, you can use strlcpy, which will NUL terminate for you. Do this instead: strncpy(dst, src, dstlen - 1); dst[dstlen - 1] = '\0'; OR strlcpy(dst, src, dstlen); where, for a char array, dstlen = sizeof(dst). A: If your output buffer isn't large enough to copy all of the source string and its trailing NUL then the output string will not be NUL terminated. In your case, the MD5 is 33 bytes including the NUL, so the NUL isn't copied. When you read the string back you're reading past the end of your buffer. Make final 33 bytes long, and ALWAYS add a NUL to the last character in the destination when using strncpy. int n = 32; char *src = "some really really long, more than 32 chars, string." char dst[n+1]; strncpy(dst, src, n); dst[n] = '\0'; A: You forgot to leave room for the null character char final[33]; strncpy(final,md5S,32); final[32] = '\0';
{ "language": "en", "url": "https://stackoverflow.com/questions/7523022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: NET1.1 Conditional Compilation I hope this is a very easy one to solve. I have a crypto library that will be used for NET1.1 apps and higher. The X509Certificate class is in NET1.1 and X509Certificate2 is in NET2.0 and above. I want to do something like: #if NET1.1 public void LoadKeys(X509Certificate cert) { .... } #else public void LoadKeys(X509Certificate2 cert) { .... } #endif What I'm missing is the compiler symbol! I found that NET20, NET30 and NET40 exist. However I want to do "if NET1.1, do this; otherwise, go with the advanced model". Also, bonus question :), do I have to compile in NET1.1 and NET2.0 separately for this to work as intended? Or can I compile the DLL in NET1.1 and then put in a machine with only NET2.0, and hopefully the ILM will go to the new framework? Thanks A: Your code already does what you want - if there's no "NET1.1" symbol defined, it will use the second piece of code. And yes, you have to compile separately for 1.1 and 2.0 for this to work, because you'll end up with different results - one will end up with only the first overload; one will end up with only the second overload. You probably could run the 1.1 code in 2.0 and higher - that's the normal case - but as you can't have a single build which contains both versions of the method and is 1.1-compatible, you might as well use two builds. One option is for both methods to appear in the .NET 2+ build though, to retain backward compatibility for apps originally built against the 1.1 build which want to migrate: public void LoadKeys(X509Certificate cert) { .... } #if !NET1.1 public void LoadKeys(X509Certificate2 cert) { .... } #endif EDIT: Just to clarify a few points from the discussion with Artur in comments: * *Artur's blanket statement that you can't use a .NET 1.1 in a .NET 4 application is definitely wrong. I've just done so with the .NET 1.1 build of NUnit (which was the simplest .NET 1.1 library I had to hand) *If you're relying on Code-Access Security then there have been changes there between framework versions; you'd have to look at the details of what you're doing to see whether the differences are significant *You can't build a .NET 2 assembly and run it in .NET 1.1 due to binary format changes - it's only the other way round that works. *While it's possible that you're relying on a call in .NET 1.1 which has been removed from a later version of .NET, that's a pretty rare case, and should be reasonably easy to determine. In general Microsoft tries to maintain backward compatibility pretty well. You might also want to read the .NET 4 Migration Guide. Finally, I'd point out that .NET 1.1 is really old now - if you know you need to support it, then that's fair enough, but personally I'd try to get clients to upgrade if at all possible :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JRadioButton that looks like JButton I'm trying to create a feature similar to that of Geogebra's toolbar: it has buttons that select tools, so only one can be selected at a time, but they don't look like radio buttons (a dot, with an inner dot if it's selected); they look like JButtons with an ImageIcon. I've gone through some of the source (specifically ModeToggleMenu.java and Toolbar.java) but still can't quite figure out what's happening. I just need something basic. I would really appreaciate help! Screenshot of what I mean: Note the pointer, point, line, perpendicular line, triangle, etc.. That's the effect I'm trying to achieve. Thanks very much! A: I think the little thing that you missed is that the Geogebra code you linked to uses this as the button class: class MyJToggleButton extends JToggleButton So the buttons are JToggleButtons not JRadioButtons. JToggleButtons can be used directly and put into button groups just like radio buttons. Geogebra's code does custom painting, but you can just set an icon as well. A: Create custom icons then use: radioButton.setIcon(...); radioBbutton.setSelectedIcon(...);
{ "language": "en", "url": "https://stackoverflow.com/questions/7523028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Model architecture without ORM or Framework for API Let me first say that I realize this question is vague and does not have a single answer. Nonetheless, I would greatly appreciate the insight of the StackOverflow community. To the purpose of this site, an answer will be chosen based on adherence to the specification and its address of roadblocks. Overview I am starting a project that will largely be a RESTful API, currently with about a half dozen models. However, their will also be a website. The goal is loosely to follow an MVC architecture so that the site and API utilize the same codebase. My plan is to heavily utilize Models, and light (or not at all) on Controllers. The views will vary between JSON (API) and HTML (website). Specification * *No ORM. I'm married to MySQL + PHP at the moment. While this may change later, I'm comfortable committing to the two and therefore don't need an ORM. *Balanced Abstraction. I do believe in Fat Models. However, per the above, I don't need queries written for me. Nonetheless, I still want to encapsulate the model properties. *Speed. As the site will largely utilize the API, speed is a cornerstone. With respect, I'd rather avoid the weight of a full-stack framework. Roadblocks * *If models are custom classes, what would be the best way to load multiple. I'd prefer to lazy load, but not at the expense of performance. Without pre-optimizing, what would be a clean approach for loading multiple models without the a half dozed require() statements at the top of every page. *Balancing abstraction, I don't want to create getX() methods in each Model for every possible query. Yet, I would like to avoid writing queries in my views. So how can I cleanly balance this between abstraction and still respect MVC paradigm? If something exists that focuses on Model abstraction, which it probably does, please point me in that direction. However, I am familiar with CakePHP, Frapi, Code Ignitor and have read up on Doctrine. I believe these don't meet the specification. A: Check out Eric Evans' Domain-Driven Design, or the free online redux Domain-Driven Design Quickly. Specification * *You don't need to use an ORM if you don't want to. Or you can use an ORM sometimes, or custom SQL other times as needed. Whatever code you write within those methods to query a database is an implementation detail and should be abstracted by the public-facing interface of the Model class. *You should write Model methods to encapsulate logical operations pertaining to your application. That is, your classes and methods are based on higher-level business requirements, not as low-level CRUD operations. *There's no need to have a Framework with a capital F to utilize Models. Check out the Page Controller pattern, which IMHO fits the PHP convention better than the Front Controller pattern that is so common among frameworks. Roadblocks * *Regarding lazy-loading, try the autoloading feature of PHP. *Avoid tedious getters and setters by designing your Model classes to higher-level interfaces, according to business goals, not low-level CRUD. A Model method could return a PHP hash array of other Model object instances. For simple object fields, you could simply make object member variables public.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails calling User record from Friends model I've built a simple Friend model, which allows Users to have multiple friends. Here's what that looks like: class Friend < ActiveRecord::Base belongs_to :user class User < ActiveRecord::Base has_many :friends Each friend record just has an id, user_id and friend_id. The user_id is the id of the user it belongs to and the friend_id is the id of user they are befriending. Here's my problem I'm not quite sure how to display a list of a particular user's friends. @user.friends will give me a list of all the friend records they have, but not the user accounts of those friends. For instance, I am trying to build a show page for the friends controller: class FriendsController < ApplicationController def show @user = current_user end SHOW.HTML.ERB <% if @user.friends.count > 0 %> <% @user.friends.each do |friend| %> <div class="entry"> <%= friend.username %> This does not work because friend in this case does not have username. I need to do something like this in my controller: @friend = User.find_by_id(friend.friend_id) But I'm not sure how I would call that in my view in the @user.friends loop. Any thoughts appreciated. Let me know if I need to be more clear. UPDATE I've updated my User model like so: has_many :friends, :include => :user has_many :friended_users, :through => :friends, :source => :user, :uniq => true However, when I run @user.friended_users it's giving me the user_ids (which is the same as @user) rather than friend_ids. How can I tweak that relationship so it's linking to the friend_id rather than user_id? The more I think about it, I think I may not have set up the relationship properly in the first place. Maybe a User should has_many :users, through => 'friends', but that doesn't really make sense... UPDATE I've updated my models based on @twooface's input: class User < ActiveRecord::Base has_many :friendships has_many :friends, :through => :friendships class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => 'User' class Friend < ActiveRecord::Base has_many :friendships has_many :users I'm just not sure what my Friends table should look like. I assume it should have a primary key and a user_id? If I create a friendship and friend record, I can do friendship.user and friendship.friend and get the correct results, but user.friends gives me an empty hash... A: I think your relations are built a bit wrong. Try something like this: class User < ActiveRecord::Base has_many :friends has_many :friendships has_many :friends, :through => :friendships class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => 'User' # This class has :user_id and :friend_id Then everything will be simpler. Every user will have an array of friends that will be just users. User.first.friends Will return an array of Users that this User friends. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mySQL query to search all tables within a database for a string? Is there a mySQL query to search all tables within a database? If not can you search all tables within a database from the mySQL workbench GUI? From phpmyadmin there's a search panel you can use to select all tables to search through. I find this super effective since magento, the ecommerce package I'm working with has hundreds of tables and different product details are in different tables. A: Alternatively, if your database is not that huge, you can make a dump and make your search in the .sql generated file. A: If you want to do it purely in MySQL, without the help of any programming language, you could use this: ## Table for storing resultant output CREATE TABLE `temp_details` ( `t_schema` varchar(45) NOT NULL, `t_table` varchar(45) NOT NULL, `t_field` varchar(45) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; ## Procedure for search in all fields of all databases DELIMITER $$ #Script to loop through all tables using Information_Schema DROP PROCEDURE IF EXISTS get_table $$ CREATE PROCEDURE get_table(in_search varchar(50)) READS SQL DATA BEGIN DECLARE trunc_cmd VARCHAR(50); DECLARE search_string VARCHAR(250); DECLARE db,tbl,clmn CHAR(50); DECLARE done INT DEFAULT 0; DECLARE COUNTER INT; DECLARE table_cur CURSOR FOR SELECT concat('SELECT COUNT(*) INTO @CNT_VALUE FROM `',table_schema,'`.`',table_name,'` WHERE `', column_name,'` REGEXP ''',in_search,''';') ,table_schema,table_name,column_name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA NOT IN ('information_schema','test','mysql'); DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; #Truncating table for refill the data for new search. PREPARE trunc_cmd FROM "TRUNCATE TABLE temp_details;"; EXECUTE trunc_cmd ; OPEN table_cur; table_loop:LOOP FETCH table_cur INTO search_string,db,tbl,clmn; #Executing the search SET @search_string = search_string; SELECT search_string; PREPARE search_string FROM @search_string; EXECUTE search_string; SET COUNTER = @CNT_VALUE; SELECT COUNTER; IF COUNTER>0 THEN # Inserting required results from search to table INSERT INTO temp_details VALUES(db,tbl,clmn); END IF; IF done=1 THEN LEAVE table_loop; END IF; END LOOP; CLOSE table_cur; #Finally Show Results SELECT * FROM temp_details; END $$ DELIMITER ; Source: http://forge.mysql.com/tools/tool.php?id=232 A: If you are using MySQL Workbench, you can do this by doing right click on the DB Schema you want to search into, and then "Search Table Data...". In there you can select the "Search using REXEXP" option, and then type your text of search as usual. It will provide the DB rows matching your specific text. You will need to check the "Search columns of all types" box as well. A: In MySQL Workbench you can use the Table Data Search feature. It can search across multiple tables and/or multiple databases. A: Search string in all tables on a database is a complex task. Normally you don't need to use exactly all tables and results are complex to read without a specific layout (tree of tables with matches or the like) SQL Workbench/J offers a GUI and a command-line version to do such task: More info: * *http://www.sql-workbench.net/manual/wb-commands.html#command-search-data *http://www.sql-workbench.net/manual/dbexplorer.html#search-table-data NOTE: Search with JDBC driver uses a lot of memory if it is not configured properly. SQL Workbench/J warns about that and although online documentation is a bit outdated, the sources of documentation (doc/xml/db-problems.xml) explain how to fix it for different BBDD: Here an extract for Postgres: The PostgreSQL JDBC driver defaults to buffer the results obtained from the database in memory before returning them to the application. This means that when retrieving data, &wb-productname; uses (for a short amount of time) twice as much memory as really needed. This also means that WbExport or WbCopy will effectively read the entire result into memory before writing it into the output file. For large exports, this is usually not wanted. This behavior of the driver can be changed so that the driver uses cursor based retrieval. To do this, the connection profile must disable the "Autocommit" option and must define a default fetch size that is greater than zero. A recommended value is e.g. 10, it might be that higher numbers give a better performance. The number defined for the fetch size, defines the number of rows the driver keeps in its internal buffer before requesting more rows from the backend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: i don't want to use std::copy...his this the right for-loop alternative? i'm trying to not use STL. i have this line in my code: std::copy(buffer_, buffer_ + size_ + 1, new_buffer) if i want to NOT use copy, is this the right equivalent? for (int i = 0; i < (size_ + 1); i++){ new_buffer[i] = buffer[i]; } or is that totally wrong? or is it off by one? or something else? thanks! A: Okay, the two code-samples you have will give the same result. However, you will have an off-by-one error if you use size_ + 1. Just size_ is the correct value since it already points to one past the last element. A: It's not clear whether what you wrote works. The copy version works if buffer_ is any random-access and new_buffer is any output iterator. Your manual version only works if buffer_ is a pointer. Other than that, your manual version is functionally equivalent. If the types are POD, though, you could probably do better with memcpy (subject to checking for overlaps). Note that your buffer, the way you wrote it, has size size_ + 1. A: This is how I would do it, since it's easier to reuse with general iterators (much like std::copy), because the code that is specific to the iterator type (random access) is outside of the loop: buffer_type* begin = buffer; // EDIT: buffer_type is whatever type buffer contains. buffer_type* end = buffer + size + 1; // EDIT: usually this would be 'buffer + size' buffer_type* out = new_buffer; // EDIT: don't want to lose the pointer to new_buffer! while(buffer != end) { *out = *begin ++begin; ++new_buffer; } So you wouldn't have to change the loop if you decided to use some other type of iterator. Some code checking utilities might complain about this because they think you are going to incur an access violation, but that's not the case since the last dereference happens before the last incrementing. The choice of size for a variable name is kind of confusing here, BTW. It implies that buffer + size would be one past the end of buffer, since you start labeling elements of an array at zero, but you start counting them at one, so the last element will be at index size - 1 typically. Also, if you are going to use a for loop and the indexing operator you should use an unsigned int to index. Negative indices are legal, but I don't think you intend to allow them here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android - How do I make buttons clickable when new layouts loads I'm trying to make buttons clickable when the new layouts loads... As what happens... I'm on the layout 1 and i have a few buttons shown... When I press a button it will straight away show me a new layout with buttons from another .xml. But it won't let me click anything on layout 2. How do i make it happen? My code is below to go from layout 1 to layout R.layout.fail. Button SectiontwoButton = (Button) findViewById(R.id.Sectiontwo); SectiontwoButton.setOnClickListener(new OnClickListener() { private Uri Uri; @Override public void onClick(View v) { setContentView(R.layout.fail); Uri uri=Uri; Intent i=new Intent(Intent.ACTION_VIEW, uri); mSoundManager.playSound(1); } }); Thanks Wahid A: You can put both your layouts as child of a viewflipper. And instead calling setContentView again, you can use viewflipper.setDisplayChild(0); This is the cleaner way of switching between layouts. This should also solve your click problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access @attributes data in SimpleXMLElement in PHP Just wanted to start by saying I have read a LOT of the questions on this site about this exact problem, but I'm still struggling to apply it to my scenario. If someone could help me out, that'd be great! :) I am trying to extract data from the following XML: $myXML = '<?xml version="1.0" encoding="UTF-8"?> <products><product uri="https://192.168.110.201:9630/api/products/1807/" id="1807" resource_type="current"><code>DEMO - MC700X/A</code><flags><inventoried>true</inventoried><editable_sell>false</editable_sell><master_model>false</master_model></flags><sell_price>0.00</sell_price><description>Apple MC700X/A Demo</description><inventory><available>7</available><reserved>0</reserved><coming_for_stock>2.0</coming_for_stock><coming_for_customer>0.0</coming_for_customer><warehouses>0</warehouses><total>7</total></inventory><product_photos/></product></products>'; I am using SimpleXML to put it into a PHP variable (object?) like this: $xml = new SimpleXMLElement($myXML); If I do a: echo '<pre>'; print_r($xml); echo '</pre>'; I get the following returned: SimpleXMLElement Object ( [product] => SimpleXMLElement Object ( [@attributes] => Array ( [uri] => https://192.168.110.201:9630/api/products/1807/ [id] => 1807 [resource_type] => current ) [code] => DEMO - MC700X/A [flags] => SimpleXMLElement Object ( [inventoried] => true [editable_sell] => false [master_model] => false ) [sell_price] => 0.00 [description] => Apple MC700X/A Demo [inventory] => SimpleXMLElement Object ( [available] => 7 [reserved] => 0 [coming_for_stock] => 2.0 [coming_for_customer] => 0.0 [warehouses] => 0 [total] => 7 ) [product_photos] => SimpleXMLElement Object ( ) ) ) Now, when I try to access that data programatically, the following works fine: // This returns the value as expected echo '<pre>'; echo($xml->product->code); echo '<br>'; echo($xml->product->sell_price); echo '<br>'; echo($xml->product->inventory->available); echo '<br>'; echo '</pre>'; This returns: DEMO - MC700X/A 0.00 7 But I need to be able to access the "id" tag in the base "product" element (i.e. the @attributes bit), but can't work it out. I've been reading a lot, and figured that I should be able to use the attributes() method, but I can't work it out exactly. Trying this didn't work: echo '<pre>'; echo($xml->attributes()); echo '<br>'; echo '</pre>'; It just returns nothing. Can someone please help me? I want to be able to display the "id" tag.. i.e. what I would expect to be: echo $xml['product']['@attributes']['id']; obviously doesn't work either. Thanks!! John A: Did you try: echo (string)$xml->product->attributes()->id; That should give you access to the attributes. If you have more than 1 product, it may be echo (string)$xml->product[0]->attributes()->id; You can also access the attributes using regular array notation such as: $xml->product['id']; // instead of $xml->product->attributes()->id See Example #5 from the SimpleXML Examples as well as the manual page on SimpleXMLElement::attributes() for more information. A: $array = (array)$obj; $prop_id = $array['@attributes'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7523044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: CSS how to style a parent item when a textarea is in focus? I have the following <div class="comment-wrap"> <textarea></textarea> </div> Whenever the textarea is in focus, I want to style the comment-wrap div. I've tried: #hallPost-inner + textarea:focus { background: red; } This does not work. Any ideas on how I can style the comment-wrap div whenever the textarea is in focus, meaning the cursor is blinking in the textarea and the user can type? Thanks A: Not sure what #hallPost-inner is, but in general CSS selectors cannot ascend, meaning you would need to have the textarea:focus selector, but then would need to style an ancestor element, which cannot be done in css. Here's a good resource, among many others. The link shows how an easy javascript solution can be achieved as well. A: With JavaScript and jQuery, you could do: $("textarea").live("focus", function(e) { $(this).closest(".comment-wrap").css({ "background": "red" }); }); A: Use the pseudo selector :focus-within. Note that any child in focus will effect the parent. If you have more children and just wanna apply when the event hits the <textarea>, you will need JS. Link for more details. (css-tricks) Ex.: form{ padding: 20px; background-color: gainsboro } input{ text-align: center } form:focus-within { background-color: yellow } <form> <input type="text" placeholder="name"> <input type="text" placeholder="lastname"> <input type="button" value="Go!"> </form> Note: not all browsers support :focus-within
{ "language": "en", "url": "https://stackoverflow.com/questions/7523047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't get ApacheDS to load the example data file In ApacheDS, I'm trying to load the sample LDAP data provided in ldif format and with instructions here. I followed the same pattern I used to load the context record by specifying an ldif file in server.xml for the partition (directions, albiet lousy ones, located here). So I have... <apacheDS id="apacheDS"> <ldapServer>#ldapServer</ldapServer> <ldifDirectory>sevenSeasRoot.ldif</ldifDirectory> <ldifDirectory>apache_ds_tutorial.ldif</ldifDirectory> </apacheDS> The sevenSeasRoot.ldif file seems to have loaded properly, because I can see an entry for it in LdapBrowser. But there are no records under it. What am I doing wrong? How do I configure server.xml to load the child records for sevenSeas? A: Just a quick note, the config says ldif*Directory* but you are passing a file. OTOH, I guess you are using 1.5.7 this is very old, it would be better to try the latest version for better support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove Oldest File in Repository I've got a git repo, and I have revisions of a file, dated with a unix timestamp. I want to get the oldest file (I.E. the one with the smallest timestamp) and remove it. Is this possible with Bash alone and if so, how? A: If you want to find the oldest file in a directory tree, you can do something like this: ls -tr $(find . -type f) | head -1 This works as long as the number of files isn't too large. It's even easier if you're willing to delete "all files older than a certain number of days". For example, if you want to get rid of anything older than 5 days: find . -type f -mtime +5 -print | xargs rm You wouldn't want to run this verbatim; you'd want to provide the appropriate filters to find -- or root it at the approriate directory -- so that you're only deleting files you really want to delete. Obviously you'll need to commit these deletes to git as well. You could do something like this: find . -type f -mtime +5 -print | xargs git rm git commit -m "deleted things" ...although note that this could commit changes that you've previously staged with "git add". Some things are best done by hand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I setup assets in Rails 3.1 to be able to show images that're created on fly? I've Rails 3.1 application which generates some images in 'public/scene/ticket_123/*.png' on fly. It works normally in development mode, but in production all assets should be precompiled. So I can't use files that I've generated after application started. Setting config.assets.compile = true hasn't solve my problem. Situation is only worse since ticket number changes - so images are in different directories which are continiously created on fly too. How should I setup assets to be able to show images that're created after an application was started? A: I had the same problem. I only found a work around by copying all my images into "public/images" and changed all the links to the new path. That worked for me for the moment. I wait until somebody comes up with a better idea. I hope that helps. A: If found solution. # In view I wrote <img src=<%= mycontroller_image_get_path :filename=>file_name %> > # In controller I created GET action def image_get send_file params[:filename], :disposition => 'inline', :type => 'image/png' end But you should care that file you're trying to send is in "#{Rails.root}/public" directory otherwise send_file says it can't found the file. (May be it is not necessary in /public but in Rails.root anyway). To change this behavior it can be useful to read this topic Can I use send_file to send a file on a drive other than the Rails.root drive?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can it be determined if one integer is divisble by another? So for this problem the question asks a number x is divisible by y if the remainder after the division is zero. Write a program that tests whether one number is divisible by another number. read both numbers from the keyboard. This is what I have so far import java.util.Scanner; public class ch3ProblemOne { public static void main(String[] args) { int x; int y; Scanner keyboard = new Scanner(System.in); x = keyboard.nextInt(); y = keyboard.nextInt(); if (x == 5); else if (y <= 0); System.out.println(x + "is not divisible by" + y); else if (x == y); System.out.println(x + "is divisible by" + y); A: you need to use the modulus operator, which tells what the remainder is. so 10 % 2 == 0 10 % 7 == 3 Use % on your variables. A: Use the modulo operator, which returns the remainder from a division operation. public class ch3ProblemOne { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int x = keyboard.nextInt(); int y = keyboard.nextInt(); if ((x % y) == 0) { System.out.println(x + " is divisible by " + y); } else { System.out.println(x + " is not divisible by " + y); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What is the big-O of the function (log n)^k What is the big-O complexity of the function (log n)k for any k? A: It will still be (log(n))^2. A logarithm raised to a power is already in the lowest/simplest form. A: (log n)^k is: * *O((log n)^k) *O(n^k) *O(n) *O(n log n) *O(n^1/2) *O(n^0.00000002) etc. Which one is meaningful for you depends on the constants and the context. A: Any function whose runtime has the form (log n)k is O((log n)k). This expression isn't reducable to any other primitive function using simple transformations, and it's fairly common to see algorithms with runtimes like O(n (log n)2). Functions with this growth rate are called polylogarithmic. By the way, typically (log n)k is written as logk n, so the above algorithm would have runtime O(n log2 n. In your case, the function log2 n + log n would be O(log2 n). However, any function with runtime of the form log (nk) has runtime O(log n), assuming that k is a constant. This is because log (nk) = k log n using logarithm identities, and k log n is O(log n) because k is a constant. You should be careful not to blindly conclude that an algorithm that is O(log (nk)) is O(log n), though; if k is a parameter to the function or depends on n, the correct big-O computation would be O(k log n) in this case. Depending on the context in which you're working, you sometimes see the notation Õ(f(n)) to mean O(f(n) logk n) for some constant k. This is sometimes called "soft-O" and is used in contexts in which the logarithmic terms are irrelevant. In that case, you could say that both functions are Õ(1), though this usage is not common in simple algorithmic analysis (in fact, outside of Wikipedia, I have seen this used precisely once). Hope this helps! A: log(n) is O((log(n))^2) so the entire expression is O((log(n))^2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: XML Android Permissions List Full I wish I could find this list before I made it. If for some strange reason you also need this, it is here for you. Only because I care. Now, like never before, give your apps full power. <uses-permission android:name="android.permission.ACCESS_CHECKIN_PROPERTIES" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCOUNT_MANAGER" /> <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /> <uses-permission android:name="android.permission.BATTERY_STATS" /> <uses-permission android:name="android.permission.BIND_APPWIDGET" /> <uses-permission android:name="android.permission.BIND_DEVICE_ADMIN" /> <uses-permission android:name="android.permission.BIND_INPUT_METHOD" /> <uses-permission android:name="android.permission.BIND_REMOTEVIEWS" /> <uses-permission android:name="android.permission.BIND_WALLPAPER" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BRICK" /> <uses-permission android:name="android.permission.BROADCAST_PACKAGE_REMOVED" /> <uses-permission android:name="android.permission.BROADCAST_SMS" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" /> <uses-permission android:name="android.permission.BROADCAST_WAP_PUSH" /> <uses-permission android:name="android.permission.CALL_PHONE"/> <uses-permission android:name="android.permission.CALL_PRIVILEGED" /> <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE" /> <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CLEAR_APP_CACHE" /> <uses-permission android:name="android.permission.CLEAR_APP_USER_DATA" /> <uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" /> <uses-permission android:name="android.permission.DELETE_CACHE_FILES" /> <uses-permission android:name="android.permission.DELETE_PACKAGES" /> <uses-permission android:name="android.permission.DEVICE_POWER" /> <uses-permission android:name="android.permission.DIAGNOSTIC" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.DUMP" /> <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" /> <uses-permission android:name="android.permission.FACTORY_TEST" /> <uses-permission android:name="android.permission.FLASHLIGHT" /> <uses-permission android:name="android.permission.FORCE_BACK" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.GET_PACKAGE_SIZE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.GLOBAL_SEARCH" /> <uses-permission android:name="android.permission.HARDWARE_TEST" /> <uses-permission android:name="android.permission.INJECT_EVENTS" /> <uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER" /> <uses-permission android:name="android.permission.INSTALL_PACKAGES" /> <uses-permission android:name="android.permission.INTERNAL_SYSTEM_WINDOW" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" /> <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> <uses-permission android:name="android.permission.MANAGE_APP_TOKENS" /> <uses-permission android:name="android.permission.MASTER_CLEAR" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> <uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.NFC" /> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" /> <uses-permission android:name="android.permission.READ_CALENDAR" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_FRAME_BUFFER" /> <uses-permission android:name="android.permission.READ_HISTORY_BOOKMARKS" /> <uses-permission android:name="android.permission.READ_INPUT_STATE" /> <uses-permission android:name="android.permission.READ_LOGS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" /> <uses-permission android:name="android.permission.READ_SYNC_STATS" /> <uses-permission android:name="android.permission.REBOOT" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_MMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_WAP_PUSH" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.REORDER_TASKS" /> <uses-permission android:name="android.permission.RESTART_PACKAGES" /> <uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.SET_ACTIVITY_WATCHER" /> <uses-permission android:name="android.permission.SET_ALARM" /> <uses-permission android:name="android.permission.SET_ALWAYS_FINISH" /> <uses-permission android:name="android.permission.SET_ANIMATION_SCALE" /> <uses-permission android:name="android.permission.SET_DEBUG_APP" /> <uses-permission android:name="android.permission.SET_ORIENTATION" /> <uses-permission android:name="android.permission.SET_POINTER_SPEED" /> <uses-permission android:name="android.permission.SET_PROCESS_LIMIT" /> <uses-permission android:name="android.permission.SET_TIME" /> <uses-permission android:name="android.permission.SET_TIME_ZONE" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" /> <uses-permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES" /> <uses-permission android:name="android.permission.STATUS_BAR" /> <uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_READ" /> <uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_WRITE" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.USE_SIP" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_APN_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_CALENDAR" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_HISTORY_BOOKMARKS" /> <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" /> EDITS Sorry for editing your post, but anything else is blocked (nothing like a closed useful thread). Anyway, few missed permissions: <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/> <uses-permission android:name="android.permission.BIND_TEXT_SERVICE"/> <uses-permission android:name="android.permission.BIND_VPN_SERVICE"/> <uses-permission android:name="android.permission.PERSISTENT_ACTIVITY"/> <uses-permission android:name="android.permission.READ_CALL_LOG"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/> <uses-permission android:name="android.permission.READ_PROFILE"/> <uses-permission android:name="android.permission.READ_SOCIAL_STREAM"/> <uses-permission android:name="android.permission.READ_USER_DICTIONARY"/> <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> <uses-permission android:name="android.permission.SET_PREFERRED_APPLICATIONS"/> <uses-permission android:name="android.permission.WRITE_CALL_LOG"/> <uses-permission android:name="com.android.browser.permission.WRITE_HISTORY_BOOKMARKS"/> <uses-permission android:name="android.permission.WRITE_PROFILE"/> <uses-permission android:name="android.permission.WRITE_SOCIAL_STREAM"/> <uses-permission android:name="android.permission.WRITE_USER_DICTIONARY"/> macias A: Is this the whole list of available permissions? Jesus! You could, however, access this list of permissions through using Eclipse, under AndroidManifest.xml by adding a "Uses Permission" control. On the right, it shows you the entire list of available permissions so you don't do a typo somewhere. But hey, sharing is caring! :D
{ "language": "en", "url": "https://stackoverflow.com/questions/7523075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "100" }
Q: Passing value of variable inside a string using C Suppose i have a string const char *temp = "i am new to C". Now i have a float variable a=1.0000; How can i send the value of "a" inside const char *temp along with the existing string. Thanks in advance. A: const char temp[] = "I am new to C"; float a = 1.0; char buffer[256]; sprintf(buffer, "%s %f", temp, a); A: If you wanted a string to include the value of a variable you could use snprintf; char temp[100]; float a =1.00; sprintf(temp,"The Value of a is %f", a); printf("%s", temp); This would print "The Value of a is 1.00"
{ "language": "en", "url": "https://stackoverflow.com/questions/7523079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: PHP/MySQL Pagination or jQuery? Just a quick question. If I use a Pagination for my website and am expecting a lot of results, is it better to use jQuery or just a basic PHP/MySQL one that just loads a new page? If I use jQuery and I have over 300 results from the database, will it have to load it all at once on the initial page load? That might take a long time to load. Or can you make it load only the first 10, and then when you go to Page 2 it will load the next 10? Just wondering if you have any suggestions for my situation, and if you recommend any good scripts I can use for it. Thanks! A: IMO, start with "basic" PHP/MySQL pagination (load a new page each time the user changes pages). Once you've got that working, if you want it, then add in jQuery pagination on top. All the jQuery pagination would do is load the new page of results via AJAX, rather than loading an entire new page. A: So, the key here is how you handle paginating results via javascript (jQuery). If you render all 300 results on the page and simply hide results 200-300 (and reveal them via javascript), your page will still be really slow to render initially, and you'll be taxing the database with a query that could be optimized via a limit (pagination). On the other hand, if you asynchronously query for more results via say, an asynchronous GET request to a web-service that spits the data out via JSON, you can both have a responsive page and avoid a taxing, limitless query. Using PHP / MySQL and post-backs to handle the issue also prevents the long-initial page load + taxing query. So, in summary, I'd absolutely paginate your results. I would also suggest you do the following: 1) First architect things using purely PHP / MySQL. So, for instance: /results/?start=0&limit=20 (Show results 0-19) /results/?start=20&limit=40 (Show results 20-40) 2) Then if you want to provide a responsive, javascript mechanism for loading more, extend your page so that it can spit out JSON with a format parameter: /results/?start=0&limit=20&format=JSON So if format=JSON instead of rendering the HTML, it'll just spit out the JSON data, paginated. 3) Then wire up the javascript to use the JSON data to dynamically load in more content: $.get('/results/?start=' + start + '&format=JSON', function(data) { // Process and display data }); Hopefully that makes sense! A: You've tagged your question with ajax, that's the answer... You should use a combo of PHP/MySQL + Ajax to make the things faster and smoother. Here is a very popular plugin which implement the client interface: JQGrid
{ "language": "en", "url": "https://stackoverflow.com/questions/7523080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I inject into an ASP.NET MVC controller, some strings (eg. configuration values) using StructureMap? I'm using structureMap as my IoC/DI for an ASP.NET MVC web site. Works great. Normally, I have my controllers that pass in Interfaces and structureMap + greedy constructors == works great. eg. public void FooController : Controller { public FooController(IPewPew pewPew) { .. } } etc.. But.. one of my controllers (and only one of em) would like to have two strings to be passed in. eg.. public void FooController2 : Controller { public FooController2(IPewPew pewPew, string aaa, string bbb) { .. } } Is there any ways I can do this with StructureMap? Is there a way to say, when a string "aaa" is listed, then use this value => "hi!"; I didn't really want to put all those strings, into a concrete class with an interface. It's like I want to say something like. For<string>().WithName("aaa").Use<string>().WithValue("hi"); Cheers! A: This worked for me: ObjectFactory.Configure( x=> { x.For<FooController2>() .Use<FooController2>() .Ctor<string>("aaa") .Is("hi"); }); A: You can register a Func<T> delegate, which allows you to have a type safe registration. container.Configure(r => r.For<FooController2>().Use(() => { var pewPew = container.GetInstance<IPewPew>(); return new FooController2(pewPew, "someValue", "anotherValue"); }));
{ "language": "en", "url": "https://stackoverflow.com/questions/7523096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: INSERT trigger to update a field that is NOT NULL in the same table I have a situation where I need to merge two product tables into one and need to keep both id fields. The Id field is the pk and an identity column. On insert I want to update the prodId to match the Id of the newly inserted row. This is what I have but I get an error saying that I cannot insert null into ProductId. What am I doing wrong? ALTER TRIGGER SyncId ON Product FOR INSERT AS BEGIN DECLARE @ID INT SET @ID = (SELECT ID FROM Inserted) UPDATE Product SET ProdId = @ID WHERE Id = @ID END A: You could create an INSTEAD OF trigger for the INSERT. You would then have to recreate the actual INSERT logic. You might need a view of the table for the trigger to sit on though... I don't recall if an INSERT within the trigger will work or not and can't test it right now. Also, your trigger as written will only work if a single row is being updated. You should always write your triggers to be able to handle multiple rows in the INSERTED and DELETED tables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I make tabs in a tabview transparent How do I make a tabview so that the tabs are a bit transparent so that you can see the content of a Listview being hosted by the tabview? So far I tried making the tabs/buttons transparent by setting the alpha, but I think that the way the Tabhost is made there isn't anything behind the buttons, so making it transparent will only show a black background Thanks! A: You can hide the tab widget. And use buttons <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/header"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="woopra" android:textColor="#ffffff" android:textSize="36sp" android:textStyle="bold"/> </LinearLayout> <FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="gone"/> <LinearLayout android:layout_width="fill_parent" android:layout_height="64dip"> <Button android:layout_height="fill_parent" android:layout_width="0dip" android:layout_weight="1.0" android:id="@+id/dashboard_tab" android:onClick="tabHandler" android:text="Dashboard"/> <Button android:layout_height="fill_parent" android:layout_width="0dip" android:layout_weight="1.0" android:id="@+id/visitors_tab" android:onClick="tabHandler" android:text="Vistors"/> <Button android:layout_height="fill_parent" android:layout_width="0dip" android:layout_weight="1.0" android:id="@+id/chat_tab" android:onClick="tabHandler" android:text="Chat"/> <Button android:layout_height="fill_parent" android:layout_width="0dip" android:layout_weight="1.0" android:id="@+id/reports_tab" android:onClick="tabHandler" android:text="Reports"/> </LinearLayout> </FrameLayout> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1.0"/> </LinearLayout> Here Ive used 4 buttons instead of the tabwidget. And in the button's onclick I use something like tabHost.setCurrentTab(1); Setting alpha to the buttons should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dialog.getWindow() returns null after dialog is created @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_ID: LayoutInflater inflater = getLayoutInflater(); View InfoLayout = inflater.inflate(R.layout.info_dialog, null); AlertDialog.Builder b = new AlertDialog.Builder(MyActivity.this) .setView(InfoLayout ); initInfoDialog(dialog); return dialog; ... private void initInfoDialog(Dialog dialog) { //this line has the null pointer WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); Why is dialog.getWindow() returning null in this case? A: I faced the same problem and I see now the getWindow() documentation is actually telling why (not the reason but why at this specific point). You can retrieve the window after calling show().
{ "language": "en", "url": "https://stackoverflow.com/questions/7523112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to upload files in JSF 1.1? I want to upload files in a JSF 1.1 project. JSF 1.1 doesn't support RichFaces file upload. I looked at Tomahawk, but I don't know how to use Tomahawk. Can anybody explain for me? * *Which JARs do I have to use? *And taglibs? *And web.xml configuration? *And faces-config.xml configuration? Or are there alternatives to Tomahawk? A: Which JARs do I have to use? The following ones: * *tomahawk *commons-fileupload *commons-io *commons-logging *commons-el I assume that you already have the JSF 1.1 JARs jsf-api and jsf-impl. And taglibs? Just the Tomahawk one, next to the two usual core/html tags: <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t" %> And web.xml configuration? You need the ExtensionsFilter. This filter will take care that JSF gets the right parameters out of a multipart/form-data request body. <filter> <filter-name>Extensions Filter</filter-name> <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class> </filter> <filter-mapping> <filter-name>Extensions Filter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> And faces-config.xml configuration? Nothing special. Just create a managed bean the usual way with a UploadedFile property which you bind to the value attribute of <t:inputFileUpload>. See also: * *How to upload files in JSF? (yes, it's targeted on JSF 1.2, but should work equally good in JSF 1.1).
{ "language": "en", "url": "https://stackoverflow.com/questions/7523113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inconsistent Silverlight 4 ComboBox Dropdown Display I have a Silverlight 4 application with a ComboBox near the bottom of the form. There can be anywhere from about 30 to 100 items in the Dropdown. When I first open the ComboBox, there is no SelectedItem, the Dropdown opens upwards and it makes about 23 entries visible; it will continue this behavior each time I re-open the Dropdown, as long as I do not select an item. Once I select an item, everytime I open the ComboBox thereafter it always opens the Dropdown downwards, and makes only 3 entries visible. I'm guessing the Dropdown is limited to 3 items, because that is the bottom limit of the window when it is maximized on my screen. How do I get it to display more items, even when an item has been previously selected? Here is an example Silverlight application that demonstrates the behavior, both in and out of browser. MainPage.xaml: <UserControl x:Class="ComboBox_Test.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="650" d:DesignWidth="1024"> <Grid x:Name="LayoutRoot" Background="LightSteelBlue" Loaded="MainPage_OnLoaded"> <Grid.RowDefinitions> <RowDefinition Height="3*" MinHeight="25" MaxHeight="25" /> <RowDefinition Height="35*" MinHeight="200" /> <RowDefinition Height="10*" MinHeight="70" MaxHeight="70" /> <RowDefinition Height="30*" MinHeight="230" MaxHeight="230" /> <RowDefinition Height="*" MinHeight="10" MaxHeight="30" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="12" /> <ColumnDefinition Width="150" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="12" /> </Grid.ColumnDefinitions> <TextBlock Name="lblData" Text="Data:" Grid.Row="1" Grid.Column="1" /> <TextBox x:Name="txtData" Grid.Row="1" Grid.Column="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" /> <StackPanel x:Name="AccessPanel" Orientation="Vertical" HorizontalAlignment="Left" Margin="5" Grid.Row="3" Grid.Column="2" Visibility="Visible"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="75" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel x:Name="CreationPanel" Orientation="Vertical" Grid.Row="1"> <Grid x:Name="CreationRoot"> <Grid.RowDefinitions> <RowDefinition Height="40" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel x:Name="TypesPanel" Orientation="Horizontal" Grid.Row="1" Grid.Column="1" Margin="0 5 0 5"> <Grid x:Name="TypesRoot"> <Grid.RowDefinitions> <RowDefinition Height="25" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="220" /> <ColumnDefinition Width="220" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Text="Types" FontFamily="Arial" FontSize="12" FontWeight="Bold" Grid.Row="0" Grid.Column="0" /> <ComboBox x:Name="cboTypes" Width="220" Height="30" Grid.Row="1" Grid.Column="0" IsEnabled="True" SelectionChanged="cboTypes_SelectionChanged"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name, Mode=OneWay}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> </Grid> </StackPanel> </Grid> </StackPanel> </Grid> </StackPanel> </Grid> </UserControl> MainPage.xaml.cs: using System; using System.Windows; using System.Windows.Controls; namespace ComboBox_Test { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void UpdateDataText(DataTypeDesc oData) { txtData.Text = String.Format("{0}\n\t{1}", oData.Name, oData.Desc); } private void MainPage_OnLoaded(object sender, RoutedEventArgs e) { object[] aDataTypeDescs = new object[] { new DataTypeDesc() {Name = "Boolean", Desc = "A Boolean value"} , new DataTypeDesc() {Name = "Byte", Desc = "An 8-bit unsigned integer"} , new DataTypeDesc() {Name = "Char", Desc = "A Unicode character"} , new DataTypeDesc() {Name = "Double", Desc = "A double-precision floating-point number"} , new DataTypeDesc() {Name = "float", Desc = "A single-precision floating-point number"} , new DataTypeDesc() {Name = "Int16", Desc = "A 16-bit signed integer"} , new DataTypeDesc() {Name = "Int32", Desc = "A 32-bit signed integer"} , new DataTypeDesc() {Name = "Int64", Desc = "A 64-bit signed integer"} , new DataTypeDesc() {Name = "SByte", Desc = "An 8-bit signed integer"} , new DataTypeDesc() {Name = "UInt16", Desc = "A 16-bit unsigned integer"} , new DataTypeDesc() {Name = "UInt32", Desc = "A 32-bit unsigned integer"} , new DataTypeDesc() {Name = "UInt64", Desc = "A 64-bit unsigned integer"} , new DataTypeDesc() {Name = "A", Desc = "The letter A in the alphabet"} , new DataTypeDesc() {Name = "B", Desc = "The letter B in the alphabet"} , new DataTypeDesc() {Name = "C", Desc = "The letter C in the alphabet"} , new DataTypeDesc() {Name = "D", Desc = "The letter D in the alphabet"} , new DataTypeDesc() {Name = "E", Desc = "The letter E in the alphabet"} , new DataTypeDesc() {Name = "F", Desc = "The letter F in the alphabet"} , new DataTypeDesc() {Name = "G", Desc = "The letter G in the alphabet"} , new DataTypeDesc() {Name = "H", Desc = "The letter H in the alphabet"} , new DataTypeDesc() {Name = "I", Desc = "The letter I in the alphabet"} , new DataTypeDesc() {Name = "J", Desc = "The letter J in the alphabet"} , new DataTypeDesc() {Name = "K", Desc = "The letter K in the alphabet"} , new DataTypeDesc() {Name = "L", Desc = "The letter L in the alphabet"} , new DataTypeDesc() {Name = "M", Desc = "The letter M in the alphabet"} , new DataTypeDesc() {Name = "N", Desc = "The letter N in the alphabet"} , new DataTypeDesc() {Name = "O", Desc = "The letter O in the alphabet"} , new DataTypeDesc() {Name = "P", Desc = "The letter P in the alphabet"} , new DataTypeDesc() {Name = "Q", Desc = "The letter Q in the alphabet"} , new DataTypeDesc() {Name = "R", Desc = "The letter R in the alphabet"} , new DataTypeDesc() {Name = "S", Desc = "The letter S in the alphabet"} , new DataTypeDesc() {Name = "T", Desc = "The letter T in the alphabet"} , new DataTypeDesc() {Name = "U", Desc = "The letter U in the alphabet"} , new DataTypeDesc() {Name = "V", Desc = "The letter V in the alphabet"} , new DataTypeDesc() {Name = "W", Desc = "The letter W in the alphabet"} , new DataTypeDesc() {Name = "X", Desc = "The letter X in the alphabet"} , new DataTypeDesc() {Name = "Y", Desc = "The letter Y in the alphabet"} , new DataTypeDesc() {Name = "Z", Desc = "The letter Z in the alphabet"} }; cboTypes.ItemsSource = aDataTypeDescs; } private void cboTypes_SelectionChanged(object sender, SelectionChangedEventArgs e) { DataTypeDesc oDesc = (DataTypeDesc)(cboTypes.SelectedItem); if (oDesc != null) UpdateDataText(oDesc); } } } DataTypeDesc.cs: using System; namespace ComboBox_Test { public class DataTypeDesc { public String Name { get; set; } public String Desc { get; set; } } } A: You need to edit the basic ComboBox template and change the size of the element called Popup. In this example it has been set to 100 high and now shows the same fixed height popup whether initial list or after selection: *Note: I used Expression blend to edit a copy of the basic template (which is quite detailed). As the element part is named "Popup" you could in theory write code to find that part in the visual tree and modify the height property that way. Source for the changed page below: <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:System="clr-namespace:System;assembly=mscorlib" x:Class="ComboBox_Test.MainPage" d:DesignHeight="650" d:DesignWidth="1024" mc:Ignorable="d"> <UserControl.Resources> <ControlTemplate x:Key="ValidationToolTipTemplate"> <Grid x:Name="Root" Margin="5,0" Opacity="0" RenderTransformOrigin="0,0"> <Grid.RenderTransform> <TranslateTransform x:Name="xform" X="-25"/> </Grid.RenderTransform> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="OpenStates"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0"/> <VisualTransition GeneratedDuration="0:0:0.2" To="Open"> <Storyboard> <DoubleAnimation Duration="0:0:0.2" To="0" Storyboard.TargetProperty="X" Storyboard.TargetName="xform"> <DoubleAnimation.EasingFunction> <BackEase Amplitude=".3" EasingMode="EaseOut"/> </DoubleAnimation.EasingFunction> </DoubleAnimation> <DoubleAnimation Duration="0:0:0.2" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Root"/> </Storyboard> </VisualTransition> </VisualStateGroup.Transitions> <VisualState x:Name="Closed"> <Storyboard> <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Root"/> </Storyboard> </VisualState> <VisualState x:Name="Open"> <Storyboard> <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="X" Storyboard.TargetName="xform"/> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Root"/> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border Background="#052A2E31" CornerRadius="5" Margin="4,4,-4,-4"/> <Border Background="#152A2E31" CornerRadius="4" Margin="3,3,-3,-3"/> <Border Background="#252A2E31" CornerRadius="3" Margin="2,2,-2,-2"/> <Border Background="#352A2E31" CornerRadius="2" Margin="1,1,-1,-1"/> <Border Background="#FFDC000C" CornerRadius="2"/> <Border CornerRadius="2"> <TextBlock Foreground="White" MaxWidth="250" Margin="8,4,8,4" TextWrapping="Wrap" Text="{Binding (Validation.Errors)[0].ErrorContent}" UseLayoutRounding="false"/> </Border> </Grid> </ControlTemplate> <Style x:Key="ComboBoxStyle1" TargetType="ComboBox"> <Setter Property="Padding" Value="6,2,25,2"/> <Setter Property="Background" Value="#FF1F3B53"/> <Setter Property="HorizontalContentAlignment" Value="Left"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="TabNavigation" Value="Once"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="BorderBrush"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFA3AEB9" Offset="0"/> <GradientStop Color="#FF8399A9" Offset="0.375"/> <GradientStop Color="#FF718597" Offset="0.375"/> <GradientStop Color="#FF617584" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ComboBox"> <Grid> <Grid.Resources> <Style x:Name="comboToggleStyle" TargetType="ToggleButton"> <Setter Property="Foreground" Value="#FF333333"/> <Setter Property="Background" Value="#FF1F3B53"/> <Setter Property="BorderBrush"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFA3AEB9" Offset="0"/> <GradientStop Color="#FF8399A9" Offset="0.375"/> <GradientStop Color="#FF718597" Offset="0.375"/> <GradientStop Color="#FF617584" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Padding" Value="3"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToggleButton"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"> <Storyboard> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundOverlay"/> <ColorAnimation Duration="0" To="#7FFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> <ColorAnimation Duration="0" To="#CCFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> <ColorAnimation Duration="0" To="#F2FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundOverlay2"/> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Highlight"/> <ColorAnimation Duration="0" To="#E5FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> <ColorAnimation Duration="0" To="#BCFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> <ColorAnimation Duration="0" To="#6BFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> <ColorAnimation Duration="0" To="#F2FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/> </Storyboard> </VisualState> <VisualState x:Name="Disabled"/> </VisualStateGroup> <VisualStateGroup x:Name="CheckStates"> <VisualState x:Name="Checked"> <Storyboard> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="BackgroundOverlay3"/> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Highlight"/> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="BackgroundGradient2"/> <ColorAnimation Duration="0" To="#E5FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient2"/> <ColorAnimation Duration="0" To="#BCFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient2"/> <ColorAnimation Duration="0" To="#6BFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient2"/> <ColorAnimation Duration="0" To="#F2FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient2"/> </Storyboard> </VisualState> <VisualState x:Name="Unchecked"/> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="FocusVisualElement"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Unfocused"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Rectangle x:Name="Background" Fill="{TemplateBinding Background}" RadiusY="3" RadiusX="3" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="{TemplateBinding BorderThickness}"/> <Rectangle x:Name="BackgroundOverlay" Fill="#FF448DCA" Opacity="0" RadiusY="3" RadiusX="3" Stroke="#00000000" StrokeThickness="{TemplateBinding BorderThickness}"/> <Rectangle x:Name="BackgroundOverlay2" Fill="#FF448DCA" Opacity="0" RadiusY="3" RadiusX="3" Stroke="#00000000" StrokeThickness="{TemplateBinding BorderThickness}"/> <Rectangle x:Name="BackgroundGradient" Margin="{TemplateBinding BorderThickness}" RadiusY="2" RadiusX="2" Stroke="#FFFFFFFF" StrokeThickness="1"> <Rectangle.Fill> <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0"> <GradientStop Color="#FFFFFFFF" Offset="0"/> <GradientStop Color="#F9FFFFFF" Offset="0.375"/> <GradientStop Color="#E5FFFFFF" Offset="0.625"/> <GradientStop Color="#C6FFFFFF" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <Rectangle x:Name="BackgroundOverlay3" Fill="#FF448DCA" Opacity="0" RadiusY="3" RadiusX="3" Stroke="#00000000" StrokeThickness="{TemplateBinding BorderThickness}"/> <Rectangle x:Name="BackgroundGradient2" Margin="{TemplateBinding BorderThickness}" Opacity="0" RadiusY="2" RadiusX="2" Stroke="#FFFFFFFF" StrokeThickness="1"> <Rectangle.Fill> <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0"> <GradientStop Color="#FFFFFFFF" Offset="0"/> <GradientStop Color="#F9FFFFFF" Offset="0.375"/> <GradientStop Color="#E5FFFFFF" Offset="0.625"/> <GradientStop Color="#C6FFFFFF" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <Rectangle x:Name="Highlight" IsHitTestVisible="false" Margin="{TemplateBinding BorderThickness}" Opacity="0" RadiusY="2" RadiusX="2" Stroke="#FF6DBDD1" StrokeThickness="1"/> <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> <Rectangle x:Name="FocusVisualElement" IsHitTestVisible="false" Margin="1" RadiusY="3.5" RadiusX="3.5" Stroke="#FF6DBDD1" StrokeThickness="1" Visibility="Collapsed"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Grid.Resources> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"/> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Duration="00:00:00" To=".55" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="DisabledVisualElement"/> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <Storyboard> <DoubleAnimation Duration="00:00:00" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="FocusVisualElement"/> </Storyboard> </VisualState> <VisualState x:Name="Unfocused"/> <VisualState x:Name="FocusedDropDown"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="00:00:00" Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="PopupBorder"> <DiscreteObjectKeyFrame KeyTime="00:00:00"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="ValidationStates"> <VisualState x:Name="Valid"/> <VisualState x:Name="InvalidUnfocused"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ValidationErrorElement"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="InvalidFocused"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ValidationErrorElement"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsOpen" Storyboard.TargetName="validationTooltip"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <System:Boolean>True</System:Boolean> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="ContentPresenterBorder"> <Grid> <ToggleButton x:Name="DropDownToggle" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Right" Margin="0" Style="{StaticResource comboToggleStyle}" VerticalAlignment="Stretch"> <Path x:Name="BtnArrow" Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z " HorizontalAlignment="Right" Height="4" Margin="0,0,6,0" Stretch="Uniform" Width="8"> <Path.Fill> <SolidColorBrush x:Name="BtnArrowColor" Color="#FF333333"/> </Path.Fill> </Path> </ToggleButton> <ContentPresenter x:Name="ContentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"> <TextBlock Text=" "/> </ContentPresenter> </Grid> </Border> <Rectangle x:Name="DisabledVisualElement" Fill="White" IsHitTestVisible="false" Opacity="0" RadiusY="3" RadiusX="3"/> <Rectangle x:Name="FocusVisualElement" IsHitTestVisible="false" Margin="1" Opacity="0" RadiusY="2" RadiusX="2" Stroke="#FF6DBDD1" StrokeThickness="1"/> <Border x:Name="ValidationErrorElement" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1" Visibility="Collapsed"> <ToolTipService.ToolTip> <ToolTip x:Name="validationTooltip" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Template="{StaticResource ValidationToolTipTemplate}"> <ToolTip.Triggers> <EventTrigger RoutedEvent="Canvas.Loaded"> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsHitTestVisible" Storyboard.TargetName="validationTooltip"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <System:Boolean>true</System:Boolean> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </ToolTip.Triggers> </ToolTip> </ToolTipService.ToolTip> <Grid Background="Transparent" HorizontalAlignment="Right" Height="12" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12"> <Path Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z" Fill="#FFDC000C" Margin="1,3,0,0"/> <Path Data="M 0,0 L2,0 L 8,6 L8,8" Fill="#ffffff" Margin="1,3,0,0"/> </Grid> </Border> <Popup x:Name="Popup"> <Border x:Name="PopupBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3" HorizontalAlignment="Stretch" Height="100"> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFFFFFFF" Offset="0"/> <GradientStop Color="#FFFEFEFE" Offset="1"/> </LinearGradientBrush> </Border.Background> <ScrollViewer x:Name="ScrollViewer" BorderThickness="0" Padding="1"> <ItemsPresenter/> </ScrollViewer> </Border> </Popup> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="LightSteelBlue" Loaded="MainPage_OnLoaded"> <Grid.RowDefinitions> <RowDefinition Height="3*" MinHeight="25" MaxHeight="25" /> <RowDefinition Height="35*" MinHeight="200" /> <RowDefinition Height="10*" MinHeight="70" MaxHeight="70" /> <RowDefinition Height="30*" MinHeight="230" MaxHeight="230" /> <RowDefinition Height="*" MinHeight="10" MaxHeight="30" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="12" /> <ColumnDefinition Width="150" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="12" /> </Grid.ColumnDefinitions> <TextBlock x:Name="lblData" Text="Data:" Grid.Row="1" Grid.Column="1" /> <TextBox x:Name="txtData" Grid.Row="1" Grid.Column="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" /> <StackPanel x:Name="AccessPanel" Orientation="Vertical" HorizontalAlignment="Left" Margin="5" Grid.Row="3" Grid.Column="2" Visibility="Visible"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="75" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel x:Name="CreationPanel" Orientation="Vertical" Grid.Row="1"> <Grid x:Name="CreationRoot"> <Grid.RowDefinitions> <RowDefinition Height="40" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel x:Name="TypesPanel" Orientation="Horizontal" Grid.Row="1" Grid.Column="1" Margin="0 5 0 5"> <Grid x:Name="TypesRoot"> <Grid.RowDefinitions> <RowDefinition Height="25" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="220" /> <ColumnDefinition Width="220" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Text="Types" FontFamily="Arial" FontSize="12" FontWeight="Bold" Grid.Row="0" Grid.Column="0" /> <ComboBox x:Name="cboTypes" Width="220" Height="30" Grid.Row="1" Grid.Column="0" IsEnabled="True" SelectionChanged="cboTypes_SelectionChanged" MaxDropDownHeight="600" Style="{StaticResource ComboBoxStyle1}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name, Mode=OneWay}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> </Grid> </StackPanel> </Grid> </StackPanel> </Grid> </StackPanel> </Grid> </UserControl> A: I was having this exact same issue (actually with Silverlight 5, but the same behavior nonetheless) and found a rather unlikely solution that does not involve modifying the template (in my case, I did not want to force the Popup to have a fixed size and direction). I discovered that if I populated my ComboBox with ComboBoxItems instead of a collection of custom objects, then the dropdown/selection/direction issue does not occur. I did not really want to do this because my original design was using Binding on ItemsSource, SelectedItem etc. But since it fixes the issue I went with ComboBoxItems and dropped the binding approach. So here are a couple of quick code snippets that illustrate the difference - the first uses a collection of custom objects and results in the strange behavior (my VehicleData class is just a simple class with an ID and Name along with few other properties): // List of Custom Objects - Results in inconsistent behavior ObservableCollection<VehicleData> vehicleList = new ObservableCollection<VehicleData>(); for (int i = 0; i < 80; i++) { vehicleList.Add(new VehicleData { ID = i, Name = string.Format("Vehicle {0}", i) }); } ComboBoxVehicles.DisplayMemberPath = "Name"; ComboBoxVehicles.ItemsSource = vehicleList; And here is an example that works fine no matter how many items are added and what the positioning of the ComboBox is: // List of ComboBoxItems - WORKS List<ComboBoxItem> testValues = new List<ComboBoxItem>(); for (int i = 0; i < 80; i++) { testValues.Add(new ComboBoxItem { Content = "Item " + i, Tag = i }); } ComboBoxVehicles.ItemsSource = testValues; I know this question has already been answered but thought I would post this in the event it helped someone else. A: Depending on the numbers of items you have and your available screen height, you can also set ScrollViewer.VerticalScrollBarVisibility="Disabled", this will force it to open upwards as there is no space downwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Help with a slight issue in reading in a text file using the '<' redirection operator in command line? C I've searched high and low, but can not find the answer to what I would've thought to be a rather simple question. I'm rather new to C, and due to the restrictions placed on me during this project I'm having a bit of trouble figuring out how to do this. I am trying to read in text from a text file, and store that data in an array. Simple enough. HOWEVER, I'm forced to do so by using the command line operator '<' and to redirect the stdin to the text file. The only way I can seem to figure out how to properly open a file and perform the subsequent operations is the following: #include <stdio.h> FILE *fr; main() { fr = fopen ("mytext.txt", "r"); /* open the file for reading */ The problem with that is that I can't seem to get the first parameter of fopen() to be the filename provided by the stdin '<'. It only works if I explicitly type a string in for the parameter. For example, if I were to run myprog.o < mytxt.txt how could I pass the name of the text file provided by that stdin redirection to the fopen function? Or is there a different/better way to do what I'm trying to do? Thanks in advance. A: You need to read from stdin instead of trying to open the file directly. This is because of how redirection works - think of it a bit like this: * *The file is opened (for purposes of demonstration, let's say fopen is used for this). *The existing stdin is closed. It no longer refers to a terminal or similar construct. *stdin is replaced with the open file in step 1. *Any reads from stdin now work directly from the input file. By using input redirection you can permit your user to either redirect a file or directly type content into your program. As for your actual problem, you might be better off passing the filename as an argument to your program. You would use argv and call your program like so: myprog.o mytxt.txt In this case, argv[1] will be mytxt.txt. A: There is a standard FILE* handle declared within <stdio.h> that points to the standard input for the executing process. Such file handle is called stdin. A: A C program never sees the redirection because it is handled by the shell. The C program should look at argc and read from stdin if no args are given or from the given files otherwise. A: If all you ever want this program to do is read from standard input, then you don't need to open any files. The OS and C libraries will handle opening and closing the file for you. So to read a file in from standard input, and write it back out, try something as simple as #include <stdio.h> int main( int argc, char ** argv ) { int ch = getchar(); while ( ch != EOF ) { putchar( ch ); ch = getchar(); } } As you can see, no opening or closing of files. putchar and getchar write to stdin and stdout relatively. If you want to be more explicit, you can use the predefined file handles. int ch = fgetc( stdin ); while ( ch != EOF ) { fputc( ch, stdout ); ch = fgetc( stdin ); } You should look up printf() and fprintf(), scanf() and fscanf(), and all the other wonderful stdio functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use cryptography in Java? I need to protect a sequence of bytes with cryptography and I will need to recover the data later. I want to use a key/password to encrypt and decrypt the data. I am using Java. How do I encrypt and decrypt a string with a key or password in Java? Thanks. Edit: The method cannot be slow. A: I hope this helps you get a general idea. This one is Symmetric cryptography. import java.security.*; import java.security.cert.*; import java.security.interfaces.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.interfaces.*; import javax.crypto.spec.*; import java.io.*; /** * AES */ public class SymmetricAES { public SymmetricAES() { } public static void main(String args[]){ BufferedReader ch = new BufferedReader(new InputStreamReader(System.in)); char[] toCode; byte[] toCode2; byte[] Coded; char[] Coded2; byte[] decoded; char[] deco2; try{ System.out.print("Text to Encrypt : "); String toMake = ch.readLine(); /** Arxikopoihsh antikeimenou KeyGenerator gia AES * kai dhmhourgia Kleidioy */ KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey aesKey = keyGen.generateKey(); /* Arxikopoihsh aesCipher gia AES */ Cipher aesCipher = Cipher.getInstance("AES"); /* Orismos aesCipher se ENCRYPT_MODE me to aesKey */ aesCipher.init(Cipher.ENCRYPT_MODE, aesKey); System.out.println("The Key : " + aesKey.getEncoded()); /* Metatroph antikeimenou String se pinaka Char * kai o ka8e xarakthras gineta Cast se Byte kai eisagwgh * se pinaka Byte isou mege8ous me ton prwto pinaka */ toCode = toMake.toCharArray(); toCode2 = new byte[toCode.length]; Coded = new byte[toCode.length]; for(int i=0;i<toCode.length;i++) toCode2[i] = (byte)toCode[i]; /* Teliko stadio Kryptografhshs */ Coded = aesCipher.doFinal(toCode2); /* byte[] --> char[] kai ektypwsh*/ Coded2 = new char[Coded.length]; for(int i=0;i<Coded.length;i++) Coded2[i] = (char)Coded[i]; System.out.println("Test Encrypt: " + new String(Coded2)); Cipher aesCipher2 = Cipher.getInstance("AES"); /* Orismos aesCipher2 se DECRYPT_MODE me to aesKey */ aesCipher2.init(Cipher.DECRYPT_MODE, aesKey); decoded = aesCipher2.doFinal(Coded); /* byte[] --> char[] kai ektypwsh*/ deco2 = new char[decoded.length]; for(int i=0;i<decoded.length;i++) deco2[i] = (char)decoded[i]; System.out.println("Test Decrypt: " + new String(deco2)); } catch(Exception e){ System.out.println(e); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Maze Algorithm KINDA works. Some mazes, not ALL help I am using a maze algorithm that works some of the time, but not all of the time. It uses recursion but I cannot figure out why it doesnt all the time. public boolean findPath(int x, int y) { myArray[x][y] = "T"; // marks coordinate T for traveled printMaze(); // prints the current state of the maze if (x == finish[0] && y == finish[1]) { // base case: if at finish, solved. isFinish = true; return isFinish; } else { isFinish = false; // not at finish for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i * j == 0 && i != j && canIGoHere(x+i, y+j) && !isFinish) { isFinish = findPath(x + i, y + j); } } } return isFinish; } } A: I think the function should return as soon as isFinish is true. As it is now, the function may find the finish position but it then continues to loop and may move away from that position before returning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Move cursor to the beginning of a designmode iframe Is it possible to move the caret to the very beginning (right before first element) of a designmode IFRAME? A: Here's a function to do that. Pass in a reference to the <iframe> element. Live demo: http://jsfiddle.net/aLP26/ Code: function moveCursorToStart(iframeEl) { var win = iframeEl.contentWindow || iframeEl.contentDocument.defaultView; var doc = win.document; if (win.getSelection && doc.createRange) { var sel = win.getSelection(); var range = doc.createRange(); range.selectNodeContents(doc.body); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } else if (doc.selection && doc.body.createTextRange) { var textRange = doc.body.createTextRange(); textRange.collapse(true); textRange.select(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nhibernate; control over when Session Per Request is saved I'm trying to develop a web forms application using NHibernate and the Session Per Request model. All the examples I've seen have an HTTPModule that create a session and transaction at the beging of each request and then commits the transaction and closes the session at the end of the request. I've got this working but I have some concerns. The main concern is that objects are automatically saved to the database when the web request is finished. I'm not particularly pleased with this and would much prefer some way to take a more active approach to deciding what is actually saved when the request is finished. Is this possible with the Session Per Request approach? Ideally I'd like for the interaction with the database to go something like this: * *Retreive object from the database or create a new one *Modify it in some way *Call a save method on the object which validates that it's indeed ready to be commited to the database *Object gets saved to the database I'm able to accomplish this if I do not use the Sessions Per Request model and wrap the interactions in a using session / using transaction blocks. The problem I ran into in taking this approach is that after the object is loaded from the database the session is closed an I am not able to utilize lazy loading. Most of the time that's okay but there are a few objects which have lists of other objects that then cannot be modified because, as stated, the session has been closed. I know I could eagerly load those objects but they don't always get used and I feel that in doing so I'm failing at utilizing NHibernate. Is there some way to use the Session Per Request (or any other model, it seems like that one is the most common) which will allow me to utilize lazy loading AND provide me with a way to manually decide when an object is saved back to the database? Any code, tutorials, or feedback is greatly appreciated. A: Yes, this is possible and you should be able to find examples of it. This is how I do it: * *Use session-per-request but do not start a transaction at the start of the request. *Set ISession.FlushMode to Commit. *Use individual transactions (occasionally multiple per session) as needed. *At the end of the session, throw an exception if there's an active uncommitted transaction. If the session is dirty, flush it and log a warning. With this approach, the session is open during the request lifetime so lazy loading works, but the transaction scope is limited as you see fit. In my opinion, using a transaction-per-request is a bad practice. Transactions should be compact and surround the data access code. Be aware that if you use database assigned identifiers (identity columns in SQL Server), NHibernate may perform inserts outside of your transaction boundaries. And lazy loads can of course occur outside of transactions (you should use transactions for reads also).
{ "language": "en", "url": "https://stackoverflow.com/questions/7523142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Powershell 2 and .NET: Optimize for extremely large hash tables? I am dabbling in Powershell and completely new to .NET. I am running a PS script that starts with an empty hash table. The hash table will grow to at least 15,000 to 20,000 entries. Keys of the hash table will be email addresses in string form, and values will be booleans. (I simply need to track whether or not I've seen an email address.) So far, I've been growing the hash table one entry at a time. I check to make sure the key-value pair doesn't already exist (PS will error on this condition), then I add the pair. Here's the portion of my code we're talking about: ... if ($ALL_AD_CONTACTS[$emailString] -ne $true) { $ALL_AD_CONTACTS += @{$emailString = $true} } ... I am wondering if there is anything one can do from a PowerShell or .NET standpoint that will optimize the performance of this hash table if you KNOW it's going to be huge ahead of time, like 15,000 to 20,000 entries or beyond. Thanks! A: I performed some basic tests using Measure-Command, using a set of 20 000 random words. The individual results are shown below, but in summary it appears that adding to one hashtable by first allocating a new hashtable with a single entry is incredibly inefficient :) Although there were some minor efficiency gains among options 2 through 5, in general they all performed about the same. If I were to choose, I might lean toward option 5 for its simplicity (just a single Add call per string), but all the alternatives I tested seem viable. $chars = [char[]]('a'[0]..'z'[0]) $words = 1..20KB | foreach { $count = Get-Random -Minimum 15 -Maximum 35 -join (Get-Random $chars -Count $count) } # 1) Original, adding to hashtable with "+=". # TotalSeconds: ~800 Measure-Command { $h = @{} $words | foreach { if( $h[$_] -ne $true ) { $h += @{ $_ = $true } } } } # 2) Using sharding among sixteen hashtables. # TotalSeconds: ~3 Measure-Command { [hashtable[]]$hs = 1..16 | foreach { @{} } $words | foreach { $h = $hs[$_.GetHashCode() % 16] if( -not $h.ContainsKey( $_ ) ) { $h.Add( $_, $null ) } } } # 3) Using ContainsKey and Add on a single hashtable. # TotalSeconds: ~3 Measure-Command { $h = @{} $words | foreach { if( -not $h.ContainsKey( $_ ) ) { $h.Add( $_, $null ) } } } # 4) Using ContainsKey and Add on a hashtable constructed with capacity. # TotalSeconds: ~3 Measure-Command { $h = New-Object Collections.Hashtable( 21KB ) $words | foreach { if( -not $h.ContainsKey( $_ ) ) { $h.Add( $_, $null ) } } } # 5) Using HashSet<string> and Add. # TotalSeconds: ~3 Measure-Command { $h = New-Object Collections.Generic.HashSet[string] $words | foreach { $null = $h.Add( $_ ) } } A: So it's a few weeks later, and I wasn't able to come up with the perfect solution. A friend at Google suggested splitting the hash into several smaller hashes. He suggested that each time I went to look up a key, I'd have several misses until I found the right "bucket", but he said the read penalty wouldn't be nearly as bad as the write penalty when the collision algorithm ran to insert entries into the (already giant) hash table. I took this idea and took it one step further. I split the hash into 16 smaller buckets. When inserting an email address as a key into the data structures, I actually first compute a hash on the email address itself, and do a mod 16 operation to get a consistent value between 0 and 15. I then use that calculated value as the "bucket" number. So instead of using one giant hash, I actually have a 16-element array, whose elements are hash tables of email addresses. The total speed it takes to build the in-memory representation of my "master list" of 20,000+ email addresses, using split-up hash table buckets, is now roughly 1,000% faster. (10 times faster). Accessing all of the data in the hashes has no noticeable speed delays. This is the best solution I've been able to come up with so far. It's slightly ugly, but the performance improvement speaks for itself. A: You're going to spend a lot of the CPU time re-allocating the internal 'arrays' in the Hashtable. Have you tried the .NET constructor for Hashtable that takes a capacity? $t = New-Object Hashtable 20000 ... if (!($t.ContainsKey($emailString))) { $t.Add($emailString, $emailString) } My version uses the same $emailString for the key & value, no .NET boxing of $true to an [object] just as a placeholder. The non-null string will evaluate to $true in PowerShell 'if' conditionals, so other code where you check shouldn't change. Your use of '+= @{...}' would be a big no-no in performance sensitive .NET code. You might be allocating a new Hashtable per email just by using the '@{}' syntax, which could be wasting a lot of time. Your approach of breaking up the very large collection into a (relatively small) number of smaller collections is called 'sharding'. You should use the Hashtable constructor that takes a capacity even if you're sharding by 16. Also, @Larold is right, if you're not looking up the email addresses, then use 'New-Object ArrayList 20000' to create a pre-allocated list. Also, the collections grow expenentially (factor of 1.5 or 2 on each 'growth'). The effect of this is that you should be able to reduce how much you pre-allocate by an order of manitude, and if the collections resize once or twice per 'data load' you probably won't notice. I would bet it is the first 10-20 generations of 'growth' that is taking time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to enter a range of Work days in Excel? I wish to set a task in which I say "My task starts on XX, May 2011 and ends after 14 work days" How do I automatically put this date range in an Excel sheet? So, can I put something like: A1Cell: 2 May 2011 A2Cell: =$A1+1 (should be a WorkDay) A3Cell: =$A2+1 (should be a WorkDay) A4Cell: =$A3+1 (should be a WorkDay) A5Cell: =$A4+1 (should be a WorkDay) A6Cell: =$A5+1 (should be a WorkDay, as this is Saturday, it should automatically take it as the next workday) Can something like the above be achieved in Excel? Or if there is a VBA code available for it? What I could get was something like: =IF($A5=(WORKDAY($A5,0)),$A5+1,$A5+3) But it does not seem to work. A: See the formula, adding the number of working days (column A) to today =WORKDAY(TODAY(),A1) A: Also try the WORKDAY.INTL function (if you are in excel2010). Allows you to pick which days are weekends and set specific holidays
{ "language": "en", "url": "https://stackoverflow.com/questions/7523146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Controlling multiple amazon EC2 instances Which class/method to use to start/stop a List of amazon EC2 instances with java API? I only know the List<Instance> A: startInstances takes a StartInstancesRequest, which has a method .setInstanceIds that allows you to attach a list of instance IDs. http://docs.amazonwebservices.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/ec2/AmazonEC2.html#startInstances%28com.amazonaws.services.ec2.model.StartInstancesRequest%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7523149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Optimize Multiple SoundCloud Objects I'm looking to embed multiple SoundCloud objects on my website -- it's the primary content, but it takes way too long to load. SoundCloud's own website doesn't take nearly as much time to load and they have more than 5 objects on a single page. What are some ways I can speed up the SoundCloud objects? A: Define "way too long to load". Is it loading (albeit slowly) or is it not? If you're embedding through SoundCloud, the objects should load in the same speed as when you're on SoundCloud.com itself, except for the data on your webpage, which goes through your webhost, then back to the user's computer. If i don't get your question wrong though, it may be a problem with your webhost's communication speed. Is your webhost a free to use one? Have you checked the upload/download speed before purchasing it? Or is it because some part of your code the embedding is wrong? (If it doesn't load, that is) Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hoogle data on Windows I can install hoogle using cabal install hoogle on Windows, however, when I run hoogle data from MinGW shell, I encounter the following error: $ hoogle data Extracting tarball... gzip: ..\hackage-cabal.tar.gz: No such file or directory hoogle.exe: System command failed: gzip --decompress --force ..\hackage-cabal.ta r.gz How can I install hoogle easily on Windows? A: Make sure you don't have MinGW or Cygwin version's gzip in your path, if you install Windows version Git, you have MinGW installed by default, this will cause your gzip starts in the wrong directory, thus you may see the error: No such file or directory Use the installer version of the Windows compatible binary (all the binaries will be installed within one directory by default), and add the binary to windows path variable. wget: http://sourceforge.net/projects/gnuwin32/files/wget/1.11.4-1/wget-1.11.4-1-setup.exe/download gzip: http://sourceforge.net/projects/gnuwin32/files/gzip/1.3.12-1/gzip-1.3.12-1-setup.exe/download tar: http://sourceforge.net/projects/gnuwin32/files/tar/1.13-1/tar-1.13-1-bin.exe/download A: To further clarify the answers given, what's going on is that hoogle internally is using windows paths while msys is making it see its view of the filesystem, resulting in hoogle being confused. To have this not happen fire up powershell, the windows version of the command line, and run hoogle data from there. You will need to have the GnuWin32 versions of wget, gzip and tar as mentioned by Sawyer. Once you've generated the data you will be able to use hoogle from msys without problem, though if later on you run hoogle data again you will still have to do it from powershell. A: http://gnuwin32.sourceforge.net/packages.html has everything you'll need. I went through this myself last week.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Is it dangerous to include your googlecode password in .git/config? Because the trick with my .netrc file doesn't work (even though it has correct filepermissions), I modified my local .git/config to like like so: [remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = https://<username>:<password>@code.google.com/p/<project>/ I immediately cloned the repo to check if the password would be still included, and it isn't. I also have a mirror hosted at github, if it matters at all. So is it in any way dangerous? A: So is it in any way dangerous? Files in your .git directory are strictly part of your local repository; they don't get pushed to your remote repositories. So you're safe in the sense that you're not publishing your password on the network. On the other hand, any system that requires you to cache your password on your local filesystem means that someone with access to your filesystem can potentially recover your password. Unfortunately, since Google doesn't support repository access over ssh, there's not much you can do about this (well, you can decide to use Github exclusively, which gets you public/private key authentication which is a substantial step up in security). Regarding the use of the .netrc file, the Google Git FAQ says: I put my credentials in .netrc, so why does git still ask me for a password? The C git client always asks for a password if you have a username in the URL. Check your command line and .git/config file and make sure that your code.google.com URLs do not include your username (the part up to the @).
{ "language": "en", "url": "https://stackoverflow.com/questions/7523152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Are there other usages of a protocol other than a delegate? I was just wondering are there other usages of a protocol other than a delegate? I've only seen protocol's been used as delegates but I haven't noticed if it has any other purpose. So are there actual purposes of protocol's other than a delegate? A: You would use it anywhere you want to define a set of shared behavior without imposing a particular inheritance tree. A: From the apple docs: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html Protocols declare methods that can be implemented by any class. Protocols are useful in at least three situations: * *To declare methods that others are expected to implement *To declare the interface to an object while concealing its class *To capture similarities among classes that are not hierarchically related Specifically, as an example, I've also used protocols to implement a provider model where I abstract out complete parts of the system. For example, to decouple my code a bit more, I could create a data provider. I could have a sqlite provider, a file provider etc... A protocol allows me to decouple those. In that case, each of the providers do not inherit from each other but they all implement the same pattern with the internals being different. Think of a protocol as a pattern you conform to - or, a contract if you think of it like an interface. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I print arbitrary values in C? Possible Duplicate: How can we apply a non-vararg function over a va_list? I'm writing a unit test framework in C (see SO for more information, or view the code at GitHub). I want to generate random test cases and throw them at a function, e.g. bool is_odd(int i), bool a_plus_b_equals_c(int a, int b, int c). If all the test cases pass, the framework will print "SUCCESS". If a test case fails, I want the framework to print the offending values, and the framework can't know the types ahead of time (no hard coding). How can I printf() a collection of values with different, arbitrary types? What's worse is that the functions to test may require very complex input. It's not hard to create a random AVL tree, but how can we handle printing that, or an integer, or anything else?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: required file not seen on heroku in jekyll blog This is my dir structure . ├── _layouts │   └── default.html ├── _posts ├── _site │   ├── config.ru │   ├── devart.rb │   └── index.html ├── config.ru ├── devart.rb └── index.html My config.ru require 'devart.rb' run Sinatra::Application When I push this to heroku in the log files I see this error saying devart file is not found during the require. What the heck am I doing wrong?? <internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- devart (LoadError) A: Ruby 1.9.2 no longer has current dir in loadpath. So changed to require './devart.rb' to get it to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Automatically Create Insert Statements to Fill Junction Table in a Pre-Created DB For a simple android app I'm creating as a teaching tool for myself (for using relational dbs/SQL among other things - pardon the simplicity of the question if you will). I'm pre-creating a sqlite db to ship with the application. I'm doing this based on the following SO question. I've got two tables with a many to many relationship and a junction table to define those relationships as follows: CREATE TABLE Names (_id INTEGER PRIMARY KEY, name TEXT ); CREATE TABLE Categories (_id INTEGER PRIMARY KEY, category TEXT ); CREATE TABLE Name_Category (name_id INTEGER, category_id INTEGER, PRIMARY KEY (name_id, category_id), foreign key (name_id) references Names(_id), foreign key (category_id) references Categories(_id) ); I've got sets of insert statements to fill the Names and Categories tables. I'm now faced with the task of filling the junction table. I'm sure that I could create the insert statements by hand by looking up the ids of the names and categories that I want to match, but that seems a bit silly. In order to automatically create the insert statements for the junction table, I imagine that I could create a script based on a set of name and category pairs that will search for the appropriate ids and dump an insert statement. (I came up with this as I was asking the question and will research it. Don't you love it when that happens?) Does anybody have any suggestions for ways to do this? EDIT I added the foreign keys because, as pointed out below, they'll help maintain integrity between the tables. EDIT #2 To solve this, I created a simple Perl script that would take a text file with name - category pairs and dump them out into another file with the appropriate SQL statements. The name - category text file has a format as follows: 'Name' 'Category' The Perl script looks like this: use strict; use warnings; open (my $name_category_pair_file, "<", "name_category.txt") or die "Can't open name_category.txt: $!"; open (my $output_sql_file, ">", "load_name_category_junction_table.sqlite") or die "Can't open load_name_category_junction_table.sqlite: $!"; while (<$name_category_pair_file>) { if (/('[a-zA-Z ]*') ('[a-zA-Z ]*')/) { my $sql_statement = "INSERT INTO Name_Category VALUES ( (SELECT _id FROM Names WHERE name = $1), (SELECT _id FROM Categories WHERE category = $2))\;\n\n"; print $output_sql_file $sql_statement; } } close $name_category_pair_file or die "$name_category_pair_file: $!"; close $output_sql_file or die "$output_sql_file: $!"; A: You can use this insert in your script or code (replacing the strings or using ?): insert into Name_Category values( (select _id from Categories where category='CAT1'), (select _id from Names where name='NAME1')); Also, you can alter the Name_Category table to constraint on the values that can be inserted and/or deleted: CREATE TABLE Name_Category ( name_id INTEGER NOT NULL, category_id INTEGER NOT NULL, PRIMARY KEY (name_id, category_id), foreign key (name_id) references Names(_id), foreign key (category_id) references Categories(_id)); A: create two main tables first and then create a junction table in which primary key of both main tables will be available as foreign key.. Primary key of junction table will be union of primary key of first and second main table. Create trigger now to automatically insert into junction table... Also don't forget to create table with cascade deletion and cascade updatation so that any value updated or deleted in main tables will be automatically reflected in junction table
{ "language": "en", "url": "https://stackoverflow.com/questions/7523166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create AJAX notification using PHP to notify friend request I'm looking to create a AJAX growl or cool AJAX Web 2.0 notification, I know PHP, and I'm looking to notify users when $username accepts friend request then a notification growl in AJAX that notifies that the users has accepted their friend request. A: What you are describing is done through the use of Push technology, which involves more than PHP. In any case, it would be a matter of using your good ol' SQL query for checking the state of the request and giving the info to a polling-kind-of AJAX script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: clustered index on "join" column or on "where" column I have two tables in SQL Server. Table A has two columns: ID and Name. They are both unique. Table B is joined to table A on the Name column. Assuming most of the queries to these tables will be: Select A.Name, B.xyz From A Inner Join B on A.Name = B.Name Where ID = 1 Which column in table A do I want to create a clustered index on? ID to speed up the WHERE or Name to speed up the JOIN? A: I don't think you want a clustered index at all. You want just a regular index. (Unless you expect to read all the data in sequential order.) What you do want is an index on both fields together, with ID first and Name second. So three indexes: ID Primary Name Unique ID, Name Unique The only reason to create the last index is if your database supports index merges. Otherwise you want just the index on ID. A.Name isn't used from the index, A.Name is data, not a search key. You want an index on B.Name. A: The NAME column since it's unique and you are more likely to perform searches/joins on this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Date Time Picker - Setting Opening Date and Time I'm using this nifty little date and time picker [ http://trentrichardson.com/examples/timepicker/ ]. How can I set the date and time for when the picker opens? A: If you're using this on a form, set it from a hidden input. $(document).ready(function () { $("#Date").datetimepicker({ ampm: true }); var date = new Date( Date.parse( $('#DatePicker').val(), "mm/dd/yyyy hh:MM tt" ) ); $('#Date').datetimepicker('setDate', date); }); HTML Form: <input type="hidden" id="DatePicker" /> <input type="text" id="DatePicker" value="fromyourdatabase" /> A: Try this $('#dtpkr').datetimepicker(); Then add $('#dtpkr').datetimepicker('setDate', (new Date())); This will give you the current date and time A: You could pass a Date object to the setDate method. $('#datetimepicker').datetimepicker().click(function() { $(this).datetimepicker('setDate',new Date(2011, 11, 20, 8, 30)); }); See it in action: http://jsfiddle.net/william/Rkewu/1/. A: Try setting the value attribute inside the input element like this: <input id="example1" value="05/05/2011" /> A: Just focus it. $('#totTb').datetimepicker({ timeFormat: 'HH:mm', timeSuffix: " Z" }).focus(function () { $('#totTb').datetimepicker('setDate', d) });
{ "language": "en", "url": "https://stackoverflow.com/questions/7523175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do i restrict the list in a referenced model in ATK4 I have a model called Task defined like this (fields not relevent to question removed) <?php class Model_Task extends Model_Table { public $entity_code='vscrum_task'; public $table_alias='tk'; function init(){ parent::init(); // debug causes error in Ajax in ATK v4.1.1 // $this->debug(true); $this->addField('id')->system(true)->visible(false); $this->addField('task_desc')->mandatory(true)->visible(true); $this->addField('tasktype_id')->mandatory(true)->refModel('Model_TaskType'); $this->addField('team_id')->system(true)->visible(false); and the refModel tasktype is defined like this (fields not relevent to question removed) <?php class Model_TaskType extends Model_Table { public $entity_code='vscrum_tasktype'; public $table_alias='ty'; function init(){ parent::init(); $this->addField('id')->mandatory(true); $this->addField('name')->mandatory(true); $this->addField('team_id'); } } I have a CRUD which is based on task and is now (thanks to help from Jancha and Romans on stackoverflow) is working fine. I want to limit the options in the drop down for TaskType to only those tasktypes defined for the user's team. I tried putting an addCondition in the TaskType Model referencing a session variable i had previously memorized $this->addCondition('team_id',$p->api->recall('team_id')); and also using a direct call to a value for the logged in use $this->addCondition('team_id',$p->api->auth->get('team_id')); but this results in showing the Tasktype fine in the Grid but leaves it empty for both Edit and Add in the Ajax dialog. If i remove the addCondition line from the TaskType Model, it shows all values in the list but i will always want this restricted to a subset. As this is the referred Model and not the Model that the CRUD is based on, any suggestions on how i get this to work as expected ? I tried Roman's suggestion of having a model which is the TaskType and a new model extended from that which is the TaskType_Team with the addCondition in it like this class Model_TaskType_Team extends Model_TaskType { function init(){ parent::init(); $this->addCondition('team_id',$p->api->auth->get('team_id')); } for which i needed to create a subdirectory undel Model called TaskType otherwise it didnt find the new Model but the end result is the same. I think this is related to another issue i previously had where the Ajax dialog loses access to $p->api and so doesnt display the restriction (and this is why it works fine for the grid on the same page as that isnt in an ajax dialog but i dont want to use a stickyGet to resolve this for security (dont want to be able to modify the URL to see other teams data) and session variables ($p->auth->memorise and $p->auth->recall) also dont seem work in this case - any further suggestions ? A: Remember that you can extend your models like that. In fact, this is very often used in larger projects. class Model_TaskType_Team extends Model_TaskType { function init(){ parent::init(); $this->addCondition('team_id',$this->api->auth->get('team_id')); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to check if jQuery has already been attached to an html page? I have some jQuery which will be put on multiple different HTML pages which I have no clue whether they will have the jQuery Library attached or not. I would like to make it so that it does not load the library if it does already exist on the page so that it can be faster, but I can't figure out if there is a way to check for whether the library already is attached to the page. Is there a way? A: From HTML5 Boilerplate: <script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.4.min.js"><\/script>')</script> Loads a local jQuery file if it hasn't already been loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Specify the table type/storage engine in Doctrine 2 So how can one specify the storage engine to use for a given entity in Doctrine 2? I'm creating a table that needs a full text index and only the MyISAM storage engine supports full text indexing in MySQL. As a side: it looks like Doctrine 2 doesn't support full text indexing out of the box? Nor full text searches? Is that correct? A: Update: See the comment about adding "@Table(name="table_name",options={"engine"="MyISAM"})" , it is the better answer. ======= Original Below =========== This is untested code aimed to help you get to an answer, you will need to read a lot of Doctrine2 code to figure out what you want though. I spent about 30mins reading code and couldnt find a way to push the $options array through the ORM layer to this DBAL layer function. check out Doctrine/DBAL/Platforms/MySQLPlatform.php 427 // get the type of the table 428 if (isset($options['engine'])) { 429 $optionStrings[] = 'ENGINE = ' . $options['engine']; 430 } else { 431 // default to innodb 432 $optionStrings[] = 'ENGINE = InnoDB'; 433 } try hard coding what engine want in there. It will almost certainly break stuff though (eg, foreign keys dont work in MyISAM) A: If you're using doctrine2 migrations .. $table = $schema->createTable('user'); $table->addColumn('id', 'integer'); $table->addOption('engine' , 'MyISAM'); $table->setPrimaryKey(array('id')); A: I'm two years too late, but knowing this is important since it isn't documented for some reason, we have been struggling to achieve this but this is the solution /** * ReportData * * @ORM\Table(name="reports_report_data",options={"engine":"MyISAM"}) * @ORM\Entity(repositoryClass="Jac\ReportGeneratorBundle\Entity\ReportDataRepository") */ class ReportData {
{ "language": "en", "url": "https://stackoverflow.com/questions/7523182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: ContextMenu ItemsSource binding problem There is a problem with ContextMenu with wpf usercontrol. I wrote a usercontrol, and this usercontrol have a windowsformhost, and i want to handle the right button contextmenu of the windows control with wpf context menu. So i send a message to wpf user control to call contextMenu.IsOpen = true, and i fill the contextMenu.ItemsSourceProperty a binding. But when i call the contextmenu.IsOpen = true, The contextMenu.Items.Count == 0, how can i solve this problem? Here is my code: <UserControl x:Class="ControlEase.Inspec.Drawing.CanvasEditorView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ControlEase.Inspec.Drawing" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <UserControl.Resources> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Header" Value="{Binding Name}"/> <Setter Property="Command" Value="{Binding Command}"/> </Style> <ContextMenu x:Key="graphicsMenu" ItemsSource="{Binding Commands}"/> </UserControl.Resources> <UserControl.ContextMenu> <ContextMenu ContextMenu="{StaticResource graphicsMenu}"/> </UserControl.ContextMenu> <Grid> <local:InitializedUserControl local:LoaderHelper.InitializedCommand="{Binding OpenCommand}" > <WindowsFormsHost x:Name="windowsHost" local:CanvasContainerExtensions.Canvas="{Binding Model}"/> <EventCommander.Mappings> <CommandEvent Event="GotFocus" Command="{Binding ActiveCommand}"/> <CommandEvent Event="LostFocus" Command="{Binding DeActiveCommand}"/> </EventCommander.Mappings> </local:InitializedUserControl> </Grid> And when i get the message in the xaml.cs, i called ContextMenu.IsOpen = true. The ContextMenu != null, but ContextMenu.Itmes.Count == 0, and there is no binding error in the output pad. Please help. A: Here, you're setting the ContextMenu property of the ContextMenu: <ContextMenu ContextMenu="{StaticResource graphicsMenu}"/> As a result, you'll have an empty outer ContextMenu, with a ContextMenu of its own that contains the items you need. The outer context menu won't ever display because it has nothing in it, but if it did and it rendered large enough, you could right-click it to see the inner context menu, which is where your menu items would be hiding away. The ContextMenu resource is redundant. You could just have this: <UserControl.ContextMenu> <ContextMenu ItemsSource="{Binding Commands}"/> </UserControl.ContextMenu>
{ "language": "en", "url": "https://stackoverflow.com/questions/7523183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing a elements className makes it unfindable using $(className).each() I have some JQuery code that converts all HTML elements of a specific class to & from textarea elements. My Problem: I use JQuery(.addClass()) to change an elements class from "updatable" to "updatable P". But when I go to search for all the elements that have the class "updatable" (using the function $(".updatable").each()) it does'nt find any elements when it should find 3. What am I doing wrong to make this happen? It seems that after I change an elements classI am unable to identify/find that element by its class(using JQuery) again. <html> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript"> <!-- var STATE = 1; function Toggle() { if (STATE==1) { convertToUpdatable(); STATE = 0; } else { convertToStatic(); STATE = 1; } } function getTitleName( ele ) { try { return ele.className.split(" ")[1]; } catch (ex) { return "undefined"; } } function convertToUpdatable() { // Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements // and store their HTML element type in the class attribute // EG: Before: <p class="updatable Paragraph1"/> Hello this is some text 1 </p> // After : <p class='updatableElementTitle'>Paragraph1</p><textarea class="updatable Paragraph1 p"/> Hello this is some text 1 </textarea> $(".updatable").each(function() { var title = getTitleName( this ); $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea>"+$(this).text() +"</textarea>"); $(this).addClass( this.nodeName ); alert( this.className ); }); } function convertToStatic() { // Post: Find all HTML elements (with the class 'updatable'), check to see if they are part of another class aswell // (which will be their original HTML element type) & convert the element back to that original HTML element type // PROBLEM OCCURS HERE: after I have changed an elements className in the convertToUpdatable() I can no // longer find any HTML elements that have the className updatable using $(".updatable").each() $(".updatable").each(function() { alert("Loop"); // Determine elements original HTML(node) type try { var type = this.className.split(" "); type = (type[ type.length-1 ]).toLowerCase(); alert(type); } catch (ex) { alert("Updatable element had no type defined in class attribute"); return; } // Convert element back to original HTML type $(this).replaceWith( type +$(this).text() + type ); // Remove elements type from its className (remove " P" from "updatable Paragraph1 P") $(this).removeClass( type ); alert( this.className ); }); // Delete all elements with the class 'updatableElementTitle' $(".updatableElementTitle").remove(); } --> </script> </head> <body> <p class="updatable Paragraph1"/> Hello this is some text 1 </p> <b class="updatable Paragraph2"/> Hello this is some text 2 </b> <i class="updatable Paragraph3"/> Hello this is some text 3 </i> <input id="MyButton" type="button" value="Click me!" onclick="Toggle();" /> </body> </html> A: You are using replaceWith which (according to the spec) completely removes all content and replaces it with the new content. After you've replaced the content there are no more nodes with the updatable class, so you won't ever find them again. Try replacing $(this).addClass( this.nodeName ); with $(this).addClass('updatable');. A: .replaceWith() destroys the existing element. Thus, you can no longer use this after you've done the replaceWith() in the loop because that DOM element is no longer the element that's in your document (it's the old one that has been removed and will be garbage collected as soon as your function exits). Since you're specifying the HTML for the new tag, I would suggest you just put the new class name in the HTML you pass to replaceWith(). Further, the alert you have to check the className is checking the old DOM element, not the new DOM element. Remember, this points to the old DOM name, not the one you replaced it with. You could do so by changing this: $(".updatable").each(function() { var title = getTitleName( this ); $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea>"+$(this).text() +"</textarea>"); $(this).addClass( this.nodeName ); alert( this.className ); }); } to this: $(".updatable").each(function() { var title = getTitleName( this ); $(this).replaceWith("<p class='updatableElementTitle " + this.nodeName + "'>" + title + "</p><textarea>"+$(this).text() +"</textarea>"); }); } Although, I don't understand why you're adding the nodeName as a class?
{ "language": "en", "url": "https://stackoverflow.com/questions/7523188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concurrent Updates in Oracle: Locking or not? I'm confused. I'm reading about MVCC in Oracle. I thought MVCC meant no locks. But, I read somewhere else that all UPDATEs do automatic locking, regardless of the isolation level. Can someone explain what happens during an Oracle update? And what happens when multiple read committed transactions try to do a concurrent update t set c = c + 1 where id = 3. What's the result, given c = 1 before either of the transactions, and what's going on with the locks and SCN? Begin T1 Begin T2 T1: update t set c = c + 1 where id = 3 T2: update t set c = c + 1 where id = 3 Commit T1 Commit T2 A: You're right, this will lock the row regardless of the isolation level. With MVCC you can get consistent reads with no locks, but you still need locks when writing. The second transaction will wait for the first one to finish (eg: COMMIT or ROLLBACK) before attempting to do anything. So in this case the cursor on T2 would "hang" on the update, waiting for T1 to finish. You'll get a new SCN after T1 commits and another after T2 commits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to setup sysroot in setup.py for cython I am compiling a simple cython example under mac OSX 10.7. The compiler keeps using -isysroot /Developer/SDKs/MacOSX10.6.sdk .... I suppose 10.7.sdk will be used instead. Why setup.py can not figure out which sdk to use? Any comments? Thanks A: The cpython installation assumes an older version of xcode on MacOSX 10.6. If you need to use SDK for 10.7 from a newer version of Xcode (4.3.3), you will need to do export CFLAGS=-sysroot,/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk export LDFLAGS=-L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk/usr/lib because you execute python setup.py
{ "language": "en", "url": "https://stackoverflow.com/questions/7523193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to store camera captured image in SQLite Database in my application? In my application i want to capture the image from secondary camera and store that photos into my SQLite data base not in SD card.Please any one help me how to do that with some sample source code A: How do you think a database system called SQLite, emphasis on the Lite, would handle 50 pictures at 2.5mb a piece? That's a 125Mb database, not including the other data. Most of my full blown MS SQL databases that back websites haven't reached that size yet. It would be in your best interest to store on the SD card :). If this still does not deter you, then look at the blob datatype in SQLite. A: You can save camera captured image into SQLitedatabase in this way.. public class CamActivity extends Activity { byte[] byteArray; private static final int CAMERA_REQUEST = 1888; protected static final int TAKE_PHOTO_CODE = 0; public ImageView imageView; private DBAdapter db; byte [] imgbyte; EditText txtView ; String name; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); db=new DBAdapter(CamActivity.this); db.open(); this.imageView = (ImageView)this.findViewById(R.id.imageView1); txtView=(EditText)findViewById(R.id.editText1); Button B = (Button) this.findViewById(R.id.camera); B.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); // cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,getImageUri()); startActivityForResult(cameraIntent,CAMERA_REQUEST ); } }); Button save = (Button)findViewById(R.id.saving); save.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { name=txtView.getText().toString(); try { db.insertImageDetails(byteArray,name); } catch (Exception e) { e.printStackTrace(); } //mySQLiteAdapter.close(); Toast.makeText(getApplicationContext(), "processing", Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "image saved", Toast.LENGTH_SHORT).show(); }}); Button G = (Button) this.findViewById(R.id.get); G.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent= new Intent(CamActivity.this,SecondActivity.class); startActivity(intent); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { //final byte[] byteArray; if (requestCode == CAMERA_REQUEST) { Bitmap photo = (Bitmap) data.getExtras().get("data"); //imageView.setImageBitmap(photo); ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.PNG, 100, stream); byteArray = stream.toByteArray(); System.out.println(byteArray); Toast.makeText(getApplicationContext(), byteArray.toString(), Toast.LENGTH_SHORT).show(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7523199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python shelve ... bsddb deprecated ... how to get shelve to use another database? I have an app developed in python 2.7.2 on OS X. I use the module shelve and seems to default to bsddb on the mac. The program won't run on a Windows 7 machine with ActiveState python 2.7 because the module bsddb is not present and is not in ActiveState's package manager (pypm). ActiveState's documentation says deprecated at v 2.6. I guess it tries bdddb because the OS X python which created the DB defaults to bsddb. When I delete the shelve database and run it on Windows, it happily uses some other underlying database. The Mac's python is also happy. So I think I should enforce the use of a non-bdsdb backend for shelve. Like the gdbm module. But I can't work out how to do that. A: You can set the type of db created by setting anydbm._defaultmod before calling shelve.open. This works for Python 2.6 (and maybe for 2.7?), but since anydbm._defaultmod is a private variable, be aware that this is a hack. anydbm._defaultmod=__import__('gdbm') For example: import anydbm import whichdb import contextlib anydbm._defaultmod=__import__('gdbm') filename='/tmp/shelf.dat' with contextlib.closing(shelve.open(filename)) as f: pass result=whichdb.whichdb(filename) print(result) # gdbm A: I seemed to have asked the wrong question. When building the windows exe, py2exe was not including an dbm modules (it couldn't infer this dependency), so at runtime python in desperation tried to find the bdbm module. this script setup.py includes a module which makes the py2exe version behave like the version run normally. It includes a dbm-clone module (I'm only storing ten simple dictionaries so the basic dumbdbm module is good enough from distutils.core import setup import py2exe, sys, os from glob import glob sys.argv.append('py2exe') data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] setup( data_files=data_files, windows = ["cashflowSim.py"], options={ "py2exe":{"includes":["dumbdbm"]}}, zipfile = None )
{ "language": "en", "url": "https://stackoverflow.com/questions/7523205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Redirection from a static method Symfony2? static public function check( $securityContext) { $user = $securityContext->getToken()->getUser(); if(is_object($user) && [...]) return **$this**->redirect(**$this**->generateUrl('route_recruteur_monespace')); return $user->getRecruteur(); } I tried with new Controller()-> but it doesn't work, so how can i call redirect() from a static method. thanks. A: You could pass the services required to the static method use Symfony\Component\HttpFoundation\RedirectResponse; class Foo { static public function check($securityContext, $router) { $user = $securityContext->getToken()->getUser(); // ... return new RedirectResponse($router->generate('route_name')); } } You can then call it in your controller Foo::check($this->get('security.context'), $this->get('router'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7523212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Serializing Tree into nested list using python I have a binary tree class like this: class BinaryTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right Now I'm facing a task to serialize this structure in to a nested list. BTW, I have a left-to-right traversal function in mind: def binary_tree(tree): if tree: for node_data in binary_tree(tree.left): yield node_data for node_data in binary_tree(tree.right): yield node_data Or there is a general way to serialize it into mixed nested structure? For example, {[]}, or [{}]? A: as a method of BinaryTree: def to_dict(self): data = self.data left = self.left if left is not None: left = left.to_dict() right = self.right if right is not None: right = right.to_dict() return {'data':data, 'left':left, 'right':right} and as a class method of BinaryTree: def from_dict(cls, D): data = D['data'] left = D['left'] if left is not None: left = cls.from_dict(left) right = D['right'] if right is not None: right = cls.from_dict(right) return cls(data, left, right)
{ "language": "en", "url": "https://stackoverflow.com/questions/7523215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating image with new frame - internet explorer displaying partial image At this URL, you can see an image that is being loaded with jQuery: http://projects.kleelof.com/dtcapture/ As soon as the image is loaded, the script loads it again. Right now it is a static image. But when the full app is running, it displays different images. Anyway...the problem... In Firefox and Chrome, the previous image remains until the new one is loaded. However, in IE, it removes the last image and fills in the space with the new image as it downloads. So you get this black box that is slowly filled with the image. Any ideas how to get IE to replace the current image after the new image is downloaded? lee A: The flow you want to achieve is: * *Load a new image. *When the new image is loaded * *Remove the old image *Make a request for a new image (loop) Here is a sample that does that: http://jsfiddle.net/933hg/ A: You can try the onLoad event. Create the image in a hidden div, then attach an onLoad event to it. Once the event fires move the image into position. But be sure to read img onload doesn't work well in IE7
{ "language": "en", "url": "https://stackoverflow.com/questions/7523216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect encoding of a string in C/C++ Given a string in form of a pointer to a array of bytes (chars), how can I detect the encoding of the string in C/C++ (I used visual studio 2008)?? I did a search but most of samples are done in C#. Thanks A: It's not an easy problem to solve, and generally relies on heuristics to take a best guess at what the input encoding is, which can be tripped up by relatively innocuous inputs - for example, take a look at this Wikipedia article and The Notepad file encoding Redux for more details. If you're looking for a Windows-only solution with minimal dependencies, you can look at using a combination of IsTextUnicode and MLang's DetectInputCodePage to attempt character set detection. If you are looking for portability, but don't mind taking on a fairly large dependency in the form of ICU then you can make use of it's character set detection routines to achieve the same thing in a portable manner. A: I have written a small C++ library for detecting text file encoding. It uses Qt, but it can be just as easily implemented using just the standard library. It operates by measuring symbol occurrence statistics and comparing it to pre-computed reference values in different encodings and languages. As a result, it not only detects encoding but also the language of the text. The downside is that pre-computed statistics must be provided for the target language to detect this language properly. https://github.com/VioletGiraffe/text-encoding-detector A: Assuming you know the length of the input array, you can make the following guesses: * *First, check to see if the first few bytes match any well know byte order marks (BOM) for Unicode. If they do, you're done! *Next, search for '\0' before the last byte. If you find one, you might be dealing with UTF-16 or UTF-32. If you find multiple consecutive '\0's, it's probably UTF-32. *If any character is from 0x80 to 0xff, it's certainly not ASCII or UTF-7. If you are restricting your input to some variant of Unicode, you can assume it's UTF-8. Otherwise, you have to do some guessing to determine which multi-byte character set it is. That will not be fun. *At this point it is either: ASCII, UTF-7, Base64, or ranges of UTF-16 or UTF-32 that just happen to not use the top bit and do not have any null characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Data structure to store 2D points clustered near the origin? I need to use a spatial 2d map for my application. The map usually contains small amount of values in (-200, -200) - (200, 200) rectangle, most of them around (0, 0). I thought of using hash map but then I need a hash function. I thought of x * 200 + y but then adding (0, 0) and (1, 0) will require 800 bytes for the hash table only, and memory is a problem in my application. The map is immutable after initial setup so insertion time isn't a matter, but there is a lot of access (about 600 a second) and the target CPU isn't really fast. What are the general memory/access time trade-offs between hash map and ordinary map(I believe RB-Tree in stl) in small areas? what is a good hash function for small areas? A: I think that there are a few things that I need to explain in a bit more detail to answer your question. For starters, there is a strong distinction between a hash function as its typically used in a program and the number of buckets used in a hash table. In most implementations of a hash function, the hash function is some mapping from objects to integers. The hash table is then free to pick any number of buckets it wants, then maps back from the integers to those buckets. Commonly, this is done by taking the hash code and then modding it by the number of buckets. This means that if you want to store points in a hash table, you don't need to worry about how large the values that your hash function produces are. For example, if the hash table has only three buckets and you produce objects with hash codes 0 and 1,000,000,000, then the first object would hash to the zeroth bucket and the second object would hash to the 1,000,000,000 % 3 = 1st bucket. You wouldn't need 1,000,000,000 buckets. Consequently, you shouldn't worry about picking a hash function like x * 200 + y, since unless your hash table is implemented very oddly you don't need to worry about space usage. If you are creating a hash table in a way where you will be inserting only once and then spending a lot of time doing accesses, you may want to look into perfect hash functions and perfect hash tables. These are data structures that work by trying to find a hash function for the set of points that you're storing such that no collisions ever occur. They take (expected) O(n) time to create, and can do lookups in worst-case O(1) time. Barring the overhead from computing the hash function, this is the fastest way to look up points in space. If you were just to dump everything in a tree-based map like most implementations of std::map, though, you should be perfectly fine. With at most 400x400 = 160,000 points, the time required to look up a point would be about lg 160,000 &approx; 18 lookups. This is unlikely to be a bottleneck in any application, though if you really need all the performance you can get the aforementioned perfect hash table is likely to be the best option. However, both of these solutions only work if the queries you are interested in are of the form "does point p exist in the set or not?" If you want to do more complex geometric queries like nearest-neighbor lookups or finding all the points in a bounding box, you may want to look into more complex data structures like the k-d tree, which supports extremely fast (O(log n)) lookups and fast nearest-neighbor and range searches. Hope this helps! A: Slightly confused by your terminology. The "map" objects in the standard library are implementations of associative arrays (either via hash tables or binary search trees). If you're doing 2D spatial processing and are looking to implement a search structure, there are many dedicated data objects - i.e. quadtrees and k-d trees. Edit: For a few ideas on implementations, perhaps check: https://stackoverflow.com/questions/1402014/kdtree-implementation-c. Honestly - the data structures aren't that complex - I've always rolled my own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to choose objects for your android application? I am new to Android but not to programming. I have taken C++ in school and we have been taught how to create objects, but not how to build robust programs using multiple objects. So you can see that using java to build Android apps leaves me with questions..... * *thinking like an object oriented programmer, do i just shop through a list of classes until i find ones that i think would suite my app *is there a definite method of choosing the best classes for your project *do i find an app similar to the one i am trying to create and try to find what classes they used any thoughts appreciated!!!!!! A: I'd recommend you start with Tutorials and also read about Application Fundamentals - they should get you started. Also browsing Classes is useful if you like wading through lots of technical docs (I do). Those three links are definitely worth looking at. A: The best way to learn (for me, at least) is by making small incremental changes to an example so I can how all the various elements of it work. Download the examples (listed here) - but accessible from your AVD and SDK manager tool from within Eclipse (Window -> Android SDK and AVD Manager). Start by modifying those examples. They are the best possible examples you can get for much of what you will want to do. A: Well first when building Android applications you need to: * *Figure out what your application will be, and how it would work. *Next you would need to find out how you will implement the android classes. *i would recommend first reading a book on Android development. One that really helped me and made me an advance developer was CommonsWare *You should really get these books. When you finish you will be well on your way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7523224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way to get list of photos with me and a friend tagged in them? I'm doing this fql: SELECT object_id, pid, src_big, src_big_height, src_big_width, src, src_height, src_width FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject= [me_uid]) AND pid IN (SELECT pid FROM photo_tag WHERE subject= [friend_uid] ) limit 0, 20 This works fine until I use 2 users ids who have thousands of photos with hundreds of them tagged with both uids. In this scenario, FB returns a 500 error: "Error loading script", error code 1 I need to incrementally retrieve data as a user pages down. Getting All photos/tags for both users and then comparing the 2 full lists is not acceptable for this app. Any thoughts? A: Maybe optimize it like so: SELECT object_id FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject = [me_uid] AND pid IN (SELECT pid FROM photo_tag WHERE subject [friend_uid]) LIMIT 0, 20) hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7523225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Fortran increase dynamic array size in function I need a variable size array in Fortran. In C++ I would use vector. So I have a function like integer function append(n, array, value) integer, pointer, dimension(:) :: array integer, pointer, dimension(:) :: tmp_arr integer n if (size(array) .eq. n) then allocate(tmp_arr(2*size(array))) tmp_arr(1:size(array)) = array deallocate(array) array => tmp_arr end if n = n + 1 array(n) = value append = n end function that works fine if I use it the way integer pos, val pos = append(n, array, val) However, if I would like to use it the way integer i,j,n ! i,j<n array(i) = append(n, array, array(j)) with gfortran this does not work. It compiles, but segfaults. The problem seems to be that gfortran makes addresses out of array(i) and array(j), sends the latter to the function append, and then when the address of array(j) is accessed and the one of array(i) written, the address space has been deallocated. What I would like is that the value of array(j) is put on the stack (not the address) and then used in the function and after the function has finished the uptodate address of array(i) is looked up and the result of the function saved to it. I am pretty sure gcc would do it the way I want, why is gfortran so mean? Is there any way in Fortran to make a robust (meaning the array(j) = ... example works) function or data type to have a c++ stl vector like behaviour? Conclusion: I eventually introduced temporary variables integer tmp_val tmp_val = value ... array(n) = tmp_val so at least the method can be called as pos = append(n, array, array(j)) array(i) = pos and hope that other/future developers on the project won't try to 'optimize' the two lines to eliminate the necessity of 'pos'. Thanks for the answers and comments. A: OK, the problem is that you cannot deallocate and re-allocate the array that you are assigning a function value to. You are correct about the cause of your problem (arguments passed by reference and not by value as it is in C). Since you deallocate the array inside the function body, the assignment to that array becomes invalid, leading to segfault. This is not a gfortran issue, tried it with ifort and pgf90, all of them report the same problem. This works for me: PROGRAM dynamic_size INTEGER,DIMENSION(:),ALLOCATABLE :: array ALLOCATE(array(10)) array=(/1,2,5,7,4,3,6,5,6,7/) WRITE(*,*)SIZE(array) CALL resize_array WRITE(*,*)size(array) CONTAINS SUBROUTINE resize_array INTEGER,DIMENSION(:),ALLOCATABLE :: tmp_arr ALLOCATE(tmp_arr(2*SIZE(array))) tmp_arr(1:SIZE(array))=array DEALLOCATE(array) ALLOCATE(array(size(tmp_arr))) array=tmp_arr ENDSUBROUTINE resize_array ENDPROGRAM dynamic_size A: Thank you a lot janneb.It was very helpful your comment. Only a few change I have made was to omit the deallocate(array) . There was'nt any erro omitting this line in my code. This change is specially helpful if you need to put it into a loop and you don't allocated array before the loop. My specific case follows below (look that I don't allocate x_all before or into the loop): begin program test integer,allocatable::x_all(:),tmp_arr(:) integer,allocatable::x_tmp(:) integer::N allocate(x_tmp(2*N)) (...) i=1 do while(logical test) ... x_tmp(i)=some calculus i=i+1 ... end do i=i-1 allocate( tmp_arr( 1:(i+size(x_all) ) ) ) tmp_arr(1:size(x_all))=x_all tmp_arr(size(x_all)+1:)=xtemp call MOVE_ALLOC(tmp_arr,x_all) ... end program A: The answer by IRO-bot is the correct approach for Fortran 90. If you can limit yourself to compilers that support the Fortran 2003 MOVE_ALLOC intrinsic (included in gfortran since the 4.2 release), you can avoid one of the copies. That is, increasing the size of an array by a factor of 2 can be written as allocate(tmp_arr(2*size(array))) tmp_arr(1:size(array)) = array deallocate(array) move_alloc(tmp_arr, array) ! tmp_arr is now deallocated
{ "language": "en", "url": "https://stackoverflow.com/questions/7523228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }