text
stringlengths
8
267k
meta
dict
Q: Glassfish + SqlServer + Liferay Bug I keep getting errors related to connection pool when I try to deploy liferay. My connection pool seems to be setup correctly. What could it be? A: If you are configuring Glassfish with SqlServer using the javax.sql.ConnectionPoolDataSource the DataSource Classname should be com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource and not what Glassfish provides: com.microsoft.sqlserver.jdbc.ConnectionPoolSQLServerDataSource Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent users from editing/deleting cases' activity history records I'm preparing an org for a call center and the customer doesn't want the agents to be editing or deleting a cases' activity history records (for instance, if an email was sent, that record shouldn't be deleted from the history). Is there a way to remove the edit/delete buttons on these records? Or is there a way that I can prevent these from being edited/deleted, maybe using a trigger? A: Remove the Edit rights from the group that the agents belong to (remove "Manage Content Permissions"). This link may help: https://login.salesforce.com/help/doc/en/content_workspace_perm.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7519730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to ensure location updates continue indefinitely? The app is handling location updates and sending the location back to a server. The app does not turn the location updates off. This is for devices permanently plugged into power, so battery is not an issue. By design, will the location updates continue indefinitely, or will Android stop sending them at some point, for example if the app is pushed out of RAM? If the location updates do stop, how do I request them in such a way that they will continue indefinitely? A: Yes, if phone is not asleep, then user processes will run. Register a LocationListener in a Service so that it's triggered when location changes. Even if your service is not running, system will start it and execute the registered method. You should definitelly read the Deep Dive into Location blog for all angles of location handling in Android. A: It depends on how you are running the app. As long as the app maintains focus, unless something catastrophic happens, it will continue to send updates. If the app loses focus, then you might run into issues, depending on how you implement the location updating. Either way, be sure to * *Create an ASyncTask[docs] to handle the actual sending of updates, otherwise your app will be killed *If the app can lose focus, you can create a Service, and detach it from your application to keep it running in the background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zend Form - setting defaults for multi checkbox The HTML for my checkbox list is like this: <dt id="list-label"> <label for="list" class="optional"> Choose which feeds to include in the mix </label> </dt> <dd id="list-element"> <label for="list-1"> <input type="checkbox" name="list[]" id="list-1" value="1">Marko Polo </label> <br /> <label for="list-2"> <input type="checkbox" name="list[]" id="list-2" value="2">Jeano Polo </label> </dd> I'm trying to pre-populate them with selected=selected for those with values of 1 from the database. I thought the following would work: $form->setDefaults(array('list-1'=>1,'list-2'=>1)); But it doesn't. Is there a way to do this? EDIT Here is my form class code: $model = new Admin_Model_Db(); $model->setTableName('graduates'); $gradA = $model->getAllGraduates(); foreach ($gradA as $grad){ if (!empty($grad['twitter'])){ $twitter[$grad['id']] = $grad['firstname'] . ' ' . $grad['lastname']; } } $list = $this->CreateElement('multicheckbox', 'list') ->setLabel('Choose which feeds to include in the mix') ->setRequired(false) ->setMultiOptions($twitter); A: Try this: $all_record = array('k1'=>'v1', 'k2'=>'v2'); $checked_values = aray('k1'); $checkbox = new Zend_Form_Element_MultiCheckbox('id', array('multiOptions' => $all_records) ); $checkbox->setValue($checked_values); // ... $this->addElement($checkbox); $this is Zend_Form of course :) A: Your form element name is list[], this means that when your boxes are checked and you get their values this way : $list = $form->getElement('list')->getValue(); $list's value will be array(1,2) So logically this should work : $form->setDefaults(array('list'=>array(1,2)); //if not, try with strings instead of integers array('1','2')
{ "language": "en", "url": "https://stackoverflow.com/questions/7519740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why bit shifting? I was recently looking at a config file that was saving some cryptic values. I happened to have the source available, so I took a look at what it was doing, and it was saving a bunch of different values and bit shifting them into each other. It mystified me why someone would do that. My question, then, is: is there an obvious advantage to storing numeric data in this way? I can see how it might make for a slightly smaller value to store, byte-wise, but it seems like a lot of work to save a couple of bytes of storage. It also seems like it would be significantly slower. The other possibility that occurred to me is that is was used for obfuscation purposes. is this a common usage of bit shifting? A: Bit shifting seems more common in systems-level languages like C, C++ and assembly, but I've seen it here and there in C# too. It's not often used so much to save space, though, as it is for one (or both) of two typical reasons: * *You're talking to an existing system (or using an established protocol, or generating a file in a known format) that requires stuff to be very precisely laid out; and/or *The combination of bits comprise a value that is itself useful for testing. Anyone who uses it in a high-level language solely to save space or obfuscate their code is almost always prematurely optimizing (and/or is an idiot). The space savings rarely justify the added complexity, and bit shifts really aren't complex enough to stop someone determined to understand your code. A: I have a project that stores day/hour matrix of available hours during one week. So it has 24x7 values that have to be stored somehow. I chose to store it as 7 ints, so each day is represented with one integer, and each hour in it as one bit. Just an example where it can be useful. A: This is one of the common usages of bit shifting. There are several benefit: 1) Bit-shift operations are fast. 2) You can store multiple flags in a single value. If you have an app that has several features, but you only want certain (configurable) ones enabled, you could do something like: [Flags] public enum Features { Profile = 1, Messaging = 1 << 1, Signing = 1 << 2, Advanced = 1 << 3 } And your single value to enable Messaging and Advanced would be: (1 << 1) + (1 << 3) = 2 + 16 = 18 <add name="EnabledFeatures" value="18" /> And then to figure out if a given feature is enabled, you just perform some simple bitwise math: var AdvancedEnabled = EnabledFeatures & Features.Advanced == Features.Advanced; A: Sometimes (especially in older Windows programming), there will be information encoded in "high order" and "low order" bits of a value... and it's sometimes necessary to shift to get the information out. I'm not 100% sure on the reasons behind that, aside from it might make it convenient to return a 64-bit value with two 32-bit values encoded in it (so you can handle it with a single return value from a method call). I agree with your assertions about needless complexity though, I don't see a lot of applications outside of really heavy number-crunching/cryptography stuff where this would be necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: PDF Add Text and Flatten I'm developing a web application that displays PDFs and allows users to order copies of the documents. We want to add text, such as "unpaid" or "sample", on the fly when the PDF is displayed. I have accomplished this using itextsharp. However, the page images are easily separated from the watermark text and extracted using a variety of freeware programs. How can I add the watermark to the pages in the PDF, but flatten the page images and watermark together so that the watermark becomes part of the pdf page image, thereby preventing the watermark from being removed (unless the person wants to use photoshop)? A: If I were you I would go down a different path. Using iTextSharp (or another library) extract each page of a given document to a folder. Then use some program (Ghostscript, Photoshop, maybe GIMP) that you can batch and convert each page to an image. Then write your overlay text onto the images. Finally use iTextSharp to combine all of the images in each folder back into a PDF. I know this sounds like a pain but you should only have to do this once per document I assume. If you don't want to go down this route, let me get you going on what you need to do to extract images. Much of the code below comes from this post. At the end of the code I'm saving the images to the desktop. Since you've got raw bytes so you could also easily pump those into a System.Drawing.Image object and write them back into a new PdfWriter object which is sounds like you are familiar with. Below is a full working WinForms app targetting iTextSharp 5.1.1.0 Option Explicit On Option Strict On Imports iTextSharp.text Imports iTextSharp.text.pdf Imports System.IO Imports System.Runtime.InteropServices Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ''//File to process Dim InputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SampleImage.pdf") ''//Bind a reader to our PDF Dim R As New PdfReader(InputFile) ''//Setup some variable to use below Dim bytes() As Byte Dim obj As PdfObject Dim pd As PdfDictionary Dim filter, width, height, bpp As String Dim pixelFormat As System.Drawing.Imaging.PixelFormat Dim bmp As System.Drawing.Bitmap Dim bmd As System.Drawing.Imaging.BitmapData ''//Loop through all of the references in the file Dim xo = R.XrefSize For I = 0 To xo - 1 ''//Get the object obj = R.GetPdfObject(I) ''//Make sure we have something and that it is a stream If (obj IsNot Nothing) AndAlso obj.IsStream() Then ''//Case it to a dictionary object pd = DirectCast(obj, PdfDictionary) ''//See if it has a subtype property that is set to /IMAGE If pd.Contains(PdfName.SUBTYPE) AndAlso pd.Get(PdfName.SUBTYPE).ToString() = PdfName.IMAGE.ToString() Then ''//Grab various properties of the image filter = pd.Get(PdfName.FILTER).ToString() width = pd.Get(PdfName.WIDTH).ToString() height = pd.Get(PdfName.HEIGHT).ToString() bpp = pd.Get(PdfName.BITSPERCOMPONENT).ToString() ''//Grab the raw bytes of the image bytes = PdfReader.GetStreamBytesRaw(DirectCast(obj, PRStream)) ''//Images can be encoded in various ways. /DCTDECODE is the simplest because its essentially JPEG and can be treated as such. ''//If your PDFs contain the other types you will need to figure out how to handle those on your own Select Case filter Case PdfName.ASCII85DECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case PdfName.ASCIIHEXDECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case PdfName.FLATEDECODE.ToString() ''//This code from https://stackoverflow.com/questions/802269/itextsharp-extract-images/1220959#1220959 bytes = pdf.PdfReader.FlateDecode(bytes, True) Select Case Integer.Parse(bpp) Case 1 pixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Case 24 pixelFormat = Drawing.Imaging.PixelFormat.Format24bppRgb Case Else Throw New Exception("Unknown pixel format " + bpp) End Select bmp = New System.Drawing.Bitmap(Int32.Parse(width), Int32.Parse(height), pixelFormat) bmd = bmp.LockBits(New System.Drawing.Rectangle(0, 0, Int32.Parse(width), Int32.Parse(height)), System.Drawing.Imaging.ImageLockMode.WriteOnly, pixelFormat) Marshal.Copy(bytes, 0, bmd.Scan0, bytes.Length) bmp.UnlockBits(bmd) Using ms As New MemoryStream bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg) bytes = ms.GetBuffer() End Using Case PdfName.LZWDECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case PdfName.RUNLENGTHDECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case PdfName.DCTDECODE.ToString() ''//Bytes should be raw JPEG so they should not need to be decoded, hopefully Case PdfName.CCITTFAXDECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case PdfName.JBIG2DECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case PdfName.JPXDECODE.ToString() Throw New NotImplementedException("Decoding this filter has not been implemented") Case Else Throw New ApplicationException("Unknown filter found : " & filter) End Select ''//At this points the byte array should contain a valid JPEG byte data, write to disk My.Computer.FileSystem.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), I & ".jpg"), bytes, False) End If End If Next Me.Close() End Sub End Class A: The whole page would have to be rendered as an image. Otherwise you're got "text objects" (the individual words/letters of the text), and the watermark object (the overlay image), which will always be distinct/separate parts of the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XML Generation Error Installing SQL Server Express 2008 on Windows 8 Disclaimer: Yes, I know Windows 8 is a pre-release and things won't necessarily work. I still need to do this. I'm trying to install SQL Server Express 2008 R2 on Windows 8 32-bit (via Virtual Box). When I run the installer, I get an error: Database installer returned error code -2147024893 (The system cannot find the path specified.) The web installer didn't work either. WPI's log file tells me: DownloadManager Information: 0 : Install exit code for product 'SQL Server Express 2008 R2' is -2068774911 I tried running this in compatibility mode for Windows 7. I can run the installer, click through the setup screen, and finally I get this error: There was an error generating the XML document. Error code: 0x84B10001. How do I get this working, or, how do I debug/triage this? I looked through the logs, but I'm not too sure what they said; it might've been a registry-write error. Running in admin mode just causes the installer to not load, or a nice BSOD: A: The answer, ironically, is quite simple -- I was installing 32-bit SQL Server on a 32-bit Windows 8. Instead, I moved to installing a 64-bit SQL Server on a 64-bit Windows 8. Problem solved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validating HTML Tags in a String in C# Assume that we have the following HTML strings. string A = " <table width=325><tr><td width=325>test</td></tr></table>" string B = " <<table width=325><tr><td width=325>test</td></table>" How can we validate A or B in C# according to HTML specifications? A should return true whereas B should return false. A: One point to start with is checking if it's valid XML. by the way, I think both your examples are incorrect as you've left out the </tr> from both. A: For this specific case you can use HTML Agility Pack to assert if the HTML is well formed or if you have tags not opened. var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml( "WAVEFORM</u> YES, <u>NEGATIVE AUSCULTATION OF EPIGASTRUM</u> YES,"); foreach (var error in htmlDoc.ParseErrors) { // Prints: TagNotOpened Console.WriteLine(error.Code); // Prints: Start tag <u> was not found Console.WriteLine(error.Reason); } Checking a HTML string for unopened tags A: http://web.archive.org/web/20110820163031/http://markbeaton.com/SoftwareInfo.aspx?ID=81a0ecd0-c41c-48da-8a39-f10c8aa3f931 Github link: https://github.com/markbeaton/TidyManaged This guy has written a .NET wrapper for HTMLTidy. I haven't used it but it may be what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Writing a polling Windows service I usually write Windows services in C# but I'm giving it a go in F#. For a polling serivce, like this one, I ordinarily use a class I've written, which is similar to BackgroundWorker. It spawns a background thread and fires an OnWork method at regular intervals. (Complete code is here [github].) Is there another, perhaps better or more idiomatic, way to do this in F#? It could be a better way to write the polling background worker class, or built-in alternatives to it. EDIT Here's what I came up, based on Joel's suggestion. module Async = open System.Diagnostics let poll interval work = let sw = Stopwatch() let rec loop() = async { sw.Restart() work() sw.Stop() let elapsed = int sw.ElapsedMilliseconds if elapsed < interval then do! Async.Sleep(interval - elapsed) return! loop() } loop() //Example open System.Threading let cts = new CancellationTokenSource() Async.Start(Async.poll 2000 (fun () -> printfn "%A" DateTime.Now), cts.Token) Thread.Sleep(TimeSpan.FromSeconds(10.0)) cts.Cancel() The service using poll: type MyService() = inherit System.ServiceProcess.ServiceBase() let mutable cts = new CancellationTokenSource() let interval = 2000 override __.OnStart(_) = let polling = Async.poll interval (fun () -> //do work ) Async.Start(polling, cts.Token) override __.OnStop() = cts.Cancel() cts.Dispose() cts <- new CancellationTokenSource() override __.Dispose(disposing) = if disposing then cts.Dispose() base.Dispose(true) I wish there was a way to avoid the mutable CancellationTokenSource, but alas. A: I might be tempted to write a simple loop in an asynchronous workflow. You can use do! Async.Sleep interval to sleep in between polling - this has two advantages: you're not tying up a thread just to have it sit idle with Thread.Sleep, and the do! automatically checks for cancellation for you if you pass a CancellationToken into Async.Start. Plus, if your polling operation involves network communication, you're already in an async workflow, making it trivial to make async network calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: SQL Azure: sp_helptext gives non-runnable source code When trying to automate reading out constraint information using sp_helpconstraint I got the bright idea of pulling out the source code of the built-in SP directly and run it myself (since it returns multiple result sets so those can't be stored in a temp table). So I ran exec sp_helptext 'sp_helpconstraint' (on SQL Azure) to generate the source code, and copied it into a new query window. However, when I run the SP (on SQL Azure), I get lot's of error messages -- for example, that object syscomments doesn't exist even though I am using the exact same source that runs perfectly when calling sp_helpconstraint directly. Just to make sure it wasn't an anomaly with the procedure or a mistake in my copy/paste execution, I tested the exact same procedure on SQL Server 2008, and if I directly copy the SP source into a new query window, it runs perfectly (obviously after removing the return statements and manually setting the input parameters). What gives?? Do built-in SP's run in a special context where more commands are available than normal on SQL Azure version? Is sp_helptext not returning the actual source that is being run on SQL Azure? If you want me to try anything out, give a suggestion and I can try it on our SQL Azure Development instance. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to programatically turn on/off a Data Annotation Validation Attribute So, I am using ASP.NET MVC 3 and Entity Framework 4.1 (code-first). I have a class like this: public class Person { public int Id { get; set; } public string Name { get; set; } [Range(18, 99)] public int Age { get; set; } } The range validation is fired correctly. But, for example, in some situations I would like to change the range for the Age attribute. Or even turn it off. How could I do it without changing my Model class? Is this possible to made programatically? A: You can use the IValidatableObject interface and define custom validation rules. See my answer at: Using Data Annotations to make a field required while searching for another in a form mvc 3 Its usually just a matter of implementing the interface and determine when to enforce your rules. A: I just realised the solution for this case. Eg. A user can have an authorization to create a 14 years old person. Before save the Model, we can invoke DataContext.GetValidationErrors() and infer if the only error validation is that we want to disable, and then set DataContext.Configuration.ValidateOnSaveEnabled = false; So, this way we are able to save the model. A: Yes, it is possible to inject validators programmatically. Altering existing validators presents separate issues, as some attributes are read-only, so you may have to delete and replace your existing validator. You can add a class to work on the validators by following my answer to this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set Directories for Silent Install I've created a Basic MSI project and have a fully functional installer. Some directories need path values found in the registry. I have a few "Set Directory" custom actions to handle this for me. The regular GUI installer works just fine, but the silent install doesn't seem to run any of the "Set Directory" custom actions. What do I need to do to make these custom actions set my directory properties correctly? Any help would be appreciated. Here is an example of one such custom action: Directory Name: DIRECTORYNAME Directory Value: [REGISTRYPATH]\subpath Execution Scheduling: Always execute Install UI Sequence: After PathWelcome Install Condition: [REGISTRYPATH] A: Schedule your custom actions in both InstallUISequence and InstallExecuteSequence. Silent installs use only InstallExecuteSequence. A: Type 35 Custom Actions ( Set Directory ) must come after CostFinalize. If you need it before CostFinalize use Type 51 ( Set Property ) Custom Actions. I don't know what PathWelcome is so I can't tell you which to use. Also read the following for advanced considerations to take into account. http://blog.deploymentengineering.com/2011/01/blair-symes-recently-posted-building-32.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7519770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is Mercurial Server a must for using Mercurial? I am trying to pick a version control software for our team but I don't have much experience for it before. After searching and googling, it seems Mercurial is a good try. However, I am a little bit confused about some general information about it. Basically, our team only have 5 people and we all connect to a server machine which will be used to store the repositories. The server is a Redhat Linux system. We probably use a lot of the centralized workflow. Because I like the local commit idea, I still prefer the DVCS kind software. Now I am trying to install mercurial. Here are my questions. 1) Does the server used for repositories always need to be installed the software "mercurial-server "? Or it depends on what kind of workflow it uses ? In other words, is it true if there is no centralized workflow used for works, then the server can be installed by "mercurial client" ? I am confused about the term "mercurial-server". Or it means the mercurial installed on the server is always called "mercurial server" and it does matter if it is centralized or not. In addition, because we all work on that server, does it mean only one copy of mercurial is required to install there ? We all have our own user directory such as /home/Cassie, /home/John,... and /home/Joe. 2) Is SSH a must ? Or it depends on what kind of connection between users and the server ? So since we all work in the server, the SSH is not required right ? Thank you very much, A: There are two things that can be called a "mercurial server". One is simply a social convention that "repository X on the shared drive is our common repository". You can safely push and pull to that mounted repository and use it as a common "trunk" for your development. A second might be particular software that allows mercurial to connect remotely. There are many options for setting this up yourself, as well as options for other remote hosting. Take a look at the first link for a list of the different connection options. But as a specific answer to #2: No, you don't need to use SSH, but it's often the simplest option if you're in an environment using it anyways. The term that you probably want to use, rather than "mercurial server", is "remote repository". This term is used to describe the "other repository" (the one you're not executing the command from) for push/pull/clone/incoming/outgoing/others-that-i'm-forgetting commands. The remote repository can be either another repository on the same disk, or something over a network. A: Typically you use one shared repository to share the code between different developers. While you don't need it technically, it has the advantage that it is easier to synchronize when there is a single spot for the fresh software. In the simplest case this can be a repository on a simple file share where file locking is possible (NFS or SMB), where each developer has write access. In this scenario there is no need to have mercurial installed on the server, but there are drawbacks: * *Every developer must have a mercurial version installed, which can handle the repo version on the share (as an example, when the repo on the share is created with mercurial 1.9, a developer with 1.3 can't access this repo) *Every developer can issue destructive operations on the shared repo, including the deletion of the whole repo. *You can't reliably run hooks on such a repo, since the hooks are executed on the developer machines, and not on the server I suggest to use the http or ssh method. You need to have mercurial installed on the server for this (I'm not taking the http-static method into account, since you can't push into a http-static path), and get the following advantages: * *the mercurial version on the server does not need to be the same as the clients, since mercurial uses a version-independent wire protocol *you can't perform destructive operations via these protocols (you can only append new revisions to a remote repo, but never remove any of them) The decision between http and ssh depends on you local network environment. http has the advantage that it bypasses many corporate firewalls, but you need to take care about secure authentication when you want to push stuff over http back into the server (or don't want everybody to see the content). On the other hand ssh has the drawback that you might need to secure the server, so that the clients can't run arbitrary programs there (it depends on how trustworthy your clients are). A: I second Rudi's answer that you should use http or ssh access to the main repository (we use http at work). I want to address your question about "mercurial-server". The basic Mercurial software does offer three server modes: * *Using hg serve; this serves a single repository, and I think it's more used for quick hacks (when the main server is down, and you need to pull some changes from a colleague, for example). *Using hgwebdir.cgi; this is a cgi script that can be used with an HTTP server such as Apache; it can serve multiple repositories. *Using ssh (Secure Shell) access; I don't know much about it, but I believe that it is more difficult to set up than the hgwebdir variant There is also a separate software package called "mercurial-server". This is provided by a different company; its homepage is http://www.lshift.net/mercurial-server.html. As far as I can tell, this is a management interface for option 3, the mercurial ssh server. So, no, you don't need to have mercurial-server installed; the mercurial package already provides a server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What are some strategies for updating volatile data in Solr? What are some strategies for updating volatile data in Solr? Imagine if you needed to model YouTube video data in a Solr index: how would you keep the "views" data fresh without swamping Solr in updates? I would imagine that storing the "views" data in a different data store (something like MongoDB or Redis) that is better at handling rapid updates would be the best idea. But what is the best way to update the index periodically with that data? Would a delta-import make sense in this context? What does a delta-import do to Solr in terms of performance for running queries? A: First you need to define "fresh". Is "fresh" 1ms? If so, by the time the value (the rendered html) gets to the browser, it's not fresh anymore, due to network latency. Does that really matter? For the vast majority of cases, no, true real-time results are not needed. A more common limit is 1s. In that case, Solr can deal with that with RankingAlgorithm (a plugin) or soft commits (currently available in Solr 4.0 trunk only). "Delta-import" is a term from DataImportHandler that doesn't have much intrinsic meaning. From the point of view of a Solr server, there's only document additions, it doesn't matter where they come from or if a set of documents represent the "whole" dataset or not. If you want to have an item indexed within 1s of its creation/modification, then do just that, add it to Solr just after it's created/modified (for example with a hook in your DAL). This should be done asynchronously, and use RA or soft commits. A: You might be interested in so-called "near-realtime search", or NRT, now available on Solr's trunk, which is designed to deal with exactly this problem. See http://wiki.apache.org/solr/NearRealtimeSearch for more info and links. A: How about using the external file field ? This helps you to maintain data outside of your index in a separate file, which you can refresh periodically without any changes to the index. For data such as downloads, views, rank which is fast changing data this can be an good option. More info @ http://lucene.apache.org/solr/api/org/apache/solr/schema/ExternalFileField.html This has some limitations, so you would need to check depending upon your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: adding conditional statement inside UPDATE The query: UPDATE empPac SET quantityLimit = allocation, allocationStart = '"&allocationStart&"', nextUpdate = DATEADD(mm, allocationMonths, "&allocationStart&"), lastUpdate = GETDATE(), quantityIssued = 0, quantityShipped = 0 WHERE allocation IS NOT NULL AND allocationMonths <> 0 AND (nextUpdate <= DATEADD(mm, "&checkCondition&", GETDATE()) OR nextUpdate IS NULL) AND empIdent in (select empIdent from employee where custIdent='"&custIdent&"') What I want to do is add a conditional statement to the SET quantityLimit = allocation so that rather than having the WHERE allocation IS NOT NULL, I want it to have a conditional statement such as SET quantityLimit = ((allocation IS NULL) ? 0 : allocation) A: You can use ISNULL(): SET quantityLimit = ISNULL(allocation, 0) Equivalent functions for other databases are NVL() for Oracle and IFNULL() for MySQL and SQLite What you really should be using though is COALESCE() if you want to increase the portability of your code. COALESCE is part of the SQL-92 standard and widely supported across RDBMSes. A: What database do you use? For example, in oracle sql you can write case when allocation is null then 0 else allocation end or nvl (allocation, 0) or coalesce (allocation, 0) And case syntax in MSSQL is the same as in Oracle. A: This is the TSQL (MSSQL) way: SET quantityLimit = isnull(allocation,0) Alternatives... SET quantityLimit = CASE WHEN allocation is null THEN 0 ELSE allocation END --This one might be handy if you wanted to check for more than just null values. Such as: ----...CASE WHEN allocation is null THEN 0 WHEN some_other_value THEN 1 WHEN ... THEN ... ELSE allocation END SET quantityLimit = coalesce(allocation,0) --This one gives you the first non-null value it finds, given a list of places to look. Such as: ----...coalesce(allocation,some_other_field,some_nuther_field,...,0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7519780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook app on fan page problems (error 404) I see this issue has appeared a few times but none of the solutions have worked for me. Here is my app: https://www.facebook.com/apps/application.php?id=168373039912688 It's basically an image of a poster: http://www.clare-ents.com/test/facebook/index.html I want this image to be the landing page of my fan page: http://www.facebook.com/ClareEnts I've added this as the site URL on the developer page and added it to my fan page. When I click 'Go to application' on the Apps tab on my fan page I get an error 404. Where could I have gone wrong? A: The App is pointing to : http://www.clare-ents.com/help/facebook/index.html and that seems not to have anything. But to make this app show a and image on the landing page you need to go to your app settings and change the Tab URL and point it to the image or HTML Poster you wish to display. Then go to the app Page https://www.facebook.com/apps/application.php?id=168373039912688 and on the left menu click "Ad to My page", select the clareEnts page. Last in your page settings select the default tab. This will be the tab where non-likers land. As an admin in wont work that way (you are always a fan is the behavior) so use another account for testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign multiple new variables on LHS in a single line I want to assign multiple variables in a single line in R. Is it possible to do something like this? values # initialize some vector of values (a, b) = values[c(2,4)] # assign a and b to values at 2 and 4 indices of 'values' Typically I want to assign about 5-6 variables in a single line, instead of having multiple lines. Is there an alternative? A: As others explained, there doesn't seem to be anything built in. ...but you could design a vassign function as follows: vassign <- function(..., values, envir=parent.frame()) { vars <- as.character(substitute(...())) values <- rep(values, length.out=length(vars)) for(i in seq_along(vars)) { assign(vars[[i]], values[[i]], envir) } } # Then test it vals <- 11:14 vassign(aa,bb,cc,dd, values=vals) cc # 13 One thing to consider though is how to handle the cases where you e.g. specify 3 variables and 5 values or the other way around. Here I simply repeat (or truncate) the values to be of the same length as the variables. Maybe a warning would be prudent. But it allows the following: vassign(aa,bb,cc,dd, values=0) cc # 0 A: list2env(setNames(as.list(rep(2,5)), letters[1:5]), .GlobalEnv) Served my purpose, i.e., assigning five 2s into first five letters. A: Had a similar problem recently and here was my try using purrr::walk2 purrr::walk2(letters,1:26,assign,envir =parent.frame()) A: https://stat.ethz.ch/R-manual/R-devel/library/base/html/list2env.html: list2env( list( a=1, b=2:4, c=rpois(10,10), d=gl(3,4,LETTERS[9:11]) ), envir=.GlobalEnv ) A: I put together an R package zeallot to tackle this very problem. zeallot includes an operator (%<-%) for unpacking, multiple, and destructuring assignment. The LHS of the assignment expression is built using calls to c(). The RHS of the assignment expression may be any expression which returns or is a vector, list, nested list, data frame, character string, date object, or custom objects (assuming there is a destructure implementation). Here is the initial question reworked using zeallot (latest version, 0.0.5). library(zeallot) values <- c(1, 2, 3, 4) # initialize a vector of values c(a, b) %<-% values[c(2, 4)] # assign `a` and `b` a #[1] 2 b #[1] 4 For more examples and information one can check out the package vignette. A: There is a great answer on the Struggling Through Problems Blog This is taken from there, with very minor modifications. USING THE FOLLOWING THREE FUNCTIONS (Plus one for allowing for lists of different sizes) # Generic form '%=%' = function(l, r, ...) UseMethod('%=%') # Binary Operator '%=%.lbunch' = function(l, r, ...) { Envir = as.environment(-1) if (length(r) > length(l)) warning("RHS has more args than LHS. Only first", length(l), "used.") if (length(l) > length(r)) { warning("LHS has more args than RHS. RHS will be repeated.") r <- extendToMatch(r, l) } for (II in 1:length(l)) { do.call('<-', list(l[[II]], r[[II]]), envir=Envir) } } # Used if LHS is larger than RHS extendToMatch <- function(source, destin) { s <- length(source) d <- length(destin) # Assume that destin is a length when it is a single number and source is not if(d==1 && s>1 && !is.null(as.numeric(destin))) d <- destin dif <- d - s if (dif > 0) { source <- rep(source, ceiling(d/s))[1:d] } return (source) } # Grouping the left hand side g = function(...) { List = as.list(substitute(list(...)))[-1L] class(List) = 'lbunch' return(List) } Then to execute: Group the left hand side using the new function g() The right hand side should be a vector or a list Use the newly-created binary operator %=% # Example Call; Note the use of g() AND `%=%` # Right-hand side can be a list or vector g(a, b, c) %=% list("hello", 123, list("apples, oranges")) g(d, e, f) %=% 101:103 # Results: > a [1] "hello" > b [1] 123 > c [[1]] [1] "apples, oranges" > d [1] 101 > e [1] 102 > f [1] 103 Example using lists of different sizes: Longer Left Hand Side g(x, y, z) %=% list("first", "second") # Warning message: # In `%=%.lbunch`(g(x, y, z), list("first", "second")) : # LHS has more args than RHS. RHS will be repeated. > x [1] "first" > y [1] "second" > z [1] "first" Longer Right Hand Side g(j, k) %=% list("first", "second", "third") # Warning message: # In `%=%.lbunch`(g(j, k), list("first", "second", "third")) : # RHS has more args than LHS. Only first2used. > j [1] "first" > k [1] "second" A: Consider using functionality included in base R. For instance, create a 1 row dataframe (say V) and initialize your variables in it. Now you can assign to multiple variables at once V[,c("a", "b")] <- values[c(2, 4)], call each one by name (V$a), or use many of them at the same time (values[c(5, 6)] <- V[,c("a", "b")]). If you get lazy and don't want to go around calling variables from the dataframe, you could attach(V) (though I personally don't ever do it). # Initialize values values <- 1:100 # V for variables V <- data.frame(a=NA, b=NA, c=NA, d=NA, e=NA) # Assign elements from a vector V[, c("a", "b", "e")] = values[c(2,4, 8)] # Also other class V[, "d"] <- "R" # Use your variables V$a V$b V$c # OOps, NA V$d V$e A: If your only requirement is to have a single line of code, then how about: > a<-values[2]; b<-values[4] A: here is my idea. Probably the syntax is quite simple: `%tin%` <- function(x, y) { mapply(assign, as.character(substitute(x)[-1]), y, MoreArgs = list(envir = parent.frame())) invisible() } c(a, b) %tin% c(1, 2) gives like this: > a Error: object 'a' not found > b Error: object 'b' not found > c(a, b) %tin% c(1, 2) > a [1] 1 > b [1] 2 this is not well tested though. A: A potentially dangerous (in as much as using assign is risky) option would be to Vectorize assign: assignVec <- Vectorize("assign",c("x","value")) #.GlobalEnv is probably not what one wants in general; see below. assignVec(c('a','b'),c(0,4),envir = .GlobalEnv) a b 0 4 > b [1] 4 > a [1] 0 Or I suppose you could vectorize it yourself manually with your own function using mapply that maybe uses a sensible default for the envir argument. For instance, Vectorize will return a function with the same environment properties of assign, which in this case is namespace:base, or you could just set envir = parent.env(environment(assignVec)). A: I'm afraid that elegent solution you are looking for (like c(a, b) = c(2, 4)) unfortunatelly does not exist. But don't give up, I'm not sure! The nearest solution I can think of is this one: attach(data.frame(a = 2, b = 4)) or if you are bothered with warnings, switch them off: attach(data.frame(a = 2, b = 4), warn = F) But I suppose you're not satisfied with this solution, I wouldn't be either... A: R> values = c(1,2,3,4) R> a <- values[2]; b <- values[3]; c <- values[4] R> a [1] 2 R> b [1] 3 R> c [1] 4 A: Another version with recursion: let <- function(..., env = parent.frame()) { f <- function(x, ..., i = 1) { if(is.null(substitute(...))){ if(length(x) == 1) x <- rep(x, i - 1); stopifnot(length(x) == i - 1) return(x); } val <- f(..., i = i + 1); assign(deparse(substitute(x)), val[[i]], env = env); return(val) } f(...) } example: > let(a, b, 4:10) [1] 4 5 6 7 8 9 10 > a [1] 4 > b [1] 5 > let(c, d, e, f, c(4, 3, 2, 1)) [1] 4 3 2 1 > c [1] 4 > f [1] 1 My version: let <- function(x, value) { mapply( assign, as.character(substitute(x)[-1]), value, MoreArgs = list(envir = parent.frame())) invisible() } example: > let(c(x, y), 1:2 + 3) > x [1] 4 > y [1] A: Combining some of the answers given here + a little bit of salt, how about this solution: assignVec <- Vectorize("assign", c("x", "value")) `%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv)) c("a", "b") %<<-% c(2, 4) a ## [1] 2 b ## [1] 4 I used this to add the R section here: http://rosettacode.org/wiki/Sort_three_variables#R Caveat: It only works for assigning global variables (like <<-). If there is a better, more general solution, pls. tell me in the comments. A: For a named list, use list2env(mylist, environment()) For instance: mylist <- list(foo = 1, bar = 2) list2env(mylist, environment()) will add foo = 1, bar = 2 to the current environement, and override any object with those names. This is equivalent to mylist <- list(foo = 1, bar = 2) foo <- mylist$foo bar <- mylist$bar This works in a function, too: f <- function(mylist) { list2env(mylist, environment()) foo * bar } mylist <- list(foo = 1, bar = 2) f(mylist) However, it is good practice to name the elements you want to include in the current environment, lest you override another object... and so write preferrably list2env(mylist[c("foo", "bar")], environment()) Finally, if you want different names for the new imported objects, write: list2env(`names<-`(mylist[c"foo", "bar"]), c("foo2", "bar2")), environment()) which is equivalent to foo2 <- mylist$foo bar2 <- mylist$bar
{ "language": "en", "url": "https://stackoverflow.com/questions/7519790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "107" }
Q: Style Trigger to Apply another Style I am sure this has been asked before, but I haven't had an easy time figuring out how to phrase the query. I have this style; <SolidColorBrush x:Key="SemiTransparentRedBrushKey">#F0FF0000</SolidColorBrush> <Style x:Key="TextBoxEmptyError" TargetType="{x:Type TextBox}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text.Length}" Value="0"> <Setter Property="BorderBrush" Value="{StaticResource ResourceKey=SemiTransparentRedBrushKey}"/> </DataTrigger> </Style.Triggers> </Style> That I can apply to Textboxes to have a red border when they are empty. Its great, I can just add Style="{StaticResource TextBoxEmptyError}" to the Control Tag. But what if I want to apply this style with a trigger, so that the control only used it under certain conditions (like a binding being true)? Something like: <TextBox.Style> <Style TargetType="TextBox"> <Style.Triggers> <DataTrigger Binding="{Binding Path=ApprovedRequired}" Value="True"> <Setter Property="Style" Value="{StaticResource TextBoxEmptyError}"></Setter> </DataTrigger> </Style.Triggers> </Style> This code throws an exception though {"Style object is not allowed to affect the Style property of the object to which it applies."} Can something like this be done? Edit: If this cannot be done with a Style trigger because it would overwrite itself, is there another way to Conditionally apply a resource style? Edit: I can change the question title if there is a more proper term for this action. A: Styles cannot be set from a Setter within the Style, because then essentially the first Style would never exist at all. Since you're looking for a Validation style, I would recommend looking into Validation.ErrorTemplate, although if that doesn't work you can change your trigger so it modifies specific properties such as BorderBrush instead of the Style property A: i would think of using a Template with a TemplateTrigger and there you can change the style to what ever you like based on what ever condition
{ "language": "en", "url": "https://stackoverflow.com/questions/7519792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sequencing Events in Javascript I am trying to make a simple hidden object game using javascript. When the user finds and clicks an image, I want 3 things to happen in the following order; a sound plays, the image size increases, and the image goes invisible. The problem I am running into is getting the 3 events to happen sequentially, not concurrent. Right now, seems that all three events happen all at the same time. I've tried using setTimeout(), and while that does create a delay, it still runs all functions at the same time, even if each function is nested in setTimeout. Example: (all this does is waits 1.5 sec then plays the sound and makes the image invisible): function FindIt(image, id){ var t = setTimeout('sound()',10); var b = setTimeout('bigger(' + image + ')',30); var h = setTimeout('hide(' + image + ')',1500); } Below are the functions I am currently using and the actual results are: click the image, nothing happens for 2 seconds, then the sound plays and the image goes invisible. function FindIt(image, id){ sound(); bigger(image); hide(image); } function sound(){ document.getElementById("sound_element").innerHTML= "<embed src='chime.wav' hidden=true autostart=true loop=false>"; } function bigger(image){ var img = document.getElementById(image); img.style.width = 112; img.style.height = 112; } function hide(id){ var ms = 2000; ms += new Date().getTime(); while (new Date() < ms){} //Create a 2 second delay var img = document.getElementById(id); img.style.visibility='hidden'; } Any guidance would be greatly appreciated! A: To trigger things sequentially, you need to execute the second item some amount of time after the first one completes, execute the third item some amount of time after the second one completes, etc... Only your sound() function actually takes some time, so I'd suggest the following: function FindIt(image, id){ sound(); // set timer to start next action a certain time after the sound starts setTimeout(function() { bigger(image); // set timer to start next action a certain time after making the image bigger setTimeout (function() { hide(image); }, 1000); // set this time for how long you want to wait after bigger, before hide }, 1000); // set the time here for how long you want to wait after starting the sound before making it bigger } FYI, the animation capabilities in libraries like jQuery or YUI make this sort of thing a lot easier. Also, please don't use this kind of construct in your JS: while (new Date() < ms){} That locks up the browser for that delay and is very unfriendly to the viewer. Use setTimeout to create a delay. For reference, using the animation libraries in jQuery, the jQuery code to handle a click on the object and then animate it over a 2 second period to a larger size, delay for 1 second, then slideup to disappear is as follows: $("#rect").click(function() { $(this).animate({height: 200, width: 400}, 2000).delay(1000).slideUp(); }); jQuery manages an animation queue and handles setting all the timers and doing all the sequencing and animation for you. It's a lot, lot easier to program and gives a very nice result. You can see it work and play with it here: http://jsfiddle.net/kC4Mz/. A: why don't use "event" approach. like onTaskDone(); function task1(arg, onTask1Done){ console.log(arg); if(onTask1Done)onTask1Done(); } task1("working", function(){console.log("task2");}); A: The Frame.js library is designed to elegantly handle situations like this: function FindIt(image, id){ Frame(10, function(next) { sound(); next(); }); Frame(30, function(next) { bigger(image); next(); }); Frame(1500, function(next) { hide(image); next(); }); Frame.start(); } Frame.js offers many advantages over using standard timeouts, especially if you are doing a lot of this kind of thing, which for a game, you likely are. https://github.com/bishopZ/Frame.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7519793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should i cache the whole query in php or should i just cache the primary key of the row? The question is quite straightforward. I can't choose between either. In the dev documents MySQL has specified that indexes can pick a row from it's position rather than searching the whole table. Suppost i have a request to fetch the 20 best posts in my Posts table based on the ratings. Should i just cache the id's of the retrieved Posts or Should i cache the whole results for responding further requests. Btw i'm using file based caching. A: Memory is cheap and caching 20 rows usually don't take up much. I would say: Cache the full rows if it isn't data that have a requirement to be fresh. A: Rule of caching - cache data which has high probability of usage. In this case the probability is high so do cache them !
{ "language": "en", "url": "https://stackoverflow.com/questions/7519795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make cell save when slickgrid looses focus I have a SlickGrid with some Editors on a form with some buttons above it. (Save and Cancel). When i edit a cell in the grid and click the buttons above the grid - the cell does not commit it's edit. I've debugged and it is not calling : commitCurrentEdit. I've also tested on clicking an empty area anywhere out of the grid area... Has anyone noticed this scenario and have a solution to get the cell to commit when one clicks out of the grid. Due to the various positions the grid good be in it would be hard to do an overlay. Thanks A: You can try this: $("#buttonName").bind("click", function(){ gridName.getEditController().commitCurrentEdit() });
{ "language": "en", "url": "https://stackoverflow.com/questions/7519796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Apache Axis - Calendar instance that gets serialized to 0001-01-01T00:00:00.000Z I'm using Apache Axis to communicate with a web service written in .Net. One of the functions in that WS has special handling when it encounters DateTime.MinDate (i.e. "0001-01-01"). Now, I'm trying to send this special value to the WS, but there seems to be no equivalent to DateTime.MinDate in Java. As you probably know, Axis wraps xsd:dateTime into Calendar objects, so I tried sending new GregorianCalendar(1 ,1 ,1); but this didn't do the trick. I tried calendar.setTime(new Date(0)), I tried many more combinations, but nothing seems to get serialized as <endDate xsi:type="xsd:dateTime">0001-01-01T00:00:00.000Z</endDate> which is what I need. Does anyone have any clue how can this be achieved? A: The following will create a GregorianCalendar object that will serialize to the equivalent of DateTime.MinValue. GregorianCalendar gc=new GregorianCalendar(1,0,1); gc.setTimeZone(TimeZone.getTimeZone("GMT-0")); Note the following: * *The month parameter is zero based, not 1 based. *GregorianCalendar defaults to the local time zone, therefore the timezone needs to be adjusted manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validating email input in form using PHP I'm creating a form in PHP that contains a field called email where the user needs to enter his/her email ID. In order to ensure that the mail ID entered is authentic in terms of syntax (eg. username_123@domain.com is valid) I need to append some kind of validation to it. I find the situation quite nebulous as I don't understand how to check if the mail ID entered contains an @ symbol etc. Kindly help. Thanks. :) A: Best solution is to just do: if (filter_var($email, FILTER_VALIDATE_EMAIL)) { ... } and let PHP handle the heavy work for you. Otherwise, if you want to be strictly correct and use a regex directly yourself, you'll be stuck with this monstrosity: (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) for strict RFC2822 compliance. A: First you need to define valid e-mail. There are different approaches to this depending on how important is this validation to you. Some folks use crazy by-the-RFC regexps. Another extreme is save anything user entered and later try sending confirmation e-mail to that address. No confirmation = bad e-mail. You'll probably want something in between: make sure there's an @ in the middle, for example: $email_arr = explode('@', $email); if (sizeof($email_arr) !== 2 || $email_arr[0] == '' || $email_arr[1] == '') ... // definitely not valid UPD: Marc B nailed it with filter_var($email, FILTER_VALIDATE_EMAIL) That's probably the best way. A: You can use regex to validate the format: <?php $email = "someone@example.com"; // or perhaps $_POST['email']; if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) { echo "Valid email address."; } else { echo "Invalid email address."; } ?> http://php.net/manual/en/function.eregi.php A: From my own code: if( !preg_match( "(^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$)i", $email)) echo "E-mail address invalid"; A very small number of legitimate addresses may fail, such as anything @example.info, and any email address that uses unusual characters, but for the most part this works nicely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL CLI web environment halts on / So I just made a question about symbols, but yeah, while the symbols are now working properly, there is still a problem with UNIX commands. The thing is, whenever I input a value that starts with / and follows with a UNIX command, the host responds with - 501 Method Not Implemented. What causes this, how to prevent this, and am I right that this happens because of MySQL in CLI environment? Yes, here in Latvia currency is "Lats", abbreviated to "Ls" and our client tend to seperate values like - "Ls 3 for students, Ls 2 for retirees /Ls 1 for children". And the /Ls there screws it all up. Thanks in advance! A: http://php.net/manual/en/function.escapeshellcmd.php However, if you're passing queries to Mysql via a command line, then you're defniitely doing it VERY VERY wrong. The mysql functions in PHP communicate directly with the database via sockets (either unix-domain or TCP). There should NEVER be a shell/command line involved in the process anywhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't inherit constructor from parent class I have problem with inheritance of consturctor: function Alive(name) { this.name = name; } var Cat = new Function(); Cat.prototype = new Alive(); Cat.prototype.constructor = Alive; var cat = new Cat('Thomas'); alert(cat.name); alert show undefined. What i do wrong? jsfiddle A: Looks like you want the parent constructor to get called automatically, that's not supported without some extra work. Your code should look like the following function Alive(name) { this.name = name; } function Cat(name) { // Call the parent constructor Alive.call(this, name); } Cat.prototype = new Alive(); // This line is to fix the constructor which was // erroneously set to Alive in the line above Cat.prototype.constructor = Cat; var cat = new Cat('Thomas'); alert(cat.name); If you use a library to implement inheritance, you don't have to worry about this. They can even call your parent constructor automatically if you don't want to create an empty constructor. The above code is still not ideal. See a post I wrote that talks about the 'right' way to do inheritance. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html A: Because Cat doesn't accept an argument. Here's what you want: function Alive(name) { this.name = name; } function Cat(name) { Alive.call(this, name); } // since there's nothing on the prototype, this isn't necessary. // Cat.prototype = new Alive(); var cat = new Cat('Tomas'); alert(cat.name);
{ "language": "en", "url": "https://stackoverflow.com/questions/7519805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing website on localhost server for iphone and ipad What I'm looking to do is preview what I've built on a custom localhost server (set up with Mamp Pro) on my iphone or ipad. The localhost is under http://devsite:8888 and not http://localhost:8888. I've tried the instructions for something similar found here. The result was being able to see the files but it was just the list of the files on the server and not picking up index.php—no previews enabled. I've triple checked to make sure I have a proper index in the root directory as well. Added /etc/apache2/extra/httpd-vhosts.conf file https://gist.github.com/07223bf788ef1e2e1411 A: Put this in your .htaccess or httpd.conf (usually /etc/apache2/httpd.conf on OSX): DirectoryIndex index.php If that is put in .htaccess be sure that somewhere in httpd.conf (or whatever customm config file for the web server) you have this (replace /var/www/html with the directory where your .htaccess file is): ## These lines can go anywhere in the main config file: AccessFileName .htaccess <Directory "/var/www/html"> AllowOverride All </Directory> Also, make sure your /etc/hosts file includes: 127.0.0.1 devsite # Or whatever your local computers IP is: # 192.164.2.164 devsite so that the hostname will resolve properly. Edit: From the comments, it sounds like your virtual hosts may need additional configuration. Can you put the contents of the /etc/apache2/extra/httpd-vhosts.conf file in your question?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In JQuery, how to pass the element that was clicked to the method that is called on onclick event I have several of these lines on a page: <div class="save-button" onclick="Save()">Save</div> In my Save() method I want to manipulate the div that was clicked to call the Save() method. How do I pass that in (I think $(this) ), without resorting to ids? Many thanks! A: Inside the event handler, this refers to the clicked element. However, inside the function you call from the event handler, which is Save, this will refer to window. You can explicitly set what this should refer to inside Save via call [MDN] (or apply): onclick="Save.call(this, event || window.event);" then you can use it inside the function as $(this): function Save(event) { // `this` refers to the clicked element // `$(this)` is a jQuery object // `event` is the Event object }; But as you are using jQuery, you really should do $('.save-button').click(Save); to bind the event handler. Mixing markup with logic is not a good style. You should separate the presentation from the application logic. Or if you want Save to accept an element as parameter, then just pass it: onclick="Save(this);" and with jQuery: $('.save-button').click(function() { Save(this); }); A: Either remove the save() and use click() to catch the event: <div class="save-button">Save</div> <script> $('.save-button').click(function () { // Now the div itself as an object is $(this) $(this).text('Saved').css('background', 'yellow'); }); </script> [ View output ] Or if you insists on using such function as save(): <div onClick="save(this)">Save</div> <script> $(function () { save = function (elm) { // Now the object is $(elm) $(elm).text('Saved').css('background', 'yellow'); }; }); </script> [ View output ] EDIT (2015): .on('click', function) <div class="save-button">Save</div> <script> $('.save-button').on('click', function () { // Now the div itself as an object is $(this) $(this).text('Saved').css('background', 'yellow'); }); </script> A: Pretty straight forward... $('#myDiv').click(function(){ save($(this)); }) function save($obj){ $obj.css('border', '1px solid red'); } A: Simply refer to it as: $(this) A: Inside the Save() function this refers to the DOM element that was clicked. You can convert this to a jQuery object with $(this). This refers to window by default however, so you'll need to pass this as a parameter of the Save function: <div class="save-button" onclick="Save(this)">Save</div> function Save(div) { } now inside Save, you can use div to refer to the div that was clicked. I was confused about how this behaved. This link helped me: http://www.quirksmode.org/js/this.html A: You can easily pass element as "this" to the function and then wrap it by $(), then you can do anything to it. Html: <div class="save-button" onclick="Save(this)" > Save </div> JQuery script: function Save(element){ // Convert it to jQuery object by wrap in into $() $(element).hide(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <div class="save-button" onclick="Save(this)" > Save </div> </body> </html> <script type="text/javascript"> $(document).ready(function(){ }); function Save(element){ // Convert it to jQuery object by wrap in into $() $(element).hide(); } </script> 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7519815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: NSDateFormatter set date to 1970 In my summarydict, I have a entire called date_generated, it looks like : Sep 22, 2:33 PM, I want to convert it into a NSDate so that I can later feed it into a repeated timer. So here's my code: ALog(@"Last update time is: %@", [[summarydict objectForKey:@"root"]objectForKey:@"date_generated"]); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setLenient:YES]; [dateFormatter setDateFormat:@"MM dd, h:mm a"]; [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]]; NSDate *date = [dateFormatter dateFromString:[[summarydict objectForKey:@"root"]objectForKey:@"date_generated"]]; ALog(@"Using timezone: %@", [dateFormatter timeZone]); ALog(@"Last updated time: %@", date); ALog(@"Current time: %@", [NSDate dateWithTimeIntervalSinceNow:0]); ALog(@"Next update time: %@", [date dateByAddingTimeInterval:600]); And here's what I got: Last update time is: Sep 22, 2:33 PM Using timezone: America/New_York (EDT) offset -14400 (Daylight) Last updated time: 1970-09-22 18:33:00 +0000 Current time: 2011-09-22 18:43:05 +0000 Next update time: 1970-09-22 18:43:00 +0000 I understand NSLog (my ALog) doesn't care about timezoon, so by displaying it as GMT timezoon is fine, but how can I make the formatter think that what I have Sep 22, 2:33 PM is for current year? I have [dateFormatter setLenient:YES]; but it doesn't work. Thanks! A: What do you think about this: NSString *str = [NSString stringWithFormat:@"2011 %@", [[summarydict objectForKey:@"root"]objectForKey:@"date_generated"]]; NSLog(@"Last update time is: %@", str); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setLenient:YES]; [dateFormatter setDateFormat:@"yyyy MM dd, h:mm a"]; [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]]; NSDate *date = [dateFormatter dateFromString:str]; NSLog(@"Using timezone: %@", [dateFormatter timeZone]); NSLog(@"Last updated time: %@", date); NSLog(@"Current time: %@", [NSDate dateWithTimeIntervalSinceNow:0]); NSLog(@"Next update time: %@", [date dateByAddingTimeInterval:600]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7519821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What affect will upgrading from ASP.NET MVC2 to MVC3 have on NHibernate? How do I upgrade ASP.NET MVC2 to MVC3 with minimal possible implications to NHibernate? A: There's there should be no impact in terms of NHibernate if you properly separated concerns in your application by using abstractions. As far as upgrading an ASP.NET MVC 2 application to ASP.NET MVC 3 application is concerned you could follow the upgrading steps mentioned in the release notes or even try the Upgrade Tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WinForm Automatically Close After Time Expires? In Framework 4.0, I have a WinForm that is opened from another form, displays some stuff and a progress bar, and then sits there. I would like to close that "pop up" form after n secods if the user does not close it manually. What's the smartest way to do that? Thanks. A: Start a timer with the desired interval and then when it ticks the first time, close the form. Something like this private Timer _timer; public PopupForm() { InitializeComponent(); _timer = new Timer(); _timer.Interval = 5000; // interval in milliseconds here. _timer.Tick += (s, e) => this.Close(); _timer.Start(); } Actually the smartest way would probably putting this in its own StartCountdown() method that takes the time as a parameter. Logic like this normally shouldn't be in a constructor strictly speaking...
{ "language": "en", "url": "https://stackoverflow.com/questions/7519832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Addition of vectors c++. Cannot understand compilation error Hi I am have written the following function for adding 2 vectors vector<double> add(vector<double>& v1, vector<double>& v2 ) { /*Do quick size check on vectors before proceeding*/ vector<double> result(v1.size()); for (unsigned int i = 0; i < result.size(); ++i) { result[i]=v1[i]+v2[i]; } return result; } Now I tried to add 3 vectors a,b,c all of same size in the following two ways vector <double> sum1, sum2; sum1=add(b,c); sum2=add(a,sum1); which worked and vector <double> sum; sum=add(a,add(b,c)); which gave me the following compiler error g++ -Wall simple.cpp simple.cpp: In function ‘int main(int, char**)’: simple.cpp:45: error: invalid initialization of non-const reference of type ‘std::vector<double, std::allocator<double> >&’ from a temporary of type ‘std::vector<double, std::allocator<double> >’ simple.cpp:16: error: in passing argument 2 of ‘std::vector<double, std::allocator<double> > add(std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&)’ Why did the second method not work? A: vector<double> add(vector<double> v1, vector<double> v2 ) From the error message, I can say with 100% certaintly that this is not the function signature in your original code. In your original code, you must be using this: vector<double> add(vector<double> & v1, vector<double> & v2 ) If so, then make it as: vector<double> add(const vector<double> & v1, const vector<double> & v2) Now it should work just fine. Explanation: The return value of add() is a temporary object, and a temporary object cannot be bound to non-const reference. That is why the compiler was giving error. It will give same error if you write this: vector<double> & v = add(a,b); //error However, if a temporary object can be bound to const reference. That is why I suggested you to make the parameter const reference. That means, you can write this: const vector<double> & v = add(a,b); //ok Also, you can make the parameter non-const non-reference as well, that is, pass the arguments by value. But I would not recommend that, as it involves unnecessary copies of the vectors. The best solution is this: vector<double> add(const vector<double> & v1, const vector<double> & v2) Getting familiar with operator+ You could also overload operator+ for vector, as: vector<double> operator + (const vector<double>& v1, const vector<double>& v2 ) { /*Do quick size check on vectors before proceeding*/ vector<double> result(v1.size()); for (unsigned int i = 0; i < result.size(); ++i) { result[i]=v1[i]+v2[i]; } return result; } If you overload this, then you can write this cool code: vector<double> c = a + b; vector<double> d = a + b + c; vector<double> e = a + b + c + d; //so on Isn't it fun? Getting familiar with Standard algorithm.. As @Gene commented, you could use std::transform in the function as: vector<double> operator+(const vector<double>& v1, const vector<double>& v2 ) { vector<double> result; std::transform(v1.begin(),v1.end(),v2.begin(), std::back_inserter(result), std::plus<double>); return result; } A: vector<double> add(vector<double>& v1, vector<double>& v2 ) Because we expect the function to modify its arguments, we cannot call the function with just any expression. Instead we must pass an lvalue argument to a reference parameter. An lvalue is a value that denotes a nontemporary object. sum=add(a,add(b,c)); The preceding call to add tries to pass a temporary object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript Split Performance I'm sure you've all seen code like this in JS: var args = 'now later today tomorrow'.split(' ') Anyone know why that's faster than this: args = ['now', 'later', 'today', 'tomorrow'] (I don't know the answer to this, but I can verify by timing in the console that splitting is faster) A: I Would be surprised if it was faster, could you post how you came to think it is? I made this perf quickly and It shows its not faster. http://jsperf.com/split-performance A: Is it possible that the javascript engine you were using has deferred execution capabilities and so the actual splitting didn't occur yet? Try timing again in the console but included accessing the first member of the split array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Clearing C# Events after execution? Say I have the following code: public event EventHandler DatabaseInitialized = delegate {}; //a intederminant amount of subscribers have subscribed to this event... // sometime later fire the event, then create a new event handler... DatabaseInitialized(null,EventArgs.Empty); //THIS LINE IS IN QUESTION DatabaseInitialized = delegate {}; Will this clear out the subscribers, replacing it with new empty default? And, will the event notify all subscribers before they get cleared out? I.E. Is there a chance for a race condition? A: Yes it will clear it out. And because events fire syncronously in the same thread there shouldn't be race condition. My advice: when in doubt, write a small test application and... well, test it. UPDATE: I tested it before posting. (In response to minuses.) A: To unsubscribe from the event use event-=delegate, so you're sure that resource is free. Even if by official Microsoft documentation it's not necessary, in my own experience, especially on a large scale complex project, unnecessary events suscribers are source for memory leaks. So unsubscribe from them explicitly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Stream camera feed of android to a java based server i am making a simple android app which streams video feed of camera to a custom java based server, i am sending the frames (basically byte[]) using tcp, [i know tcp is not a good approach for video streaming but it is ok for me], android is the client and a java application is the server, i have implemented the client successfully but i am having problem in implementing the java application, the server has to receive the byte[], convert them to image and display in some image container, this is the source code of server: package dummyserver; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import javax.imageio.ImageIO; import javax.media.jai.PlanarImage; /** * * @author usama */ public class ServerListen implements Runnable{ CameraFeed camera_feed_ui; ServerSocket server_socket=null; Socket client_socket=null; InputStream in=null; int port=9000; DataInputStream dis=null; public ServerListen() {} public ServerListen(CameraFeed camera_feed_ui) { this.camera_feed_ui = camera_feed_ui; } public void run() { int len = 0; byte[] data; while(true) { try { System.out.println("Waiting"); server_socket = new ServerSocket(port); client_socket=server_socket.accept(); System.out.println("Client arrived"); System.out.println("Reading Image"); in=client_socket.getInputStream(); data=new byte[client_socket.getReceiveBufferSize()]; in.read(data, 0, client_socket.getReceiveBufferSize()); Image image = getImageFromByteArray(data); BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); PlanarImage planar_image=PlanarImage.wrapRenderedImage(bufferedImage); System.out.println("Converting byte[] to Image completed"); camera_feed_ui.displayImage(planar_image); // client_socket.close(); server_socket.close(); } catch(Exception ex) { System.out.println("error: " + ex.toString()); } } } public static Image getImageFromByteArray(byte[] byteArray) { InputStream is = new ByteArrayInputStream(byteArray); try { return ImageIO.read(is); } catch (IOException ex) { System.out.println("Unable to converet byte[] into image."); return null; } } } Explanation of code: CameraFeed is the object of my JFrame and it basically contains the image container on which the video is to be displayed (for displaying video i am using jai [java advance imaging]). The method displayImage(PlanarImage) simply takes the image to be displayed in the container. I think the problem is in converting byte[] to image or i am not correctly extracting byte[] from the sockets, now in the output i am getting a black image. One more thing, in the client side, i am establishing tcp connection for every frame, it's also clear from this code, i am closing the connection (server_socket.close()) after the frame is received, is this a good approach? How can i make this streaming efficient? if u can please describe the appropriate approach for video streaming from android phone to server (i am asking about algorithm). Thanks in advance regards usama Edit: C# code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Threading; namespace VideoServer { public partial class Form1 : Form { TcpListener server_socket; Socket client_socket; Thread video_thread; NetworkStream ns; public Form1() { InitializeComponent(); server_socket = null; client_socket = null; } private void startVideoConferencing() { try { server_socket = new TcpListener(System.Net.IPAddress.Parse("192.168.15.153"),9000); server_socket.Start(); client_socket = server_socket.AcceptSocket(); ns = new NetworkStream(client_socket); pictureBoxVideo.Image = Image.FromStream(ns); server_socket.Stop(); if (client_socket.Connected == true) { while (true) { startVideoConferencing(); } ns.Flush(); } } catch (Exception ex) { button1.Enabled = true; video_thread.Abort(); } } private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; video_thread = new Thread(new ThreadStart(startVideoConferencing)); video_thread.Start(); } } } Basically the problem is that what is the equivalent of Image.FromStream in java, if there is any such method in java which just takes a stream and convert into image while abstracting the low level details of conversion, then this task would also be done for Java. So any idea ?? A: Video stream is not just a stream of images (e.g. Jpegs). Depending on codec, its a stream of encoded frames, some of them are only partial (intraframes) frames. So you can not just take a video stream and simply decode it with image codec. You need a video stream codec. Take a look at this two open source projects to see how they implemented it: http://code.google.com/p/spydroid-ipcamera/ http://code.google.com/p/ipcamera-for-android/
{ "language": "en", "url": "https://stackoverflow.com/questions/7519847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Regions in CSS like C# regions? Is there a way to define regions in CSS file just like regions in C#? Like in C# you define regions as follows #region My Region //your code here #endregion My problem is I don't want to use separate CSS files for my asp.net project but I also want to organinze so I can define specific sections like one for Master Page CSS and one for FormUser and so forth so it is easy to troubleshoot when needed. Is it possible? A: Type region and press tab you will get the following /*#region name */ /*#endregion */ where you can edit the name to give the region a name of your choice. A: You can't do regions, but you can always just use spacing and comments to add some organization if you like. /*Layout rules*/ body{} div{} etc{} /*Typography Rules*/ etc{} etc... A: No there is no support for regions in CSS. The usual approach is separating into different CSS files and then use a CSS minification tool for production releases that combines and minifies your CSS, i.e. see minify or YUI Compressor. A: You can add Regions to your CSS exactly as you describe by using a visual studio plugin called "Web Essentials" (this is the VS2012 link, but earlier versions are available) Then you can simply add regions in your CSS by doing this : /*#region Footer ---------------------------------------------------- */ .footerHyperlinks{ decoration:none; } /*#endregion*/ In conjunction with the keyboard shortcut (ctrl+M, ctrl+L) this for me is invaluable. as it instantly reduces your huge, long page that you have to scroll through MUCH, MUCH quicker. Hope that helps you out !! A: You can use this for regions...works well to make collapsible regions /*#region RegionName*/ /*#endregion RegionName*/ The RegionName is optional in endregion, you can also use /*#region RegionName*/ /*#endregion */ A: You should use different CSS files and move them into 1 file while building your application. There are special tools for this that do just that as this is the only way. A: Use type of Media Query! this is too late to answer but I did this for grouping my code and it working perfectly for me @media all /*'Global Settings'*/{ body { background: red; padding-bottom: 120px; } } @media all /*'Header Settings'*/{ .add-to-cart-header { height: 66px; background: #f7f7f7; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: How to equalize and in Emacs? Some key bindings are designed in a way that Enter (<return>) and numpad Enter (<kb-enter>) are not the same (I guess, if a binding is (kbd "<return>/<kb-enter>") not (kbd "RET")). Is it possible to rewrite <kb-enter to <return> in Emacs or I have to change system settings? A: It sounds like this is what you want: (define-key local-function-key-map [kp-enter] [return]) That will translate the <kp-enter> key to the <return> key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how do I get emacs to treat a file with the wrong extension correctly? So (let us not concern ourselves with why) I have a .emacs file which is called dotemacs, and a .bashrc file which is called dotbashrc. When I load up dotemacs, I get no syntax highlighing (amongst other things). If I do M-x lisp-mode then all is well. Without changing the name of the file, how do I get emacs to recognise automatically that dotemacs is a lisp file and go into lisp-mode? Similarly for bash scripts, and indeed any other type of file with the wrong (or no) extension. A: You can put this at the top of the dotemacs file: ; -*- mode: lisp -*- causing it to start elisp-mode when you load the file. For shell scripts, putting a #!/bin/bash (for whichever shell you are using) is enough to turn on the correct mode. Or otherwise put this at the top of the file: # -*- mode: sh -*- A: I like the answer above, but here is another way you could do it :) Add the following line to your .emacs (add-to-list 'auto-mode-alist '(".emacs" . lisp-mode))
{ "language": "en", "url": "https://stackoverflow.com/questions/7519867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generate a list of files/objects dynamically from within makefile I am trying to do this: From a directory, pick all the C (.c) files, generate .o and add it to my final target executable. The C files can be added or removed at anytime, so when I run make for my target, the available C files from the directory has to be picked to compile and link with my target. So far, I have the following: define test_tgt = DIR = full/path/to/dir FILES = $(wildcard $(DIR)/*.c) OBJS = <rule-to-convert-C-to-O> endef get_new_files: $(eval $(test_tgt)) final-target: get_new_files $(CC) <other-objs> $(OBJS) Somehow this doesn't seem to work. I see a lot of similar examples, but not sure what is wrong here. If this approach is not correct, can anyone suggest a better way to accomplish this. TIA. A: You are trying to program a check that make does by itself. Just list $(OBJS) as dependencies of final-target. Something like this should work under GNU make: DIR = full/path/to/dir FILES = $(wildcard $(DIR)/*.c) OBJS = $(subst .c,.o,$(FILES)) final-target: $(OBJS) $(LD) -o $@ $+ # or similar Full documentation is here: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7519868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Camel idiom to route dynamically based on the value in the body of the message Suppose you have a route like: from("direct:start").to("http://some.endpoint/accounts/"); where message passed through direct:start is an XML: <payload> <account id="1">Bob</account> </payload> What's the idiomatic way to extract the account's id and append it to the to endpoint in order to send this message to http://some.endpoint/accounts/1? A: you can use the recipient list pattern to create dynamic endpoints based on Exchange data. from("direct:start") .recipientList(constant("http://some.endpoint/accounts/") .append(XPathBuilder.xpath("/payload/account/@id", String.class))); A: See this FAQ about dynamic to http://camel.apache.org/how-do-i-use-dynamic-uri-in-to.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7519869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Object does not exist or is not a valid using 'sp_changeobjectowner' I changed the table schema from dbo to db_owner using the SQL statement below (SQL 2008 R2): DECLARE @old sysname, @new sysname, @sql varchar(1000) SELECT @old = 'db_owner' , @new = 'dbo' , @sql = ' IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES WHERE QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?'' AND TABLE_SCHEMA = ''' + @old + ''' ) EXECUTE sp_changeobjectowner ''?'', ''' + @new + '''' EXECUTE sp_MSforeachtable @sql I need to change it back by switch the old and new name parameters, but I am getting an error: Msg 15001, Level 16, State 1, Procedure sp_changeobjectowner, Line 75 Object '[db_owner].[language_link]' does not exist or is not a valid object for this operation. That table does exist though and even with that old db_owner. Any way to fix this? Here is a screenshot on how I could tell it is still owned by db_owner. Only some tables were moved back properly: A: Are you sure you should be using sp_changeobjectowner? (Objects don't really have owners anymore as of SQL 2005.) How did you verify that db_owner.language_link exists? Personally I would use ALTER SCHEMA for this and I would also lean toward catalog views (sys.tables) rather than information_schema.tables. Finally, I wouldn't use the undocumented and unsupported sp_MSforeachtable - I have highlighted issues with sp_MSforeachdb that are likely potential issues here because the code is quite similar. DECLARE @old SYSNAME = N'db_owner', @new SYSNAME = N'dbo', @sql NVARCHAR(MAX) = N''; SELECT @sql += CHAR(13) + CHAR(10) + 'ALTER SCHEMA ' + @new + ' TRANSFER ' + QUOTENAME(SCHEMA_NAME([schema_id])) + '.' + QUOTENAME(name) + ';' FROM sys.tables AS t WHERE SCHEMA_NAME([schema_id]) = @old AND NOT EXISTS (SELECT 1 FROM sys.tables WHERE name = t.name AND SCHEMA_NAME([schema_id]) = @new); PRINT @sql; --EXEC sp_executesql @sql; EDIT adding code to find objects that are common to both schemas. And to move the ones already in the new schema to some dummy schema: CREATE SCHEMA dummy AUTHORIZATION dbo; GO DECLARE @old SYSNAME = N'db_owner', @new SYSNAME = N'dbo', @sql NVARCHAR(MAX) = N''; SELECT @sql += CHAR(13) + CHAR(10) + 'ALTER SCHEMA dummy TRANSFER ' + QUOTENAME(@new) + '.' + QUOTENAME(t1.name) + ';' FROM sys.tables AS t1 INNER JOIN sys.tables AS t2 ON t1.name = t2.name WHERE t1.schema_id = SCHEMA_ID(@new) AND t2.schema_id = SCHEMA_ID(@old); PRINT @sql; -- EXEC sp_executesql @sql; But really it just sounds like you messed something up and it requires some manual cleanup... EDIT adding evidence because OP seems convinced that this code is not working because it is not possible to move things into the dbo schema. No, that is not the case, it's just not possible to move dummy.floob -> dbo.floob if there's already an object named dbo.floob. Note that it may not be a table! CREATE DATABASE schema_test; GO USE schema_test; GO CREATE SCHEMA floob AUTHORIZATION dbo; GO CREATE TABLE dbo.x(a INT); CREATE TABLE dbo.y(a INT); GO Move all tables from dbo -> floob: DECLARE @old SYSNAME = N'dbo', @new SYSNAME = N'floob', @sql NVARCHAR(MAX) = N''; SELECT @sql += CHAR(13) + CHAR(10) + 'ALTER SCHEMA ' + @new + ' TRANSFER ' + QUOTENAME(SCHEMA_NAME([schema_id])) + '.' + QUOTENAME(name) + ';' FROM sys.tables AS t WHERE SCHEMA_NAME([schema_id]) = @old AND NOT EXISTS (SELECT 1 FROM sys.tables WHERE name = t.name AND SCHEMA_NAME([schema_id]) = @new); EXEC sp_executesql @sql; GO SELECT SCHEMA_NAME([schema_id]),name FROM sys.tables; Results: Move all tables back from floob -> dbo: DECLARE @old SYSNAME = N'floob', @new SYSNAME = N'dbo', @sql NVARCHAR(MAX) = N''; SELECT @sql += CHAR(13) + CHAR(10) + 'ALTER SCHEMA ' + @new + ' TRANSFER ' + QUOTENAME(SCHEMA_NAME([schema_id])) + '.' + QUOTENAME(name) + ';' FROM sys.tables AS t WHERE SCHEMA_NAME([schema_id]) = @old AND NOT EXISTS (SELECT 1 FROM sys.tables WHERE name = t.name AND SCHEMA_NAME([schema_id]) = @new); EXEC sp_executesql @sql; GO SELECT SCHEMA_NAME([schema_id]),name FROM sys.tables; Results:
{ "language": "en", "url": "https://stackoverflow.com/questions/7519870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use a common test harness for MStests & NUnit and run them in Mono? I'm using VS2010 to develop a project and will be adding some NUnit tests to an existing test harness which is full of MStests.How do i run only the NUnit tests from that harness in Mono? Is there way i can selectively switch between running MSTests and NUnit tests when i am running them on a PC versus Mac? Or making a separate test harness with just the NUnit tests and running them in mono is the only solution?? I have tried to find easier ways, but looks like not many have attempted this. Any pointers are appreciated! A: You can try a neat trick to 'cross-compile' your unit tests to one of the two frameworks depending on target platform. Put this a the beginning of a test file: #if MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; using Category = Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute; #else using NUnit.Framework; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestContext = System.Object; using TestProperty = NUnit.Framework.PropertyAttribute; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; #endif (taken from http://completedevelopment.blogspot.com/2009/05/blog-post.html )
{ "language": "en", "url": "https://stackoverflow.com/questions/7519883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Soap - How to remove xsi:type= from XML tag I'm sending a SOAP request that looks like: <SOAP-ENV:Body> <api:GetOrder xsi:type="SOAP-ENC:Struct"> <api_orderId xsi:type="xsd:int">1234</api_orderId> </api:GetOrder> </SOAP-ENV:Body> But needs to look like this (SoapUI generated): <soapenv:Body> <api:GetOrder> <api:orderId>1234</api:orderId> </api:GetOrder> </soapenv:Body> My PHP Code: $client = $this->getConnection(); $soap_options = array('soapaction' => $config->getValue('soapaction_url') . 'GetOrder'); $obj = new stdClass(); $obj->api_orderId = 59698; $results = $client->__soapCall('GetOrder', array(new SoapParam($obj, "api:GetOrder")), $soap_options); 2 questions really: 1) How can I remove the "xsi:type" from the request? (If I add xsi:type in to my SoapUI request, I get back a "400 Bad Request" 2) Instead of "api_orderId" I need to send "api:orderId", but I can't name an object with a colon, so do I have to pass the name and value as an array somehow? Appreciate any help, thank you. EDIT: I wasn't able to figure out any other way to send these requests and I essentially ended up doing as Mr.K suggested below. I wrote a custom class to extend SoapClient. Then overrode the __doRequest method to send my own custom SOAP request. The only downside is that SOAP no longer returns me an array of objects, so I also had to parse the XML of the SOAP response. Also I suspect that the performance of doing it this way is a bit slower, but I didn't notice it. A: Try with Simple XML parsing, and create the new request as you like. Read the tag values from Original request, assign those values to a new XML object using parsing. You can create string of XML message and load it as an XML object in PHP. Just like get it from there, put it inside this..and Send!..
{ "language": "en", "url": "https://stackoverflow.com/questions/7519884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to cut Faces after detection I have been working on a college project using OpenCV. I made a simple program which detects faces, by passing frames captured by a webcam in a function which detects faces. On detection it draws black boxes on the faces when detected. However my project does not end here, i would like to be able to clip out those faces which get detected as soon as possible and save it in an image and then apply different image processing techniques [as per my need]. If this is too problematic i could use a simple image instead of using frames captured by a webcam. I am just clueless about how to go about clipping those faces out that get detected. A: http://nashruddin.com/OpenCV_Region_of_Interest_(ROI) Check this link, you can crop the image using the dimensions of the black box, resize it and save as a new file. A: For C++ version you can check this tutorial from OpenCV documentation. In the function detectAndDisplay you can see the line Mat faceROI = frame_gray( faces[i] ); where faceROI is clipped face and you can save it to file with imwrite function: imwrite("face.jpg", faceROI); A: Could you grab the frame and crop the photo with the X,Y coordinates of each corner?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Generate unique username from first and last name? I've got a bunch of users in my database and I want to reset all their usernames to the first letter of their first name, plus their full last name. As you can imagine, there are some dupes. In this scenario, I'd like to add a "2" or "3" or something to the end of the username. How would I write a query to generate a unique username like this? UPDATE user SET username=lower(concat(substring(first_name,1,1), last_name), UNIQUETHINGHERE) A: CREATE TABLE bar LIKE foo; INSERT INTO bar (id,user,first,last) (SELECT f.id,CONCAT(SUBSTRING(f.first,1,1),f.last, (SELECT COUNT(*) FROM foo f2 WHERE SUBSTRING(f2.first,1,1) = SUBSTRING(f.first,1,1) AND f2.last = f.last AND f2.id <= f.id )),f.first,f.last from foo f); DROP TABLE foo; RENAME TABLE bar TO foo; This relies on a primary key id, so for each record inserted into bar, we only count duplicates found in foo with id less than bar.id. Given foo: select * from foo; +----+------+--------+--------+ | id | user | first | last | +----+------+--------+--------+ | 1 | aaa | Roger | Hill | | 2 | bbb | Sally | Road | | 3 | ccc | Fred | Mount | | 4 | ddd | Darren | Meadow | | 5 | eee | Sharon | Road | +----+------+--------+--------+ The above INSERTs into bar, resulting in: select * from bar; +----+----------+--------+--------+ | id | user | first | last | +----+----------+--------+--------+ | 1 | RHill1 | Roger | Hill | | 2 | SRoad1 | Sally | Road | | 3 | FMount1 | Fred | Mount | | 4 | DMeadow1 | Darren | Meadow | | 5 | SRoad2 | Sharon | Road | +----+----------+--------+--------+ To remove the "1" from the end of user names, INSERT INTO bar (id,user,first,last) (SELECT f3.id, CONCAT( SUBSTRING(f3.first,1,1), f3.last, CASE f3.cnt WHEN 1 THEN '' ELSE f3.cnt END), f3.first, f3.last FROM ( SELECT f.id, f.first, f.last, ( SELECT COUNT(*) FROM foo f2 WHERE SUBSTRING(f2.first,1,1) = SUBSTRING(f.first,1,1) AND f2.last = f.last AND f2.id <= f.id ) as cnt FROM foo f) f3) A: As a two-parter: SELECT max(username) FROM user WHERE username LIKE concat(lower(concat(substring(first_name,1,1),lastname), '%') to retrieve the "highest" username for that name combo. Extract the numeric suffix, increment it, then insert back into the database for your new user. This is racy, of course. Two users with the same first/last names might stomp on each other's usernames, depending on how things work out. You'd definitely want to sprinkle some transaction/locking onto the queries to make sure you don't have any users conflicting. A: Nevermind.... I just found the dupes: select LOWER(CONCAT(SUBSTRING(first_name,1,1),last_name)) as new_login,count(* ) as cnt from wx_user group by new_login having count(* )>1; And set those ones manually. Was only a handful. A: Inspired in the answer of unutbu: there is no need to create an extra table neither several queries: UPDATE USER a LEFT JOIN ( SELECT USR_ID, REPLACE( CONCAT( SUBSTRING(f.`USR_FIRSTNAME`,1,1), f.`USR_LASTNAME`, ( (SELECT IF(COUNT(*) > 1, COUNT(*), '') FROM USER f2 WHERE SUBSTRING(f2.`USR_FIRSTNAME`,1,1) = SUBSTRING(f.`USR_FIRSTNAME`,1,1) AND f2.`USR_LASTNAME` = f.`USR_LASTNAME` AND f2.`USR_ID` <= f.`USR_ID`) ) ), ' ', '') as login FROM USER f) b ON a.USR_ID = b.USR_ID SET a.USR_NICKNAME = b.login
{ "language": "en", "url": "https://stackoverflow.com/questions/7519892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Ajax Error Reporting With PrototypeJS I am wondering if there is script or something out there that will report javascript/PrototypeJS errors that happen in Ajax calls. It can be time consuming to fill code with console.log and/or alerts. It would be great if there was something like a browser plugin that would do it. Anybody have any tools or tips? A: Firefox has Firebug. Chrome has Developer Tools (already built in). Internet Explorer has Developer Toolbar (already built in). To catch the errors in script you can use Ajax.Responders, Ajax.Responders.register({ onException: function(request, exception) { if (window.console) console.log(exception); } }); A: You mean like, http errors? Some http errors are logged to firebug, like 404 or 500. You can extend Ajax.Request and make it report any http response status you want without having to repeat code. Ajax.MyRequest = Class.create(Ajax.Request, { initialize: function($super, url, options) { function debuggerHandler(response) { if(console && console.error) { console.error("ERROR: " + response.responseText); } } var debuggers = ["onFailure"]; //add any custom http status code options = Object.clone(options) || {}; var handler; var old; for(var d in debuggers) { handler = debuggers[d]; if(options[d]) { old = options[d]; handler = function(response) { old(response); debuggers[d](response); } } options[d] = handler; } $super(url, options); } }); Then, instead of calling Ajax.Request, you call Ajax.MyRequest and every ajax call will go through the debugger handlers and through any handler that you want to treat the error individually. Like: new Ajax.MyRequest("/thisresourcedoesnotexist"); Will throw a 404 and log to console.error. new Ajax.MyRequest("/thisresourcedoesnotexist", { on404: function() { console.error("But I want to treat this one"); } }); Will throw a 404, execute the custom handler and log to console.error. There is a number of ways to improve this approach. This is just the general idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send 'POST' request without submit event Event after which i am sending ajax is not submit. I even don't have sumbmin button. This is part of my jquery: var description_data = $('#description_form').serialize(); alert(description_data) $.ajax({ url: '/accounts/profile/add_description/', type: 'POST', data: description_data, success: function(data){alert('ok')} }); and my view.py def add_description(request): if request.is_ajax() or request.method == "POST": form = DescriptionForm(request.POST, prefix="description") if form.is_valid(): user = request.user profile = user.get_profile() description = form.cleaned_data['content'] profile.description=description profile.save() response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(serializers.serialize('json', [profile], fields=('description'))) return response else: return HttpResponse('form invalid') else: return HttpResponse('error') Ajas is sent not by submit event, but when it is send like that there request.is_ajax() or request.method=="POST" return False. How can i make it working? A: You probably need to call preventDefault, to stop the click event submitting the form before it runs the Ajax request. $('#myButton').click(function(e) { e.preventDefault; //Your code from above });
{ "language": "en", "url": "https://stackoverflow.com/questions/7519897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using to make a servlet call that returns additional 's, but they're not being rendered So this question suggested using a servlet to do the file check before doing the include: How can you check if a file exists before including/importing it in JSP? So I wrote a servlet that does that. I call it using something like <jsp:include page='<%= "/servlet/fileChecker?section=THX&file=1138" &>'></jsp:include> but the output of that servlet call contains a jsp:include tag, to the file I was checking for. Unfortunately, the browser doesn't "include" it. I'm getting errors like "there is no attribute 'page'" and "element 'jsp:include' undefined" -- which suggests the servlet output is not being rendered as Java but as HTML. Here is the output: <p>Text before the servlet call</p> <p><h4>From THX1138</h4><jsp:include page='thx/results_1138.jsp'></jsp:include></p> <p>Text after the servlet call</p> Here is the main call of my servlet: private String FileChecker(String section, String file) { String result = ""; // assume file does not exist String pathToCheck = section + "/results_" + file + ".jsp"; // realPath is defined in the init() method as config.getServletContext().getRealPath("/"); File fileToCheck = new File(realPath + pathToCheck); if (fileToCheck.exists()) { result = "<p><h4>" + section + "</h4><jsp:include page='" + pathToCheck + "'></jsp:include></p>"; } return result; } I feel like the answer is close, but I'm not sure what curtain I should be looking behind. Any help? A: Do not write a string with a bunch of HTML and JSP tags to the response. This makes no sense. The webbrowser does not understand JSP tags. Call RequestDispatcher#include() instead. request.getRequestDispatcher(checkedJspPath).include(request, response); And move that HTML back into the JSP. Unrelated to the concrete question, I know that you're referring to an old answer of me, but I realize that it's actually better to check if ServletContext#getResource() doesn't return null instead of using File#exists(). This way it'll work as well whenever the WAR is not expanded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: core-plot remove decimal points from axis labels Can someone tell me how to remove the decimal points from the Axis labels? Instead of 10.0 I'd like to have only 10 showing. A: CPTXYAxis *x = axisSet.xAxis; NSNumberFormatter *Xformatter = [[NSNumberFormatter alloc] init]; [Xformatter setGeneratesDecimalNumbers:NO]; [Xformatter setNumberStyle:NSNumberFormatterDecimalStyle]; x.labelFormatter = Xformatter; [Xformatter release]; This will take care of the decimals on the x axis as well as add commas with NSNumberFormatterDecimalStyle. You will need to do the same for the y axis. There are a ton of things you can do with NSNumberFormatter, including converting numbers into dollars using: [Xformatter setNumberStyle:NSNumberFormatterCurrencyStyle]; //this will add a decimal point again if you put this in the code above Play around with the Esc key to see all formatting available for setNumberStyle or other methods. A: Set the labelFormatter property on the axis to a new formatter. This is a standard NSNumberFormatter object. See Apple's class documentation for details on the options available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Codeigniter session using ajax i know maybe it's a repetitive question, but i would like to know if someone has a good idea for leave user session alive when using ajax calls. I figured out that when i'm logged and i leave the browser open for 1-2 hours, when i launch ajax calls the session is expired. i'm using the standard: $config['sess_time_to_update'] = 7200; i would like to know if someone has the definitive way to keep alive the user session, better without using interval js functions A: The session time is set in the __construct() so you could just call any method from the session library when you are making the ajax call and it should update your session expiration time. I would probably just set an "ajax_request" item in the session just to call the library and fire the constructor to reset the session expiration time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does query with AND and OR operators yield unexpected results? I have this query but it's not giving me the expected results: User.all(:conditions => ["company_id == ? AND role_id == ? OR role_id == ? OR role_id == ?", X, 1,2,3 ]) It's supposed to mean: Get all the users with X company_id AND their roles can be either 1 or 2 or 3. So it can be either of those roles, but ALL of those users have to be from THAT company_id. A: It isn't working because the precedence is wrong. That is, company_id = ? AND role_id = ? OR role_id = ? OR role_id = ? is interpreted as ((company_id = ? AND role_id = ?) OR role_id = ?) OR role_id = ? because AND has higher precedence than OR -- but more relevant to this case -- they are also both are leftward-associative. The simple fix would thus be: company_id = ? AND (role_id = ? OR role_id = ? OR role_id = ?) (But see other answers for an alternative syntax and/or approaches. I also took the liberty of fixing the equality operator.) Happy coding. A: Could be a couple things. First use single equals =, not double equals == in :conditions => "...". Second, you could either use "...AND role_id IN (?,?,?)", X, 1, 2, 3]), or you need to group your role_id comparisons with parenthesis so it would be condition AND (condition OR condition OR condition). A: You may want to investigate https://github.com/binarylogic/searchlogic However otherwise you could say User.all(:conditions => ["company_id = ? AND role_id IN (?,?,?)", X, 1,2,3 ]) A: For future reference, this helped me a lot ease up this kind of finds, you could do: company_id = "X" role_ids = [1,2,3] User.find(:all, :conditions => "company_id=#{company_id} AND role_id IN (#{role_ids.join(',')})")
{ "language": "en", "url": "https://stackoverflow.com/questions/7519913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem using HDI membership provider with asp.net I am trying to use HDI custom membership provider and after seting up with web.config when I run the applcation it gives me an error as shown below. And I am unable to know where I am going wrong?Can anyone point me the right way? Failed to map the path '/'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Failed to map the path '/'. This is my web.config: <configuration> <connectionStrings> <add name="HDIConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"/> </connectionStrings> <system.web> <membership defaultProvider="HDIMembershipProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="HDIMembershipProvider" type="HDI.AspNet.Membership.HDIMembershipProvider" connectionStringName="HDIConnectionString" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" writeExceptionsToEventLog="false"/> </providers> </membership> <machineKey validationKey="34A0AF973A6817E4F7067DA1486E93AD5F7466B65D32405DB50766FDF335304F499C7B1943C084C7A67B1375D196CF02C8E84F297F7A0CA130C1D5722586749F" decryptionKey="48C8B6F952BC7C39DD91A2A17F17B08E113967DC5FF687FE6DFAF65F3248309C" validation="SHA1" decryption="AES"/> <authentication mode="Forms"/> <compilation debug="true" strict="false" explicit="true" targetFramework="4.0"> <assemblies> <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> </system.web> <system.net> </system.net> </configuration> A: I have rectified the problem just by starting Visual Studio as Administrator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery UI Tabs AJAX link with anchor I am trying to implement something quite simple, I want to have a tab menu, with submenu as anchor in tabs, let say : <div id="tabs"> <ul> <li><a href="file1.html">Nunc tincidunt</a> <ul> <li><a href="file1.html#anchor1">Et perditur</a></li> <li><a href="file1.html#anchor2">Proin elit arcu</a></li> </li> <li><a href="file2.html">Proin dolor</a></li> <li><a href="file3.html">Aenean lacinia</a></li> </ul> </div> I can easily switch tabs on the top level , but any attempts to access the file#anchor link failed, the best I could do was to actually open the right tab, but not go to the anchor. Any hint ? Working example ? A: Take a look at this answer https://stackoverflow.com/a/3330919/1285020 Here's an example using jquery address plugin http://www.asual.com/jquery/address/samples/tabs/
{ "language": "en", "url": "https://stackoverflow.com/questions/7519918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException I have a J2EE based web application which perfectly gets deployed on JBoss 6.0 app server. I am using JBoss's "default" server configuration. My ".ear" file contains EJBs and a ".war" file - I am using Spring Security 3x for user authentication and authorization. When I deploy the same ear file on JBoss 6.1, I find my WAR deployment fails with following errors. Surprising thing is: if I deploy the same ".ear" file in exploded format, then the deployment is successful. 22:31:14,827 INFO [StdSchedulerFactory] Quartz scheduler version: 1.8.3 22:31:14,828 INFO [QuartzScheduler] Scheduler EdmQuartzScheduler_$_NON_CLUSTERED started. 22:31:14,828 INFO [QuartzService] QuartzService(EdmQuartzMBean) started. 22:31:14,837 INFO [TomcatDeployment] deploy, ctxPath=/edm 22:31:14,896 INFO [[/edm]] Initializing Spring root WebApplicationContext 22:31:14,897 INFO [ContextLoader] Root WebApplicationContext: initialization started 22:31:14,907 INFO [XmlWebApplicationContext] Refreshing Root WebApplicationContext: startup date [Wed Sep 21 22:31:14 PDT 2011]; rootof context hierarchy 22:31:14,910 INFO [XmlBeanDefinitionReader] Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext-business.xml] 22:31:14,911 ERROR [ContextLoader] Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext-business.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext-business.xml] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) [:3.0.5.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) [:3.0.5.RELEASE] at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) [:3.0.5.RELEASE] at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93) [:3.0.5.RELEASE] at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) [:3.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) [:3.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) [:3.0.5.RELEASE] at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) [:3.0.5.RELEASE] at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) [:3.0.5.RELEASE] at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [:3.0.5.RELEASE] at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3369) [:6.1.0.Final] at org.apache.catalina.core.StandardContext.start(StandardContext.java:3828) [:6.1.0.Final] at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:294) [:6.1.0.Final] at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:146) [:6.1.0.Final] at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:476) [:6.1.0.Final] at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118) [:6.1.0.Final] at org.jboss.web.deployers.WebModule.start(WebModule.java:95) [:6.1.0.Final] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_27] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_27] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_27] at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_27] at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157) [:6.0.0.GA] at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96) [:6.0.0.GA] at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) [:6.0.0.GA] at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:271) [:6.0.0.GA] at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:670) [:6.0.0.GA] at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206) [:2.2.0.SP2] at $Proxy41.start(Unknown Source) at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:53) [:2.2.0.SP2] at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:41) [:2.2.0.SP2] at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.SP2] at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.SP2] at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.SP2] at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.SP2] at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:301) [:2.2.0.SP2] at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.SP2] at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.SP2] . . . . In my WAR's web.xml I have specified Spring configuration file locations as: <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext-business.xml /WEB-INF/applicationContext-security.xml </param-value> </context-param> I have verified that the XML files do not have any syntax issue and those files are indeed packaged under WAR's WEB-INF directory. Now I believe JBoss uses Tomcat which unpacks the WAR file. So it seems that the files cannot be found on the classpath when the WAR file is loaded and/or it is not being unpacked. I have no clue how it successfully works in JBoss 6.0 but fails on 6.1. There are more bug fixes in 6.1 but internal structure or libraries are not changed between these 2 releases. Can anyone please suggest why Spring cannot find those configuration files when the "ear" is deployed in archived/collapsed format? Do I need to package such configuration files under WEB-INF/classes or should I use any prefix like "classpath:" in tags? Many thanks in advance. A: I know we can fix this by adding the files in class path and changing the web.xml to <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:/resource/applicationContext-business.xml </param-value> </context-param>
{ "language": "en", "url": "https://stackoverflow.com/questions/7519920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using group and file references to imitate a real folder in Xcode I have the following directory structure: - container - app - index.html - ... - ios - mobile.xcodeproj - Mobile - www # imaginary folder (or could be a real, empty one) - android - ... app contains files shared among an Android and iOS application. I'd like to add a imaginary folder to my xcodeproject so that files in app look like they really are in www inside the ios directory (../app should look like ./www). I need to exclude certain files in the app directory, thus I can't simply use a symlink and add that folder, because then I can't selective exclude certain files. The reason why I'm going through this trouble is that PhoneGap searches for the file index.html inside the www directory, which don't exist in my case so I need to somehow fake its existence. Anyone know how to solve this? My guess is to setup folder groups and add file-references, but I can't get it to work properly. Also, let me know if I should elaborate on something. A: Note that when you create a group, you can then specify where the root folder of that group is with Xcode. In Xcode 4.x, click on the group icon on the left pane. Open the rightmost pane and click on the top icon that looks like a document. You'll see "Identity" underneath is "Group Name", "Path", then another entry with no label that has a window-like icon to the right. Click on that icon to set which folder the group aligns with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to condense/collate multiple jQuery events into one event on a time delay? I want to condense multiple events into a single event on a time delay. I don't need my bound function to be called repeatedly for really common things like mouse movement and page scrolling. At most, once every half second would be plenty if there is a queued event to fire. For the sake of a more concrete example: Let's say I bind to jQuery(...).scroll() with a somewhat expensive function. As the user scrolls the page, this will get called hundreds, possibly thousands of times. I want to condense all those events into one event call per .5 seconds, sending the most recent event to the handler after .5 seconds has passed and IGNORING previous events that would have fired. Visually: * *15:20:35.000 - User scroll event. Timer starts. New event stored. *15:20:35.020 - User scroll event. Replace stored event. *15:20:35.100 - User scroll event. Replace stored event. *15:20:35.371 - User scroll event. Replace stored event. *15:20:35.500 - Timer expires. Event from 15:20:35.371 is sent to the registered handler/callback. None of the earlier events get sent. BTW, a couple months ago I found a jQuery plugin somewhere that specifically did exactly this and had some nice features too but now I can't find it again or any similar plugin. I would much rather find a working plugin than reinvent the wheel and hack together a solution (but I'll take the hack). A: Here is a jQuery plugin (not by me) that introduces the scrollstart and scrollend events. You can change the time delay inside the function by modifying the latency parameter. I am using this in a current project, and it works great.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display iframe div contents on parent page I'm sure this is pretty basic, but I can't seem to get any of the solutions I've found to work for me. Basically, I need to get the contents of a div from an iframe, and write them to a div in the parent page. This is what I have: <iframe src="slideshows/slideshow/case2.html" frameborder=0 scrolling="no" id="frame1" name="frame1"></iframe> <div id="caption"> <script type="text/javascript"> var caption = frame1.document.getElementById('slidecaption'); document.write(caption); </script> </div> 'slidecaption' is the name of Id in the iframe that I'm trying to grab. All I get is "null". Is it because the iframe contents haven't loaded yet? If so, how do I delay until the iframe has loaded? Thanks, Scott Thanks to both of you for your help. I figured it out, based on Márcio's idea: I put the function in the parent page: <script type="text/javascript"> function send() { document.getElementById('slidecaption').innerHTML = frame1.document.getElementById('slidecaption').innerHTML} </script> And I put the call in the iframe document: <body onload="parent.send();"> Regards, Scott A: I'm not sure this is the only thing you need to do, but you certainly need to retrieve frame1 from the dom. <script type="text/javascript"> var frame1 = document.getElementById('frame1'); var caption = frame1.contentWindow.document.getElementById('slidecaption'); document.write(caption); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7519934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Painting a Triangle and Trying to use other Swing Objects I am having a bit of an issue using Netbeans to design a GUI (Yeah im lazy :\ ) and manually trying to paint a triangle onto the JFrame. The Swing Components are 'covered up' until I press tab and put focus on the objects. Ive attached a picture and code below of the issue. All of the auto generated code for the GUI is in the initComponents() portion of the code. And the Triage generating is in the override code for the JFrame Paint method. What it looks like is happening is the initComponents code is run before the paint, since the object is created before setVisibile(true). Once setVisible(true) is called then the paint method paints over all of the generated objects initComponents created. Just looking for a solution so that nothing gets covered up. Any help would be appreciated. $/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * SimpleClient.java * * Created on Sep 22, 2011, 11:38:30 AM */ package Assignment3; import java.awt.Graphics; /** * * @author Mark */ public class SimpleClient extends javax.swing.JFrame { /** Creates new form SimpleClient */ public SimpleClient() { initComponents(); } public void paint(Graphics g) { int[] xPoints = {100, 100, 200}; int[] yPoints = {100, 200, 200}; g.drawPolygon(xPoints, yPoints, 3); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTextField1 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setText("jTextField1"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(103, 103, 103) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(238, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(220, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60)) ); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SimpleClient().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTextField jTextField1; // End of variables declaration } A: Don't override the paint() method of a Top Level Container (JFrame, JDialog...). Custom painting is done by override the paintCompnent() method of a JPanel (or JComponent). Then you add the component to the content pane of the frame. Don't forget to also override the getPreferredSize() method of the component so the layout managers will work properly. Read up on Custom Painting for more information and working examples. A: Some quick recommendations: * *Don't draw directly in the JFrame. *Draw instead in a JComponent such as a JPanel. *Override the paintComponent method of the JPanel, not the paint method. *Call super.paintComponent(g), usually as the first method call of your paintComponent method to allow your JPanel to do its housekeeping and to erase old images. *Read several tutorials on Swing graphics because for many of us (me especially), it's not intuitive and you'll have to break some assumptions to do it correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Online payments for a middleman I'm new to online payments and would like some opinions on my task. Here is the scenario: I have a website where people buy and sell digital photos. A seller has a photo and wants to sell it. They create an ad on the site and upload the photo into the website database. Buyers looking for photos come to the site and buy them. The buyer pays the asking amount and then can download the photo. As the middleman, I'd like to charge the seller a fee or percentage of the selling price. The buyer shouldn't pay any website fees, just the selling price. My question is - what is the best way to do this? I dont mean programmatically, but what service should I be looking at? As far as I know PayPal wont work because of their fee structure. Im told Amazon payments would work but its sort of a hack. The seller has to set up a business account and then tie their item to my website as a third party sales venue. Is there an easire way to accomplish what Im trying to do? Of course keeping fees as low was possible. A: This will work perfectly fine with PayPal. PayPal offers Adaptive Payments as of a while ago, which allows you to specify 'primary' and 'secondary' receivers (up to 10 recievers per 1 transaction I believe, from the top of my head). You could thus use Adaptive Payments to set the photographer as the primary receiver, set yourself as the secondary receiver and optionally move the transaction fees onto the photographer as well. Have a look at this page for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: MSI - How to know when a particular MSI is running Is there a simply way to know when an msi is running? (either in silent or no silent mode.) Maybe using and MSI API? Reading from somewhere?... I need this in order to avoid launching a program coded in C++. Thanks for your help. A: There isn't any API for detecting running installers. Also, an MSI installation has two sequences: * *the installation UI -> InstallUISequence *the actual installation process -> InstallExecuteSequence InstallUISequence uses a process which runs under the current user account. InstallExecuteSequence uses a process which is a child of the Windows Installer service. So there's not an easy way for detecting a running installation. The only solution I can think of is enumerating all open windows and trying to find an installation dialog by name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery tagit plugin, public methods Does anyone know if the tagit jQuery plugin has a public method for removing just 1 specified tag from the list? I saw there is for removing (clear) all tags from the list, but I would need to remove only 1 tag :P Also, how to call all the public methods from outside of tagit() call? A: No, it does not. Just wrap a public function around _popTag in the widget code, e.g. removeTag : function(label,value) { this._popTag(label, value); } and call it like this: $(myElement).tagit("removeTag", label, value); A: If you're using the jQuery UI Tag-it plugin by aehlke, then these instructions will provide the plugin with this functionality: Syntax: // removes the tag called "outdated-tag" $("#mytags").tagit("removeTagByName","outdated-tag"); Add this method right below the removeAll method in the tag-it.js file: removeTagByName: function(tagName) { var that = this; this.removeTag(this.tagList.children('.tagit-choice').find("input[value='"+ tagName +"']").parent(), null); } NOTE: You are modifying a code library! So be sure to document what you're doing with clear code comments and otherwise documenting this change so that when you or a colleague update the plugin to another version, you're sure to include this functionality and not be baffled by why things suddenly stopped working ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7519945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to put sounds in an array? I have 10 sounds, and it would be easier for me to put them into an array. However I'm new to Obj C. Here is the code so far, this is just for 1 sound. I could copy and paste it 10 times. But if all 10 sounds are in an array I'll be able to do more functions with the sounds. - (IBAction)oneSound:(id)sender; { NSString *path = [[NSBundle mainBundle] pathForResource:@"Vocal 1" ofType:@"mp3"]; if (oneAudio) [oneAudio release]; NSError *error = nil; oneAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; if (error) NSLog(@"%@",[error localizedDescription]); oneAudio.delegate = self; [oneAudio play]; } thanks A: Heres one way, NSMutableArray *soundArray = [NSMutableArray arrayWithCapacity:10]; [soundArray addObject:oneAudio]; . . . [soundArray addObject:tenAudio]; or you could also put the paths to the audio content into the Array and instantiate them when required. A: Take the file paths of the arrays, make them into strings, add THOSE to the array, and access them only when needed, or else you'll be using up a lot of memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Speech recognition framework for iOS that supports Spanish Is there a speech to text framework for iOS that supports Spanish out of the box? Commercial or OS is ok. A: There are a bunch of commercial IOS librariers for speech recognition. The names I keep hearing are Nuance, iSpeech, and Yapme. Each offers cloud speech recognition (off the device) and a client library and SDK to build into your app. Nuance seems to support Spanish - http://blog.dragonmobileapps.com/2011/01/mobile-app-developer-dragon-mobile-sdk.html ...you can speech-enable your app for including US and UK English, European Spanish, European French, German, Italian and Japanese---with even more languages on tap for 2011! and now Nuance gives developers free access - http://www.masshightech.com/stories/2011/09/26/daily13-Nuance-tweaks-mobile-dev-program-with-free-access-to-Dragon.html iSpeech is likely to support Spanish - http://www.ispeech.org/developers/iphone iSpeech's Mobile SDKs support 27 TTS and ASR (defined grammar) languages and 15 languages for free-form dictation voice recognition. Yapme, sorry, I'm not sure - http://yapinc.com/speech-cloud.html A: Take a look here: http://src.chromium.org/viewvc/chrome/trunk/src/content/browser/speech/ It's the Chrome Browser Speech to search...... you can do it in Objective-C. Try go google.com on chrome browser and if spanish is recognized, you win! :) You can easily use: - (void) SpeechFromGooglezzz { NSURL *url = [NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US"]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; NSString *filePath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.flac"]; NSData *myData = [NSData dataWithContentsOfFile:filePath]; [request addPostValue:myData forKey:@"Content"]; [request addPostValue:@"audio/x-flac; rate=16000" forKey:@"Content-Type"]; [request startSynchronous]; NSLog(@"req: %@", [request responseString]); } Remember that you must recording a 16000 bitrate FLAC file! Or nothing! Google responds with a json containing the words. hope this helps. A: I've written a client library for the Google Speech APIs. Works best with iOS and also supports other Unix-like systems: Edit: try here: https://github.com/H2CO3/libsprec
{ "language": "en", "url": "https://stackoverflow.com/questions/7519947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Discovering the reason for File.mkdirs() failure If I call one of the methods File.mkdir() or File.mkdirs() in Java, and it returns false, is there a way to know why was the directory not created? A: Not really, no. If a SecurityException is NOT thrown, then the most likely cause is a typo in the path, meaning you've accidentally specified a parent path to the new directories that is somehow invalid. I don't suppose you have it wrapped in a try { ... } catch (Exception e) block, where you don't realize a SecurityException is being thrown, because you're catching an ancestor of SecurityException, do you? If you have a high belief that everything looks right, and it still fails, I suppose you could simply put it in a loop to retry, say, three times. If it still fails, and depending on your application, you might raise some kind of alert at the UI level, or log the error in a log file (assuming you can write to it). I suppose it's possible that some deeper I/O issue is preventing it from working, but beyond simply notifying the user of a failure there isn't much you can (or really should) do at an application level. If there's something deeper in the I/O wrong, that's more likely a problem with the system/hardware/OS, or something completely wonky that you have no control over like a subsystem/service crash. ...and if that's happening, that's the responsibility of the IT guy to fix, not your application. Unless of course your app is somehow causing the crash. A: I had a mkdirs() failure on windows on a UNC path. The code looks like this: public File getOldDirectoryPath(String root, String name) { File fulldir = new File(root, name) boolean created = false int retry = 0 while (!created) { retry++ if (!(created = fulldir.exists())) { if (20 == retry) break if (!fulldir.mkdirs()) { sleep(100) fulldir = new File(root, name) } } } return fulldir.exists() ? fulldir : null } There appears to be some sort of caching involved where exists() returns false (does not exists) but the mkdir on the file system fails because it does exist. Recreating the File() entry or lengthing the timeout did not make a difference. I discovered a plugin on elasticsearch to fix a SMB problem on Windows. Researching the solution, it uses nio.file instead of io.File. Rewriting the function fixed the issue: public File getDirectoryPath(String root, String name) { Path fulldir = Paths.get(root, name) boolean created = false int retry = 0 while (!created) { retry++ if (!(created = Files.isDirectory(fulldir))) { if (20 == retry) break try { Files.createDirectories(fulldir) } catch (Throwable thx) { // error handling } } } return fulldir.toFile() } createDirectories() sometimes fail, but recovers where mkdirs() does not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Escaping shell / database with utf-8 characters What is the preferred order for escaping characters? For instance in PHP environment: 1) shell -> database = return escapeshellcmd(mysqli_real_escape_string($string));? 2) database -> shell = return mysqli_real_escape_string(escapeshellcmd($string));? 3) No difference at all? Update Just to clarify, the website I'm currently trying to fix, contains a lot of old, deprecated functions, uses magic_quotes and is basicly, unusable after the transfer from old host to current one, where the problems arose. First problem was MySQL escaping, that I fixed with mysql_real_escape_string();, but, still the problem with CLI/Socket MySQL connection environment persists. That is, when you have a value inside a textarea that refers to a UNIX command, preceded by a / - forward slash symbol and you post it- Apache results in 501 Method Not Implemented. So yes, I have to escape mysql, and escape shell commands. But, the shell command escaping (with example no. 1 from original question) resulted in UTF-8 character braking and losing lots of needed HTML symbols. The content that needs to be escaped comes out of an WYSIWYG editor (SPAW), therefore it contains lot of quotes and from time to time a UNIX command, that resembles our nations - Latvia - currency. "/ls", where LS is the currency. The website is updated by client itself, not a tech person and it has to stay that way- I mean, we cannot take over the content editing. Plus, while we could tell them not to use /ls the UNIX problem persists if, for example, they accidentally get to /mkdir what could resemble an identificator of something. They are an active travel company, therefore this needs to be fixed ASAP. Since we overtook their website, they are aware that the system is broken, but they don't have free money at the moment to spend on a new website/fixing current one. Where we have made a conclusion that fixing it would be harder, therefore more expensive than to move over to our CMS, but money is still money. So, how do I escape shell and database commands from this WYSIWYG editor's textarea, that is a single string, but, while preserving UTF-8 encoding of our Latvian alphabet letters - ā, š, č, ž etc.? Maybe I don't have to escape both, that's why I'm asking. Thanks in advance! Update On Shrapnels' request, an example string (copied from SPAW's HTML view) that would cause Apache to respond with 501: <div> <span style="color: rgb(0, 0, 128); " class="Apple-style-span"> <span style="font-size: 12px; " class="Apple-style-span"> /ls </span> </span> </div> SPAW automatically adds all these dumb elements, and yes, if /<command> is inside the string, 501! And that's all what it takes to halt, just a namespace referring to a UNIX command line function. Like in this case /ls, but could be /rmdir, /mkdir etc. You could have 20000 symbol stuff there with no /ls and it'll work. Once there is something like this - bam, dead! There was originally a function that was meant to clear all the errors (at least I suppose so, it's original name was - removeShit();): $string = $_POST['wysiwyg_textarea']; // SPAW text area function removeStuff($string){ return str_replace('/wysiwyg/empty.html', '', $txt); } The file /wysiwyg/empty.html is 0 bytes- completely empty file. But this doesn't cure the mysql escaping and/or UNIX shell command recognition. Therefore, I need a fix to escape the UNIX commands and any MySQL harmful stuff. So, I was trying to do it with: return escapeshellcmd(mysqli_real_escape_string($string)); But this one strap out all the utf-8 characters, plus, all the new line symbols got converted to simple string "rn" from, I'd guess \r\n. And now I'm looking for a function to escape MySQL and Shell cmd`s in one, because I cannot think of another way how to cure all this mess. A: Neither. Use either escapeshellcmd() or mysqli_real_escape_string(), depending on what you are planning to do with $string. Never use both at the same time. It wouldn't make sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement 'either-or' scenario in left outer joins in SQL I am a newbie in SQL queries and am really struggling with the following query. I have to implement something like this: Select person.name, person.age, employee.yearsofservice from person join employee on person.name = employee.name join fulltimeemployed on person.name = fulltimeemployed.name join parttimeemployed on person.name = parttimeemployed.name where fulltimeemployed.manager = 'Rob' or parttimeemployed.manager = 'Rob' Basically I want to extract a list of all full time and part time employees who has their manager as 'Rob'. But the above query gives empty result since the employee cannot be present in both fulltimeemployed as well as parttime employed table. So I need a way to implement a OR clause between those 2 joins (fulltimeemployed and parttimeemployed). Please suggest any ideas :( A: select person.name, person.age, employee.yearsofservice from person join employee on person.name = employee.name join ( select name from fulltimeemployed where manager = 'Rob' union all select name from parttimeemployed where manager = 'Rob') employed on person.name = employed.name A: You should do left outer joins for this: Select person.name, person.age, employee.yearsofservice from person join employee on person.name = employee.name left outer join fulltimeemployed on person.name = fulltimeemployed.name left outer join parttimeemployed on person.name = parttimeemployed.name where fulltimeemployed.manager = 'Rob' or parttimeemployed.manager = 'Rob' A: I question the need to have an employee table and then two different tables for full vs. parttime as well as the wisdom of joining on names, but this would work as well (notice I join fulltimeemployed and parttimeemployed to employee and not person): Select p.name ,p.age ,e.yearsofservice from person AS p join employee AS e on p.name = e.name left outer join fulltimeemployed AS ft on p.name = ft.name AND ft.Manager = 'Rob' left outer join parttimeemployed AS pt on p.name = pt.name AND pt.manager = 'Rob' A: Select person.name, person.age, employee.yearsofservice from person join employee on person.name = employee.name left join fulltimeemployed on person.name = fulltimeemployed.name and fulltimeemployed.manager = 'Rob' left join parttimeemployed on person.name = parttimeemployed.name and parttimeemployed.manager = 'Rob' where fulltimeemployed.id is not null or fulltimeemployed.id is not null
{ "language": "en", "url": "https://stackoverflow.com/questions/7519956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove duplicates in Table Join with Case Statement I need to be able to select distinct "phone" regardless if the phone comes from work or home. All phones need to be unique. This query produces duplicates when the same phone is found in work and home in different rows. SELECT CASE WorkPhone WHEN '' THEN HomePhone ELSE WorkPhone END AS Phone ,MAX(LastName) ,MAX(FirstName) FROM TableA WHERE (statusid = Inactive) AND (modifieddate > '11/11/2011') AND NOT EXISTS (SELECT Phone FROM TableB WHERE Phone = WorkPhone OR Phone = HomePhone) AND NOT EXISTS ( SELECT AreaCode + PhoneNumber FROM TableC WHERE (AreaCode = LEFT(WorkPhone,3) AND PhoneNumber = Substring(WorkPhone, 4, 7) ) OR (AreaCode = LEFT(HomePhone,3) AND PhoneNumber = Substring(HomePhone, 4, 7)) ) GROUP BY WorkPhone, HomePhone A: You should group by: CASE WorkPhone WHEN '' THEN HomePhone ELSE WorkPhone END instead of grouping by WorkPhone, HomePhone
{ "language": "en", "url": "https://stackoverflow.com/questions/7519959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is a foreach loop on $_GET a good way to apply htmlspecialchars? I'm wondering if there is a significant downside to using the following code: if(isset($_GET)){ foreach($_GET as $v){ $v = htmlspecialchars($v); } } I realize that it probably isn't necessary to use htmlspecialchars on each variable. Anyone know offhand if this is good to do? UPDATE: Because I don't think my above code would work, I'm updating this with the code that I'm using (despite the negativity towards the suggestions). :) if(isset($_GET)){ foreach($_GET as $k=>$v){ $_GET[$k] = htmlspecialchars($v); } } A: This totally depends on what you want to do. In general, the answer is "no", and you should only escape data specifically for their intended purpose. Randomly escaping data without purpose isn't helping, and it just causes further confusion, as you have to keep track of what's been escaped and how. In short, keep your data stored raw, and escape it specifically for its intended use when you use it: * *for HTML output, use htmlentities(). *for shell command names, use escapeshellcmd(). *for shell arguments, use escapeshellarg(). *for building a GET URL string, use urlencode() on the parameter values. *for database queries, use the respective database escape mechanism (or prepared statements). This reasoning applies recursively. So if you want to write a link to a GET URL to the HTML output, it'd be something like this: echo "<a href=" . htmlentities("$url?q=" . urlencode($var)) . ">click</a>"; It'd be terrible if at that point you'd have to remember if $var had already previously been escaped, and how. A: Blanket escaping isn't necessary, and it's possibly harmful to the data. Don't do it. Apply htmlspecialchars() only to data that you are about to output in a HTML page - ideally immediately before, or directly when you output it. A: It won't affect numbers, but it can backfire for string parameters which are not intended to be put in HTML code. You have to treat each key different depending on its meaning. Possibility of generalization also depends on your application. A: The way you're doing it won't work. You need to make $v a reference, and it breaks for anything requiring recursion ($_GET['array'][0], for example). if(isset($_GET)) { foreach($_GET as &$v) { $v = htmlspecialchars($v); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python pull back plain text body from message from IMAP account I have been working on this and am missing the mark. I am able to connect and get the mail via imaplib. msrv = imaplib.IMAP4(server) msrv.login(username,password) # Get mail msrv.select() #msrv.search(None, 'ALL') typ, data = msrv.search(None, 'ALL') # iterate through messages for num in data[0].split(): typ, msg_itm = msrv.fetch(num, '(RFC822)') print msg_itm print num But what I need to do is get the body of the message as plain text and I think that works with the email parser but I am having problems getting it working. Does anyone have a complete example I can look at? Thanks, A: To get the plain text version of the body of the email I did something like this.... xxx= data[0][1] #puts message from list into string xyz=email.message_from_string(xxx)# converts string to instance of message xyz is an email message so multipart and walk work on it. #Finds the plain text version of the body of the message. if xyz.get_content_maintype() == 'multipart': #If message is multi part we only want the text version of the body, this walks the message and gets the body. for part in xyz.walk(): if part.get_content_type() == "text/plain": body = part.get_payload(decode=True) else: continue A: Here is a minimal example from the docs: import getpass, imaplib M = imaplib.IMAP4() M.login(getpass.getuser(), getpass.getpass()) M.select() typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0][1]) M.close() M.logout() In this case, data[0][1] contains the message body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Configure date-time format for JODA in Jackson when deserializing I am using "Full Data Binding" in Jackson to deserialize a date in a JSON string. The format these dates are coming is "EEE MMM dd HH:mm:ss zzz yyyy". I'm using Jackson 1.8 and I cannot figure out how to configure the ObjectMapper so it would deserialize these Strings properly into JODA DateTime objects. Snippet from the POJO: private DateTime deliveryTime; @JsonProperty("DeliveryTime") public void setDeliveryTime(DateTime deliveryTime) { this.deliveryTime = deliveryTime; } @JsonProperty("DeliveryTime") public DateTime getDeliveryTime() { return deliveryTime; } Thanks. A: The simplest way to configure ObjectMapper to use specific date/time format is to call ObjectMapper.setDateFormat(...) method. There are some preliminary plans in creating a new Joda datatype Jackson module, as that would make it much easier to add powerful new configuration; current challenge being that Jackson itself should not have hard (static) dependency to external libraries (as much as I like Joda personally!), which limits degree to which lib-specific configurability can work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Display a new view when button in cell is pressed I have data displayed in a customized cell view. A cell contains a title and a button. When a user clicks on the button, the page will re-direct to a new view. Now what I need to do is, when the user clicks on the button (and not the cell), the title of the cell should be displayed on the new view that will be loaded. How should I code this? A: Here are a few tips you should try out. * *When you push the view controller ( inside the IBaction of that button that gets pressed) to the next view, implement the title of the next view accordingly. *Use tags for the buttons and logically form a link between them and the uiTableViewCell in which you implemented the button. *Set the cell.textLabel.text value to the nextViewController.title. A: You must first add button to cell and set button as Accessory of Table Cell : myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [myButton setFrame:CGRectMake(50, 100, 20, 10)]; [cell addSubview:myButton]; cell.accessoryView = myButton; [myButton addTarget:self action:@selector (ActionMethod) forControlEvents:UIControlEventTouchUpInside]; Now in the ActionMethod you have to put the logic for pushing it to a new view : -(void) ActionMethod { myViewController *Obj=[[myViewController alloc]init]; [self.navigationController pushViewController:Obj animated:NO]; [Obj release]; } Hope it helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redis mimic MASTER/MASTER? or something else? I have been reading a lot of the posts on here and surfing the web, but maybe I am not asking the right question. I know that Redis is currently Master/slave until Cluster becomes available. However, I was wondering if someone can tell me how I would want to configure Redis logistically to meet my needs (or if its not the right tool). Scenerio: we have 2 sites on opposite ends of the US. We want clients to be able to write at each site at a high volume. We then want each client to be able to perform reads at their site as well. However we want the data to be available from a write at the sister site in < 50ms. Given that we have plenty of bandwidth. Is there a way to configure redis to meet our needs? our writes maximum size would be on the order of 5k usually much less. The main point is how can i have2 masters that are syncing to one another even if it is not supported by default. A: This is probably best handled as part of your client - just have the client write to both nodes. Writes generally don't need to be synchronous, so sending the extra command shouldn't affect the performance you get from having a local node. A: It's about 19ms at the speed of light to cross the US. <50ms is going to be hard to achieve. http://www.wolframalpha.com/input/?i=new+york+to+los+angeles A: The catch with Tom's answer is that you are not running any sort of cluster, you are just writing to two servers. This is a problem if you want to ensure consistency between them. Consider what happens when your client fails a write to the remote server. Do you undo the write to local? What happens to the application when you can't write to the remote server? What happens when you can't read from the local? The second catch is the fundamental physics issue Joshua raises. For a round trip you are talking a theoretical minimum of 38ms leaving a theoretical maximum processing time on both ends (of three systems) of 12ms. I'd say that expectation is a bit too much and bandwidth has nothing to do with latency in this case. You could have a 10GB pipe and those timings are still extant. That said, transferring 5k across the continent in 12ms is asking a lot as well. Are you sure you've got the connection capacity to transfer 5k of data in 50ms, let alone 12? I've been on private no-utilization circuits across the continent and seen ping times exceeding 50ms - and ping isn't transferring 5k of data. How will you keep the two unrelated servers in-sync? If you truly need sub-50ms latency across the continent, the above theoretical best-case means you have 12ms to run synchronization algorithms. Even one query to check the data on the other server means you are outside the 50ms window. If the data is out of sync, how will you fix it? Given the above timings, I don't see how it is possible to synchronize in under 50ms. I would recommend revisiting the fundamental design requirements. Specifically, why this requirement? Latency requirements of 50ms round trip across the continent are usually the sign of marketing or lack of attention to detail. I'd wager that if you analyze the requirements you'll find that this 50ms window is excessive and unnecessary. If it isn't, and data synchronization is actually important (likely), than someone will need to determine if the significant extra effort to write synchronization code is worth it or even possible to keep within the 50ms window. Cross-continent sub-50ms latency data sync is not a simple issue. If you have no need for synchronization, why not simply run one server? You could use a slave on the other side of the continent for recovery-only purposes. Of course, that still means that best-case you have 12ms to get the data over there and back. I would not count on 50ms round trip operations+latency+5k/10k data transfer across the continent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Tfs custom work item value migration I have a task to create reports about various work items from a Team Foundation Server 2010 instance. They are looking for more information than the query tools seem to expose which is why I am not using the OOB reporting capabilities. The documentation on creating custom reports against TFS identify the Tfs_Analysis cube and the Tfs_Warehouse database as the intended sources for reporting. They have created a custom work item, "Deployment Requests", to track requests for code migrations. This work item has custom urgency levels (critical, medium, low). According to Manually Process the Data Warehouse and Analysis Services Cube for Team Foundation Server, every two minutes my ODS (Tfs_DefaultCollection) should sync with the Tfs_Warehouse and every 2 hours it hits the Tfs_Analysis cube. The basic work items correctly show up in my Tfs_Warehouse except not all of the data makes it over, in particular, the urgency isn't getting migrated. As a concrete example, work item 19301 was a deployment request. This is what they can see using the native query tool from the web front-end. I can find it in the Tfs_DefaultCollection and the "Urgency" is mapped to Fld10176. SELECT Fld10176 AS Urgency , * FROM Tfs_DefaultCollection.dbo.WorkItemsAre WHERE ID = 19301 trimmed results... Urgency Not A Field Changed Date 1 - Critical - (Right Away) 58 2011-09-07 15:52:29.613 If I query the warehouse, I see the deployment request and the "standard" data (people, time, area, etc) SELECT DWI.System_WorkItemType , DWI.Microsoft_VSTS_Common_Priority , DWI.Microsoft_VSTS_Common_Severity , * FROM Tfw_Warehouse.dbo.DimWorkItem DWI WHERE DWI.System_Id = 19301 Trimmed results System_WorkItemType Microsoft_VSTS_Common_Priority Microsoft_VSTS_Common_Severity Deployment Request NULL NULL I am not the TFS admin (first exposure to TFS is at this new gig) and thus far, they've been rather ...unhelpful. * *Is there be a way to map that custom field over to an existing field in the Tfs_Warehouse? (Backfilling legacy values would be great but fixing current/future is all I need) *Is there a different approach I should be using? A: Did you mark the field as reportable? See http://msdn.microsoft.com/en-us/library/ee921481.aspx for more information about this topic. A: Based on Ewald Hofman's link, I ran C:\Program Files\Microsoft Visual Studio 10.0\VC>witadmin listfields /collection:http://SomeServer/tfs > \tmp\witadmin.txt and discovered a host of things not configured Reportable As: None At this point, I punted the ticket to the TFS admins and indicated they needed to fix things. In particular, examine these two fields Field: Application.Changes Name: ApplicationChanges Type: PlainText Use: Project1, Project2 Indexed: False Reportable As: None or Field: Microsoft.VSTS.Common.ApplicationChanges Name: Application Changes Type: Html Use: Project1, Project2 Indexed: False Reportable As: None It will be a while before the TFS Admins do anything but I'm happy to accept Edwald's answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: iOS: How to get swipe effect between views of tabbed view controller? I keep seeing apps that appear to be tabbed view controller apps, where the user can easily swipe left or right between views. How do I enable that kind of behavior? Thanks. A: The best and least hassle free solution I found is Andrey Tarantsov's ATPagingViev class. Works just like a UITableView, i.e. how many pages do you want, scroll horiz or vert. provide view for page, etc. Very easy and well coded. It's here: SoloComponents It also has a recycling feature so it's memory stable. A: If you refer to something like Apples photo app, it is using UIScrollView which has a property to enable paging. If you define the views content width wider than your view's frame, you'll get the effect you describe. The view will page in steps of it's bounds width. On each page you can place another view. http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html A: Another option I found is SwipeView: https://github.com/nicklockwood/SwipeView
{ "language": "en", "url": "https://stackoverflow.com/questions/7519987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CDT compare broken? Help. I have been relying on the compare editor for code review, and it mostly works quite well. But for some reason, on some files, it is giving me inconsistent results and telling me that some code is different when it is not. It can't seem to deal with commented out code in this file. It tells me that later functions are different and tries to match lines in those functions. I have also found cases where it simply thinks the code is different but it is not. It then decides that there must be changes in hundreds of lines below this. I am able to work around by remove the code with #if 0, #endif, but it is not pretty. Has anyone else seen this and do you know of any way to fix it? I am trying to get a clean diff do I can see just the actual changes between the files. It is driving me to drink - and it is still early in the day!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: writeToFile fails - how do I debug WHY it fails (what tools)? I'm getting an NSDictionary from JSON (using SBJson), and I want to store it. I'm using [liveData writeToFile:localFilePath atomically:YES] and it fails. The data looks like its all NSString, NSDictionary, and NSArray (which "atomically:YES" demands). I used the same localFilePath elesewhere. So my question is: how can I find out where the problem is? What tools can I use to understand why writeToFile fails? The log doesn't show an error message. A: It may have multiple reasons: * *The path you are writing to is wrong, not writable (you don't have write access to it), or the parent directory does not exists (if localFilePath is "/path/to/file.plist" but the directory "/path/to/" does not exists, it will fail) *The liveData dictionary does contains objects that are not PropertyList objects. Only NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary objects can be written into a Property List file (and writeToFile:atomically: do write to a plist file so the dictionary do have to contains only PList objects for that method to succeed) A: I know this is a 2 year old question. But since I just had this same problem and fixed it here's what I found. I bet your NSDictionary has some keys that are not NSStrings. Instead of keying like: [_myDictionay setObject:thisObj forKey:[NSNumber numberWithInt:keyNumber]]; Key like: [_myDictionay setObject:thisObj forKey:[NSString stringWithFormat:@"%i",numberWithInt:keyNumber]]; That fixed my problem right up. The top way can't be saved to a plist file. Since you're getting your info from a JSON conversion, it is possible that there are some objects or keys that are NSNumbers in there. You would have to convert them. But that's a pain. So since you already have it in json, just store it as the json string in its entirety in a @"data" key and the re-expand it when you load the plist later back into your array or dict. A: I've tried saving an NSDictionary to disk with only numbers for keys and values. Switching the keys to NSString works but not when they keys are NSNumber. Do keys have to be NSString? EDIT: I know better now that it can be any object that responds to hash; often it's NSString's, though. A: Old thread : But this apple thread would be nice to read. Basically iOS has issue in Cache directory. For 1000+ folders it returns error. I would suggest to add your own atomic mechanism to write file as a fallback. https://developer.apple.com/forums/thread/128927
{ "language": "en", "url": "https://stackoverflow.com/questions/7519996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Getting value from Map I need to get one data from a collection (get() calls in the range of 100K for a single file processing). public class DemoCollection { private Map<GroupCriteria, GroupData> collectionHolder = new ConcurrentHashMap<GroupCriteria, GroupData>(); /** * * @param groupCriteria * GroupCriteria * @return GroupData */ public GroupData getGroupForGroupingCriteriaOne(GroupCriteria groupCriteria) { GroupData groupData = null; if (collectionHolder.containsKey(groupCriteria)) { groupData = collectionHolder.get(groupCriteria); } else { // Get from database } return groupData; } /** * * @param groupCriteria * GroupCriteria * @return GroupData */ public GroupData getGroupForGroupingCriteriaTwo(GroupCriteria groupCriteria) { GroupData groupData = null; if ((groupData = collectionHolder.get(groupCriteria)) == null) { // GEt from database } return groupData; } } Which is the best practice in this regard ? The approach one (getGroupForGroupingCriteriaOne) , two (getGroupForGroupingCriteriaTwo) or neither ? Usually I ignore these premature optimization things, but since the get() calls are too huge I'm little bothered. Could you please advice ? A: getGroupForGroupingCriteriaTwo is the way to go because you're asking the map to do the key lookup once instead of twice. A: getGroupForGroupingCriteriaTwo looks perfectly reasonable. getGroupForGroupingCriteriaOne makes two lookups to the Map - one for searching the 'key' and the other for fetching the value. However, I am hoping that after fetching from database, you would put the object into the Map (as a cache) so that the same can be used from the Map next time, rather than querying. A: Version two is probably better for the reasons pointed out by others, but why not be less cryptic... public GroupData getGroupForGroupingCriteriaThree(GroupCriteria groupCriteria) { GroupData groupData = collectionHolder.get(groupCriteria); return groupData != null ? groupData : callGetDataFromDB(); } A: Consider using Guava's MapMaker: private ConcurrentMap<GroupCriteria, GroupData> collectionHolder = new MapMaker() .makeComputingMap( new Function<GroupCriteria, GroupData>() { @Override public GroupData apply(GroupCriteria key) { //get from database and return } }); This ConcurrentMap will handle all concurrent requests for you. See the MapMaker documentation for a list of all configurable features of the produced map. A: In general I agree with the responses that getGroupForGroupingCriteriaTwo is better since it accesses the map only once, however your concern that since the map holds 100K items the access time will be high is misplaced. You are using a ConcurrentHashMap, HashMap lookups have computation complexity of O(1) which means irrespective of the size of the data, these calls will return in constant time. This optimization will not improve the performance. If you are really concerned about improving performance, consider using a proper caching framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Receive index of list element using jQuery i have an unordered list with an unknown number of list items. it looks like this: <ul id="keyvisualpager"> <li><a><span>first</span></a></li> <li><a><span>second</span></a></li> <li><a><span>third</span></a></li> <li><a><span>and so on</span></a></li> <li><a><span>fsdfsf</span></a></li> <li><a><span>asdad</span></a></li> </ul> when the user clicks on a link, i need to find out the index of the list element and assign it to a variable. e.g. if the user is clicking the second link ("second") the variable should be set to "2"... $('#keyvisualpager li a').click(function () { // receive index of list element var mbr_index = ???; }); i have to use jquery 1.2.1 ... so no fancy stuff please :) any help is greatly appreciated, thanks! A: Maybe you overlooked that .index(element) [docs] was already available in jQuery 1.0: var $items = $('#keyvisualpager li'); $items.find('a').click(function () { var mbr_index = $items.index($(this).parent()) + 1; // one based index }); Original answer: This should work in jQuery 1.2: var mbr_index = $(this).parent().prevAll().length + 1; // one based index A: You might consider assigning the click a little more manually using each(). You can iterate over the list items and have the index available to you. You can find the anchor within the list item and bind its click method. $('#keyvisualpager li').each(function(index) { $(this).find('a').bind('click', function() { var mbr_index = index + 1; // indices start at 0 ... }); }); each() was available in jQuery 1.0 so you should be able to use it no problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yahoo! Contacts API fails for new users I have spent the last several days implementing OAuth-based communication with Yahoo! in order to retrieve a user's contact information and I have successfully built an implementation which works beautifully with a Yahoo! account I created several years ago. Now I am attempting to retrieve the contacts for a user I just barely created and Yahoo! is returning an incredibly informative 503 (Service unavailable) error to the tune of: <?xml version="1.0" encoding="utf-8"?> <error xmlns="http://social.yahooapis.com/v1/schema.rng" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:uri="http://www.yahooapis.com/v1/errors/503" yahoo:lang="en-US"> <description>Not available</description> <detail>new user</detail> </error> Currently, I am using the older version of the Contacts API which is queried with a request to: http://social.yahooapis.com/v1/user/{guid}/contacts?format=XML, so in an effort to track the issue I tested a query to the new YQL based mechanism in the YQL Console and was able to retrieve contacts for the user in question. I attempted to switch my application to use YQL, but for some reason, reusing the OAuth authorization process I had in place for the old API is resulting in a 401 (Unauthorized) error when I request http://query.yahooapis.com/v1/yql?format=xml&q=select%20*%20from%20social.contacts%20where%20guid={guid} (or guid=me): <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <yahoo:error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:uri="http://yahoo.com" xml:lang="en-US"> <yahoo:description>Please provide valid credentials. OAuth oauth_problem=&quot;OST_OAUTH_SIGNATURE_INVALID_ERROR&quot;, realm=&quot;yahooapis.com&quot;</yahoo:description> <yahoo:detail>Please provide valid credentials. OAuth oauth_problem=&quot;OST_OAUTH_SIGNATURE_INVALID_ERROR&quot;, realm=&quot;yahooapis.com&quot;</yahoo:detail> </yahoo:error> So, I have two questions and I'd be happy with an answer to either one: * *Why can't I get contacts from the Yahoo! old Contacts API for new Yahoo! accounts *(OR) Why is my YQL query for contacts returning a 401 error? Update I did some further testing with the original Contacts API and it seems that Yahoo! is blocking the retrieval of contacts for users which were created recently. Although I am not sure what Yahoo! considers 'recent', I was able to retrieve contacts for a user created a little over 2 weeks ago. Why isn't this in their documentation? :(
{ "language": "en", "url": "https://stackoverflow.com/questions/7520013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep 3rd party's site credentials with GAE? My GAE site should communicate with 3rd party site (i.e. should use it's API). That 3rd party site requires HTTP Digest Authentication. To support that I use the following header, it works well: headers={'Authorization': 'Basic %s' % base64.b64encode('login:pass')} How can I check if authorization on that side is still valid and if it is not, how should I ask user to input login and pass again? A: If the authentication details are not valid, the site will return a 401 Unauthorized response. The only way to check for validity is to make a request - any request - and see if you get a 401. How you prompt the user for updated credentials depends entirely on your application, how it's designed, and who your users are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What will be the SQL trigger of this scenario? I have three tables, requirement, selloffer and tradeleads. Tradelead is a table which holds the common entities of earlier two tables. Schema of requirement: reqId, name, description, posteddate, companyid, cat1,cat2,cat3 .... Schema of selloffer: sellid, name, description, posteddate, companyid, cat1,cat2,cat3 .... Schema of tradelead: id, name, description, posteddate, companyid, cat1,cat2,cat3, typeid here in the tradelead i am using typeid to distinguish btween buy and sell. It its buy then 1 will get inserted alongwith the data else 2. So what will be mine trigger for the above scenario? Scenario: whenever a row is either inserted into requirements or selloffers, a row will also get created into the tradeleads tables, using the above mentioned columns.Mean to say when a row is created in requirement it also get created in TradeLead with type id =1 and if it is creating in selloffers , the tradelead will get populated with type=2 and rest same. I hope , i am clear now A: CREATE TRIGGER dbo.requirment_insert ON dbo.requirment FOR INSERT AS BEGIN INSERT dbo.tradelead(id, name, ..., typeid) SELECT reqId, name, ..., 1 FROM inserted; END GO CREATE TRIGGER dbo.selloffer_insert ON dbo.selloffer FOR INSERT AS BEGIN INSERT dbo.tradelead(id, name, ..., typeid) SELECT sellid, name, ..., 2 FROM inserted; END GO
{ "language": "en", "url": "https://stackoverflow.com/questions/7520019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why isn't a jQuery Tools tooltip showing up as a jQuery extension? I have a Boilerplate 2.0-based page and want to add tooltips. Under the call to load jQuery, I add a call to load the jQuery-tools bundle, and then in js/script.js call: jQuery(".has-tooltip").tooltip(); The result? No tooltips show up; Chrome's JavaScript console gives: jQuery('.has-tooltip').tooltip(); script.js:30Uncaught TypeError: Object [object Object] has no method 'tooltip' So far as I can tell, and from the order of things in index.html, the following happens: * *I load jQuery. *I load jQuery Tools, without apparent error. *I call jQuery().tooltip(). This errors out, and doesn't display tooltips. What can I do to ensure that the Tools extension is being registered to jQuery and I can call jQuery().tooltip(...)? ATdhvaanckse, --edit-- It's for a portfolio; the URL is: http://JonathanHayward.com/portfolio I've tried to pull things in to local loading (i.e. removed the CDN jQuery hit); this has not produced observable differences. A: First, You load jQuery twice, also have two body and html closing tags and fix Modernizr issue which is not defined
{ "language": "en", "url": "https://stackoverflow.com/questions/7520025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pointing to another object's attributes and adding your own Suppose I have a class: class Car(object): def __init__(self, name, tank_size=10, mpg=30): self.name = name self.tank_size = tank_size self.mpg = mpg I put together a list of the cars I'm looking at: cars = [] cars.append(Car("Toyota", 11, 29)) cars.append(Car("Ford", 15, 12)) cars.append(Car("Honda", 12, 25)) If I assign a name to my current favorite (a "pointer" into the list, if you will): my_current_fav = cars[1] I can easily access the attributes of my current favorite: my_current_fav.name # Returns "Ford" my_current_fav.tank_size # Returns 15 my_current_fav.mpg # Returns 12 Here's where I start getting foggy. I would like to provide additional "computed" attributes only for my current favorite (let's assume these attributes are too "expensive" to store in the original list and are easier to just compute): my_current_fav.range # Would return tank_size * mpg = 180 # (if pointing to "Ford") In my case, I just capitulated and added 'range' as an attribute of Car(). But what if storing 'range' in each Car() instance was expensive but calculating it was cheap? I considered making 'my_current_fav' a sub-class of Car(), but I couldn't figure out a way to do that and still maintain my ability to simply "point" 'my_current_favorite' to an entry in the 'cars' list. I also considered using decorators to compute and return 'range', but couldn't figure out a way to also provide access to the attributes 'name', 'mpg', etc. Is there an elegant way to point to any item in the list 'cars', provide access to the attributes of the instance being pointed to as well as provide additional attributes not found in the class Car? Additional information: After reading many of your answers, I see there is background information I should have put into the original question. Rather than comment on many answers individually, I'll put the additional info here. This question is a simplification of a more complicated issue. The original problem involves modifications to an existing library. While making range a method call rather than an attribute is a good way to go, changing some_var = my_current_favorite.range to some_var = my_current_favorite.range() in many existing user scripts would be expensive. Heck, tracking down those user scripts would be expensive. Likewise, my current approach of computing range for every car isn't "expensive" in Python terms, but is expensive in run-time because the real-world analog requires slow calls to the (embedded) OS. While Python itself isn't slow, those calls are, so I am seeking to minimize them. A: This is easiest to do for your example, without changing Car, and changing as little else as possible, with __getattr__: class Car(object): def __init__(self, name, tank_size=10, mpg=30): self.name = name self.tank_size = tank_size self.mpg = mpg class Favorite(object): def __init__(self, car): self.car = car def __getattr__(self, attr): return getattr(self.car, attr) @property def range(self): return self.mpg * self.tank_size cars = [] cars.append(Car("Toyota", 11, 29)) cars.append(Car("Ford", 15, 12)) cars.append(Car("Honda", 12, 25)) my_current_fav = Favorite(cars[1]) print my_current_fav.range Any attribute not found on an instance of Favorite will be looked up on the Favorite instances car attribute, which you set when you make the Favorite. Your example of range isn't a particularly good one for something to add to Favorite, because it should just be a property of car, but I used it for simplicity. Edit: Note that a benefit of this method is if you change your favorite car, and you've not stored anything car-specific on Favorite, you can change the existing favorite to a different car with: my_current_fav.car = cars[0] # or Car('whatever') A: If you have access to the class (and it sounds like you do), just create a function inside the class instead. def range(self): return self.tank_size * self.mpg A: With regards to your example, you could make range a read-only property of class Car that would be computed on demand. No need for extra classes. A: Why don't you just create a method: class Car(object): def __init__(self, name, tank_size=10, mpg=30): self.name = name self.tank_size = tank_size self.mpg = mpg def range(self): return self.tank_size * self.mpg A: Sounds like range() should be a method of the class. Methods are very cheap - the objects don't store them. The downside is it is computed each time you access the value of range. class Car(object): def __init__(self, name, tank_size=10, mpg=30): [AS ABOVE] def range(self): return self.tank_size * self.mpg If you prefer it to behave like a field, i.e. compute only once, you can store the value in the object during the range method: def range(self): if not hasattr(self,'_rangeval'): self._rangeval = self.tank_size * self.mpg return self._rangeval This takes advantage of the fact that you can dynamically create fields in objects. I don't understand why the default would be 180 when the default of the computed values is 300. If this strange behaviour is important, you will need to set another flag to see if the other parameters have been initialised to the default or not. A: I'm not sure I understand what you're trying to do, so I'm going to cover a few different possible understandings of what you're thinking. In my case, I just capitulated and added 'range' as an attribute of Car(). But what if storing 'range' in each Car() instance was expensive but calculating it was cheap? First off, worrying about things being "expensive" is usually not that Pythonic. If it really mattered, you would be using a lower-level language most of the time. But in general, if you want something to be calculated rather than stored, the natural way is to use a method. Add it to the Car class. It does not cost per-object, unless of course you explicitly replace the method on a per-object basis. Here's how it works: when you make a call to a_car.range(), the range attribute is looked up in a_car first. If it's not found there, then (skipping lots and lots of details here!) the class of a_car is identified as Car, and the attribute is looked up there. You define range as a Car method, so it gets found there, and is determined to be something that's actually callable, so it gets called. As a special syntax rule, a_car gets passed as the first parameter to the method (all of which partly explains why you need to have an explicit parameter - named self by convention - for methods in Python, unlike many other languages with an implicit this). I considered making 'my_current_fav' a sub-class of Car(), but I couldn't figure out a way to do that and still maintain my ability to simply "point" 'my_current_favorite' to an entry in the 'cars' list. You can definitely store a subclass of Car in the same list as a bunch of ordinary Cars. No problem there. Heck, you can store a Banana in the same list as a bunch of Cars if you like; Python is dynamically typed, and doesn't care. It will figure out what kind of object something is at the exact moment that it becomes relevant. What you can't easily do is cause an existing Car to become a MyFavouriteCar. If you created a new MyFavouriteCar that my_favourite_car refers to (don't say "points at", please; object references are a higher-level abstraction, and unlike Java there is no "null pointer" in Python - None is an object), then you could replace an existing car in the list with it, but it's still a different object (even if it's somehow based on the original Car that it replaces). You can design in such a way that this doesn't matter; or you can resort to evil hackery (which I won't explain here); or you can (much better in your case) just offer the functionality to all Cars, because it's really free to do so. From the Zen of Python: Special cases aren't special enough. A: You talk about my_current_fav being a 'pointer' -- I just want to make sure you realize that, in fact, my_current_fav = cars[1] binds a name to cars[1] -- in other words, my_current_fav is cars[1] == True. There is no pointing going on. If you really want a pointer-stlye you can do something like this: class Favorite(object): def __init__(self, car_list, index): self.car_list = car_list self.index = index def __getattr__(self, attr): return getattr(self.car_list[self.index], attr) def __index__(self): return self.index @property def range(self): return self.mpg * self.tank_size my_current_fav = Favorite(cars, 1) print my_current_fav.name print my_current_fav.range print cars[my_current_fav]
{ "language": "en", "url": "https://stackoverflow.com/questions/7520031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby: unless vs if not I find myself preferring if not rather than unless. Is there a proper way to write that sort of condition? How do people generally feel about unless? A: I hope this helps you: https://github.com/rubocop-hq/ruby-style-guide#if-vs-unless Prefer unless over if for negative conditions (or control flow ||). # bad do_something if !some_condition # bad do_something if not some_condition # good do_something unless some_condition I personally agree with what's written there choosing unless something over if !something for modifiers and simple ones and when there's an else prefer if. A: I use unless every time, except when there is an else clause. So, I'll use unless blah_blah ... end but if there is an else condition, I'll use if not (or if !) if !blah_blah ... else ... end After using if ! for years and years and years, it actually took me a while to get used to unless. Nowadays I prefer it in every case where reading it out loud sounds natural. I'm also a fan of using a trailing unless increment_by_one unless max_value_reached I'm using these method/variable names obviously as a readability example - the code's structure should basically follow that pattern, in my opinion. In a broader sense, the structure should be: take_action unless exception_applies A: if not condition is rarely used. Ruby programmers (usually coming from other languages) tend to prefer the use if !condition. On the other side, unless is widely use in case there is a single condition and if it sounds readable. Also see making sense with Ruby unless for further suggestions about unless coding style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: Why can't you use a object property as an index in a for loop? (MATLAB) Below is an example that doesn't work in Matlab because obj.yo is used as the for loop's index. You can just convert this to the equivalent while loop and it works fine, so why won't Matlab let this code run? classdef iter_test properties yo = 1; end methods function obj = iter_test end function run(obj) for obj.yo = 1:10 disp('yo'); end end end end A: From help "properties are like fields of a struct object." Hence, you can use a property to read/write to it. But not use it as variable like you are trying to do. When you write for obj.yo = 1:10 disp('yo'); end then obj.yo is being used as a variable, not a field name. compare to actual struct usage to make it more clear: EDU>> s = struct('id',10) for s.id=1:10 disp('hi') end s = id: 10 ??? for s.id=1:10 | Error: Unexpected MATLAB operator. However, one can 'set' the struct field to new value EDU>> s.id=4 s = id: 4 compare the above error to what you got: ??? Error using ==> iter_test Error: File: iter_test.m Line: 9 Column: 20 Unexpected MATLAB operator. Therefore, I do not think what you are trying to do is possible. A: Foreword: You shouldn't expect too much from Matlab's oop capabilities. Even though things have gotten better with matlab > 2008a, compared to a real programming language, oop support in Matlab is very poor. From my experience, Mathworks is trying to protect the user as much as possible from doing mistakes. This sometimes also means that they are restricting the possibilities. Looking at your example I believe that exactly the same is happening. Possible Answer: Since Matlab doesn't have any explicit typing (variables / parameters are getting typed on the fly), your code might run into problems. Imagine: $ a = iter_test() % a.yo is set to 1 % let's overwrite 'yo' $ a.yo = struct('somefield', [], 'second_field', []); % a.yo is now a struct The following code will therefore fail: $ for a.yo disp('hey'); end I bet that if matlab would support typing of parameters / variables, your code would work just fine. However, since you can assign a completely different data type to a parameter / variable after initialization, the compiler doesn't allow you to do what you want to do because you might run into trouble. A: The error is ??? Error: File: iter_test.m Line: 9 Column: 20 Unexpected MATLAB operator. Means that the MATLAB parser doesn't understand it. I'll leave it to you to decide whether it's a bug or deliberate. Raise it with TMW Technical Support. EDIT: This also occurs for all other kinds of subscripting: The following all fail to parse: a = [0 1]; for a(1) = 1:10, end a = {0 1}; for a{1} = 1:10, end a = struct('a', 0, 'b', 0); for a.a = 1:10, end It's an issue with the MATLAB parser. Raise it with Mathworks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to store user mentions I want to implement user mentions with @username like in Twitter. But, in my app, the username may change. My approach is to parse the post before saving into the database and convert all the @username to @userId. What do you think of this? Does anyone has any better alternative? A: Store the original text, as is, and create a table of related records with the uid and username. Example schema: post [table] id text user_mention [table] id post_id user_id_mentioned user_name_mentioned When a post is saved, your code should go through and create all the user_mention records. You can loop through the mention table to send e-mails or whatever else you want to do. If the user changes their user name, you now have the option of updating the post with the new username, or having the old username link to the correct user. My rule is to never, ever modify original unstructured text before saving to the database (but do sanity check it to avoid injections and whatnot) and modify the data only on output. This means you always have the user entered data, and you never know when that will be valuable. Maybe one day you are interested in who changed their username after being mentioned n number of times? Or some other report that you can't get because you modified unstructured data. You never know when you will want the original data and, in this case, you get the added bonus of having your text easier to work with. A: Yeah, I think checking the username list at the post time, and converting them internally to a user ID makes sense. Then, whenever you display the post, translate the user ID back to the current username. Note that this will be more difficult for non-dynamic content, such as emails sent, etc. Also, I'd make sure that the usernames are displayed in a way that makes it clear that they're not words the OP posted, otherwise, that would give a way for users to inject text into someone else's post. A: Yes I think that is good. Twitter itself doesn't just use Usernames it uses UserIDs. It gets the tweeters user ID then looks it up to get the the actual username. Documentation : Mentions and Lookup Each user should have a unique ID. You should match the ID's with the username before you send it anywhere which would be visible for users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Show users with any privileges to database. MySQL i have to select all users with any privileges to database (e.g. database 'mysql'). Any suggestions? Thanks. A: A good view of all users and their approximate privileges. If there is a password, it will by an encrytped string; if not, this field is blank. Select is a very general privlege; insert allows table manipulation within a database; shutdown allows major system changes, and should only be usable by root; the ability to grant permissions is separate from the others. SELECT user, host, password, select_priv, insert_priv, shutdown_priv, grant_priv FROM mysql.user View permissions for individual databases. SELECT user, host, db, select_priv, insert_priv, grant_priv FROM mysql.db A: * *database privileges are stored in mysql.db *table privileges are stored in mysql.tables_priv *column privileges are stored in mysql.columns_priv *routine privileges are stored in mysql.proc_privs You can define a store procedure to list the privileges: delimiter // CREATE PROCEDURE list_privileges (IN db_name CHAR(50)) BEGIN SELECT concat(Db,'.', '*') as 'what', User, Host, '...' as 'perms' FROM mysql.db WHERE Db=db_name UNION SELECT concat(Db,'.', Table_name), User, Host, table_priv FROM mysql.tables_priv WHERE Db=db_name and table_priv != '' UNION SELECT concat(Db,'.', Table_name, '(', Column_name,')'), User, Host, Column_priv FROM mysql.columns_priv WHERE Db=db_name UNION SELECT concat(Db,'.', Routine_name, '()'), User, Host, Proc_priv FROM mysql.procs_priv WHERE Db=db_name; END// delimiter ; example: mysql> call list_privileges("testlink2"); +-----------------------------+-----------+-----------+---------+ | what | User | Host | perms | +-----------------------------+-----------+-----------+---------+ | testlink2.* | testlink2 | % | ... | | testlink2.* | testlink2 | localhost | ... | | testlink2.executions | testlink2 | % | Select | | testlink2.users(id) | testlink2 | % | Select | | testlink2.list_privileges() | testlink2 | % | Execute | +-----------------------------+-----------+-----------+---------+ 5 rows in set (0.00 sec) Query OK, 0 rows affected (0.00 sec) A: Look the in mysql database (an actual db named mysql inside the mysql server, just to be clear). There's three tables (db, tables_priv, and columns_priv) where the db/table/column privs are stored: SELECT 'db', User, Host FROM db WHERE Db='mydatabase' UNION SELECT 'table', User, Host FROM tables_priv WHERE Db='mydatabase' UNION SELECT 'col', User, Host FROM columns_priv WHERE Db='mydatabase' should show you what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to do multiple publication scheduling in C# service? I have one service which is listening for position updates coming from upstream system. Now there are multiple consumers of this position updates. * *One consumer wants to get update as soon as possible *One consumer wants to get update every 30 seconds *One consumer want to get update when 50 updates are accumulated *One consumer want to get update when 50 updates are accumulated or 30 seconds which ever is earlier. Above can be changed anytime or new variation can be added ? How can I make this configurable, scalable, and what kind of programming approach I should use. I am developing in C#, Window Service A: It sounds like you are describing a scenario where the service is an intermediary between the publishing source (the service itself is a subscriber) and the service re-broadcasts this information to N subscribers, but according to their schedule. So assuming an update is a single position update and not some sort of aggregation like a rolling average nor a buffering (e.g. just the latest position of a car every 30 seconds not all its positions since the last 30 seconds), then you need to maintain some information for each subscriber: * *a subscription. Who is the consumer? how do I notify it? (e.g. callback, reply queue, etc.) *a specification. What does the consumer want and when? (e.g. every 50 ticks) *state * *time since last send *number of updates since last send *... As the service receives updates, for each consumer it must evaluate the specification against the state for each update from the source; something like: if (consumer.Spec.Matches(consumer.State, updateMessage) SendUpdate(consumer.Subscription.Callback, updateMessage) The above assumes your spec is directly executable by the service (i.e. the consumers are in-process or the spec was serialized and can be deserialized by the service. If this isn't the case, your spec could perhaps represent a DSL (e.g. a parseable representation that the server could compile into something it could execute). Another approach is thinking of the spec as an instruction set. For example, public enum FrequencyUnit { SecondsSinceLastSend, UpdatesSinceLastSend, } public class Frequency { public double Value { get; set; } public FrequencyUnit Unit { get; set; } } public class Operator { Every, // Unary: e.g. every update; every 10 sec; every 5 updates Or, // Nary: e.g. every 50 or every 20 sec (whichever's first) And, // Nary: e.g. 19 messages and 20 sec have passed // etc. } public class UpdateSpec { public Frequency[] Frequencies { get; set; } public Operator Operator { get; set; } } These are pretty flexible, and can be configured on the server in-code, or built-up by reading XML or something. These could also be passed to the service from the consumer itself upon registration. For example, an IService.Register() could expose an interface taking in the subscription and specification. The last bit would be scalability. I described the service looping on each update for the consumers. This won't scale well because the loop may block receiving the updates from the source or if asynchronous with the source, would at least likely accumulate updates faster than processing them. A strategy to deal with this is to add an internal queue to the information you maintain for each subscriber. The service, upon receiving an update, would enqueue it to each internal queue. Service tasks (TPL-based), thread-pool threads, or long-lived threads would then dequeue and evaluate the update as above. There are many possible variations and optimizations of this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with AVAudioPlayer ? Creating delay While using AVAudioPlayer .... Sound not playing at instant if i click button... and in that class i have one NSTimer which keep changing image so for that purpose i have to ring sound. But If i will use this AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);... i am not able to hear sound in device.. cause my file is in mp3 format. AVAudioPlayer Code: NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/slotmachine.mp3", [[NSBundle mainBundle] resourcePath]]]; NSError *error; audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; audioPlayer.numberOfLoops = -1; [audioPlayer play]; So anyone can tell me why i am not able to use AVAudioPlayer so smoothly like System Sound does.. what is the appropriate way to integrate ? A: Call [audioPlayer prepareToPlay] well before you want to actually play the audio.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: alertDialog button go to URI As the title says, I want to make a button in my alertDialog of my app go to a certain URI, and I was wondering how i would do this? heres and excerpt of the code: // Add a neutral button to the alert box AND assign a listener for said button... alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener(){ // click listener for box public void onClick(DialogInterface arg0, int arg1){ // Button was clicked!! Toast.makeText(getApplicationContext(), "Dialog closed successfully!", Toast.LENGTH_LONG).show(); } }); // Add a Forums button to take user to forums... alertbox.setPositiveButton("Forums", new DialogInterface.OnClickListener(){ //listener for button public void onClick(DialogInterface arg0, int arg1){ // Button Pressed! Toast.makeText(getApplicationContext(), "Oops...this button is broke!", Toast.LENGTH_LONG).show(); } }); // show it!!! alertbox.show(); instead of making display the toast info saying the button is broke, I actually want it to launch the browser and take the user to a URI. There has to be a way... Ideas? Thanks! Updated with more code.. A: Start intent in onClick() handler: Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse("http://website.com")); startActivity(intent);
{ "language": "en", "url": "https://stackoverflow.com/questions/7520047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access multidimensional array by string with delimiter suppose i have a multidimensional array like something like this: <?php $array = array("test1" => array("test2" => array("test3" => 1)), ... foo1 = array("foo2" => 2)); ?> i want to access an array element by passing a string like "test1.test2.test3" to a function which in turn calls the array element. I could use eval() by replacing the string with [] (calling $array["test2]["test3"] ...) but i wonder if there is a different more solid approach in calling a array element without traversing through all of its depth or use eval(). A: You could use function get_multi($arr, $str) { foreach (explode('.', $str) as $key) { if (!array_key_exists($key, $arr)) { return NULL; } $arr = $arr[$key]; } return $arr; } A: Symfony provides a PropertyAccess component for this. The PropertyAccess component provides function to read and write from/to an object or array using a simple string notation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to Combine two or more columns with Android SimpleCursorAdapter SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.mytaskslayout, cursor, new String[] {"Aircraft","Discrepancy","ARR_FLT"}, new int[] {R.id.ac, R.id.discrepancy, R.id.arrinfo} ); Can I combine two or more columns and display in one R.id.XXX ? If yes, how ? A: You can create a SimpleCursorAdapter.ViewBinder to do this. See this answer for an example. Basically your ViewBinder will get called for each View. So when you get to the View that you want to have both columns, just retrieve both column values, combine them, and set the value on the View yourself. A: Finally found a solution. I Had the same question as someone new to Android and Xamarin for Android. To be clear - I'm using Xamarin Studio, and Xamarin for Android written in C#. Although it seems like the SimpleCursorAdapter can accommodate multiple fields, when binding to something like the SimpleListItem only one field gets used. I first tried this: string[] fromColumns = new string[]{ "checkListName","checkListDesc" }; int[] toControlIDs = new int[] {Android.Resource.Id.Text1, Android.Resource.id.Text1}; try{ listView.Adapter = new SimpleCursorAdapter(this,Android.Resource.Layout.SimpleListItem1 , c, fromColumns, toControlIDs, 0); } catch(SQLiteException e){ Console.WriteLine ("whoops, " + e.Message.ToString ()); } But all I ever got was the last field in the cursor row. I learned that a CUSTOM LISTVIEW was needed. Following are code files for four files: * *MainActivity.cs *myList.xml *Main.axml *PreFloat.cs (this is the database part) I have included all of this to provide as much as possible a completely working sample that is as close to real life as possible. Here is MainActivity.cs which sets a content view, uses a cursor to get data from a SQLite database, and defines a using System; using Android.App; using Android.Content; using Android.Database; using Android.Database.Sqlite; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace Darjeeling { [Activity (Label = "Darjeeling", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { ListView listView; Darjeeling.PreFloatDatabase pdb; ICursor c; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); listView = FindViewById<ListView> (Resource.Id.listView1); pdb = new PreFloatDatabase (this); // Assign the cursor to a query c = pdb.ReadableDatabase.RawQuery ("select * from checkLists", null); StartManagingCursor (c); // A ListView needs an adapter -- so we'll assign our instantiated listView's adapter to our customized adapter called HomeScreenCursorAdapter. listView.Adapter = (IListAdapter)new HomeScreenCursorAdapter (this,c); } // End onCreate method // This handles the cursor when the user is done with the activity protected override void OnDestroy() { StopManagingCursor(c); c.Close (); base.OnDestroy(); } // Here's the magic -- public class HomeScreenCursorAdapter : CursorAdapter { Activity context; public HomeScreenCursorAdapter(Activity context, ICursor c) : base (context, c) { this.context = context; } // This overridden BindView method is going to let me assign TextView controls that I've set up in an XML file, to specific fields in the cursor. public override void BindView(View view, Context context, ICursor cursor) { var txtCheckListName = view.FindViewById<TextView> (Resource.Id.txtCheckListName); //(Android.Resource.Id.Text1); var txtCheckListDesc = view.FindViewById<TextView> (Resource.Id.txtCheckListDesc); //(Android.Resource.Id.Text2); // For testing purposes, I first assigned static values to txtCheckListName and txtCheckListDesc, for instance, txtCheckListName.Text = "Hello"; and txtCheckListDesc.Text = "World"; txtCheckListName.Text = cursor.GetString (3); txtCheckListDesc.Text = cursor.GetString (4); } // This overridden View inflates each row (I think). This could inflate a built-in ListView control like SimpleListItem, OR, in this case, it references a custom written XML file called myList. public override View NewView(Context context, ICursor cursor, ViewGroup parent) { return this.context.LayoutInflater.Inflate (Resource.Layout.myList, parent, false); } } } } Here's the Main.axml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/linearLayout1" android:minWidth="25px" android:minHeight="25px"> <ListView android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView1" /> </LinearLayout> And finally, the myList.xml file which is essentially the definition of the ListView row: <?xml version="1.0" encoding="utf-8"?> <!---<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="200dp" android:layout_height="match_parent" android:background="#FF0000FF"> --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/linearLayout1" android:minWidth="25px" android:minHeight="25px"> <TextView android:id="@+id/txtCheckListName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="" /> <TextView android:id="@+id/txtCheckListDesc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="" /> </LinearLayout> <!---</FrameLayout>--> And here's the database file: using System; using Android.Database.Sqlite; using Android.Content; namespace Darjeeling { class PreFloatDatabase : SQLiteOpenHelper { public static readonly string create_checkLists_table = "create table if not exists checkLists([_id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, checkListID INTEGER, checkListType INTEGER, checkListName TEXT, checkListDesc TEXT);"; public static readonly string DatabaseName = "prefloat.db"; public static readonly int DatabaseVersion = 1; public PreFloatDatabase (Context context) : base (context, DatabaseName, null, DatabaseVersion){ } public override void OnCreate(SQLiteDatabase db){ // fire the statement that creates the checkLists table try{ db.ExecSQL (create_checkLists_table); // Now pre-fill the checkLists table db.ExecSQL ("insert into checkLists (checkListID, checkListType, checkListName, checkListDesc) values (0, 0, 'Widgeon','Widgeon Daysailer');"); db.ExecSQL ("insert into checkLists (checkListID, checkListType, checkListName, checkListDesc) values (1, 1, 'Widgeon','Widgeon Daysailer');"); db.ExecSQL ("insert into checkLists (checkListID, checkListType, checkListName, checkListDesc) values (2, 0, 'Bowrider', 'Mo Motor, Mo Fun');"); db.ExecSQL ("insert into checkLists (checkListID, checkListType, checkListName, checkListDesc) values (3, 1, 'Bowrider', 'Mo Motor, Mo Fun');"); db.ExecSQL ("insert into checkLists (checkListID, checkListType, checkListName, checkListDesc) values (4, 0, 'HobieCat','Hang yer ass out fun');"); db.ExecSQL ("insert into checkLists (checkListID, checkListType, checkListName, checkListDesc) values (5, 1, 'HobieCat','Hang yer ass out fun');"); } catch(SQLiteException e){ Console.WriteLine ("Problem with the database " + e.Message.ToString ()); } } public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ throw new NotImplementedException (); } } // matches with class PreFloatDatabase } // matches with namespace Darjeeling Questions: SHOULD a SimpleListItem control have more than a single field or at most a checkbox control and label? Should a grid control be used instead? Alternatives: Instead of doing all these shenanigans, wouldn't it be easier to simple concatenate the needed values using SQL? Especially since coordinating the positioning of two text controls might be too complicated. Full Disclosure: This code is an amalgam of code I read in other posts and forums, and customized to fit my own particular requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: FQL query response randomly omits some results I'm trying to make a simple "only status updates, nothing else" app (since FB doesn't seem too interested in this sort of thing). However, my queries seem to omit some results: "select status_id,uid,time,message from status where uid in (select uid2 from friend where uid1= $my_id) ORDER BY time DESC LIMIT 25", for instance, when I last tested it, only returned 21 results (and yes, I've got enough friends who have made enough updates that there are definitely more than 25 historical statuses). This is with the PHP API, by way of Heroku, but I've had similar issues for a while, going back to before FBML was deprecated, with basically the same query. I haven't tested enough to determine absolutely that this is the case, but it seems only to return one status per user (if Bob posted six updates, it only returns his newest status and ignores the previous ones). Is this a known issue/bug? Any workarounds? A: facebook trades accuracy for performance it has been always the case , so it usually returns a limited number of results per query A: It's probably because a user has not given access for a friends apps to access their posts. Apparently making an FQL request, facebook does the initial request, including your limit param. Then it filters the list removing anything that you don't have permissions to see. Hence receiving less than 25 results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what should I do to analyze the log file I have an app (node.js) running on multiple servers. each server has its own log (request log, error log, etc). The log file contains time, http request, sometimes with userId. What program I can use to analyze log file? or if there is any node.js plug-in that can do it? since logs are on multiple servers, should I combine them first before analyzing? Or, should I store the error into DB instead? (like mongo) A: Sounds like http://search.npmjs.org/#/winston might be useful for you, it can send logged data to a database. You shouldn't log stuff as plain text but as JSON objects so that you can easily query the logs in the DB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create struct with boost graph I whant to use this structure that I've created with a graph: typedef struct type_INFOGRAPH { boost::adjacency_list < boost::listS, boost::vecS, boost::undirectedS, Node, Line > graphNetworkType; map<int,graph_traits<graphNetworkType>::edge_descriptor> emymap; map<int, graph_traits<graphNetworkType>::vertex_descriptor> vmymap; }INFOGRAPH; But when I trie to construct the graph with a function: INFOGRAPH *infograph = NULL; infograph->graph = CreateGraphFromDataset3(file); I get an erro like this: "Unhandled exception at 0x00ae4b14 graph.exe : 0xC0000005: Access violation reading location 0x00000018." A: I doubt this even compiles, since your INFOGRAPH class doesn't even have a member called graph. More importantly, though, you've never created an instance of the class - you just made a pointer, set that to NULL and dereferenced it. Naturally that isn't valid and gets you crashed. You can make an instance either automatically or dynamically, depending on how you're going to use it: // Automatic: INFOGRAPH infograph; infograph.graph = CreateGraphFromDataset3(file); // Dynamic: INFOGRAPH * pinfograph = new INFOGRAPH; pinfograph->graph = CreateGraphFromDataset3(file); // ouch, who cleans up `*pinfograph` now?
{ "language": "en", "url": "https://stackoverflow.com/questions/7520059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fill input text How can I fill a text input with a value? I am trying this: <input id="curso" maxlength="150" name="curso" size="40" type="text" value="window.location.href.substring(91))" /> But that does not work. A: <input id="curso" maxlength="150" name="curso" size="40" type="text"> <script> document.getElementById("curso").value = document.getElementById("curso").defaultValue = window.location.href.substring(91); </script> You can't execute JavaScript from within an arbitrary HTML attribute. Only <script> elements and event handlers can contain JavaScript, so add a <script> that sets the value. You also need to set the defaultValue property so that any form reset resets the value to the desired value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Agile Parallel Database Migrations I work in an environment that is very agile. We typically have daily rollouts. That ability is necessary due to the nature of our business. Often we have updates to the database. We built a home brewed database migration library, however there is currently no concept of a version, and the migrations are not run sequentially. We have decided to refactor and run the migration sequentially, however we now find that in order to do so we must create a sequence and each migration must have a unique version. How is this accomplished in an automated way in an environment where multiple developers are working in parallel? Example: 3 branches are merged together to be promoted to staging, each branch has a data base migration to be run. How do we determine which comes before the other that requires minimal human interaction. A: Woooo agile ... I work in an environment that is very it's even cooler ;) It's not that simple, if one branch implies modifications to the schema that haven't been taken into account in the other branch etc... it'll of course fail. What you want is a branch reconciliation solution that will handle basic cases where no collision is possible - I.E. a piece of code that will read your SQL, find every ALTER TABLE , check that no two scripts are altering the same tables, then if it is the case, compare the alters to see if they can be combined etc. Of course I can write that for ya but ... maybe somebody already open-sourced a "sqlmigrationscriptcombinatorofdoom". GL ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7520067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to combine multiple TBytes arrays What is the best way to combine TBytes arrays? All arrays are of the same size. I want the content of Array2 to be added to the end of Array1, Array3 to the end of Array2, and so forth. A: To merge two TBytes together, you have to allocate a third TBytes that is the total length of the two individual TBytes, then copy the bytes from both into it. For example: var arr1, arr2, merged: TBytes; begin ... SetLength(merged, Length(arr1) + Length(arr2)); if arr1 <> nil then Move(arr1[0], merged[0], Length(arr1)); if arr2 <> nil then Move(arr2[0], merged[Length(arr1)], Length(arr2)); end; A: You can use string-like operations: var LArray1, LArray2, LMerged: TBytes; begin ... LMerged := LArray1 + LArray2; end; Or you can use the system "Concat" function: var LArray1, LArray2, LMerged: TBytes; begin ... LMerged := Concat(LArray1, LArray2); end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7520068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Prevent iOS from taking screen capture of app before going into background You all might know that iOS takes a screen shot of your application before throwing it into the background. This is usually for a better User experience like quick animation to bring the app back and so on. I don't want my app screen shot to be stored on the device, but I want the multitasking to still exist. I came out with a solution but I'm not sure if I'm heading in the right direction. So, when the applicationDidEnterBackground is called -- I put in an overlay image that will be captured by the OS, and once the app enters foreground, I will remove the overlay. I'm not sure if this is going to work but I'm on my way to implement this. Meanwhile, any other thoughts on this will help me figure out the optimal way of attacking this issue. A: Working methods in AppDelegate, swift 4.2: func blurScreen(style: UIBlurEffect.Style = UIBlurEffect.Style.regular) { screen = UIScreen.main.snapshotView(afterScreenUpdates: false) let blurEffect = UIBlurEffect(style: style) let blurBackground = UIVisualEffectView(effect: blurEffect) screen?.addSubview(blurBackground) blurBackground.frame = (screen?.frame)! window?.addSubview(screen!) } func removeBlurScreen() { screen?.removeFromSuperview() } Where is: weak var screen : UIView? = nil // property of the AppDelegate Call these methods in needed delegate methods: func applicationWillResignActive(_ application: UIApplication) { blurScreen() } func applicationDidBecomeActive(_ application: UIApplication) { removeBlurScreen() } A: Your approach is exactly the correct and only way to do it. Place an overlay view and remove it later. It is valid to do this if your app shows sensitive data that you don't want to be cached in image format anywhere. A: You are on the right track. This is Apple's recommended way to do this as noted in the iOS Application Programming Guide: Remove sensitive information from views before moving to the background. When an application transitions to the background, the system takes a snapshot of the application’s main window, which it then presents briefly when transitioning your application back to the foreground. Before returning from your applicationDidEnterBackground: method, you should hide or obscure passwords and other sensitive personal information that might be captured as part of the snapshot. A: Apple Doc https://developer.apple.com/library/archive/qa/qa1838/_index.html Note: Your implementation of -applicationDidEnterBackground: should not start any animations (pass NO to any animated: parameter). The snapshot of your application's window is captured immediately upon returning from this method. Animations will not complete before the snapshot is taken. Converted Apple code in swift 4.2 App delegate i declared func applicationDidEnterBackground(_ application: UIApplication) { // Your application can present a full screen modal view controller to // cover its contents when it moves into the background. If your // application requires a password unlock when it retuns to the // foreground, present your lock screen or authentication view controller here. let blankViewController = UIViewController() blankViewController.view.backgroundColor = UIColor.black // Pass NO for the animated parameter. Any animation will not complete // before the snapshot is taken. window.rootViewController?.present(blankViewController, animated: false) } func applicationWillEnterForeground(_ application: UIApplication) { // This should be omitted if your application presented a lock screen // in -applicationDidEnterBackground: window.rootViewController?.dismiss(animated: false) false } A: Need to write the code in Application life cycle methods, here we are putting an imageView while the app animate to background : -(void)applicationWillResignActive:(UIApplication *)application { imageView = [[UIImageView alloc]initWithFrame:[self.window frame]]; [imageView setImage:[UIImage imageNamed:@"Splash_Screen.png"]]; [self.window addSubview:imageView]; } Here is the code to remove the imageView: - (void)applicationDidBecomeActive:(UIApplication *)application { if(imageView != nil) { [imageView removeFromSuperview]; imageView = nil; } } It is working and properly tested. A: I came across the same issue, and my research has lead me to the following answers: * *set a blurry screen overlay before the app goes in the background and once the app becomes active remove this overlay *if it is iOS 7 or later you can use the function ignoreSnapshotOnNextApplicationLaunch See in apple documentation: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/ignoreSnapshotOnNextApplicationLaunch I hope this helps somebody. A: Improvement in Depak Kumar post : Make a property UIImage *snapShotOfSplash; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[UIApplication sharedApplication] ignoreSnapshotOnNextApplicationLaunch]; snapShotOfSplash =[UIImage imageNamed:@"splash_logo"]; } - (void)applicationDidEnterBackground:(UIApplication *)application { self.overlayView = [[UIImageView alloc]initWithFrame:[self.window frame]]; self.overlayView.backgroundColor = [UIColor whiteColor]; [self.overlayView setImage:snapShotOfSplash]; [self.overlayView setContentMode:UIViewContentModeCenter]; [self.window addSubview:self.overlayView]; [self.window bringSubviewToFront:self.overlayView]; } - (void)applicationDidBecomeActive:(UIApplication *)application { if(self.overlayView != nil) { [self.overlayView removeFromSuperview]; self.overlayView = nil; } } A: Implementation with some animation while going in background and reverse action - (void)applicationWillResignActive:(UIApplication *)application { // fill screen with our own colour UIView *colourView = [[UIView alloc]initWithFrame:self.window.frame]; colourView.backgroundColor = [UIColor blackColor]; colourView.tag = 1111; colourView.alpha = 0; [self.window addSubview:colourView]; [self.window bringSubviewToFront:colourView]; // fade in the view [UIView animateWithDuration:0.5 animations:^{ colourView.alpha = 1; }]; } - (void)applicationDidBecomeActive:(UIApplication *)application { // grab a reference to our coloured view UIView *colourView = [self.window viewWithTag:1111]; // fade away colour view from main view [UIView animateWithDuration:0.5 animations:^{ colourView.alpha = 0; } completion:^(BOOL finished) { // remove when finished fading [colourView removeFromSuperview]; }]; } A: swift 4.0 version. for use custom icon first add this line at top of AppDelegate var imageView: UIImageView? and add this: func applicationDidEnterBackground(_ application: UIApplication) { imageView = UIImageView(frame: window!.frame) imageView?.image = UIImage(named: "AppIcon") window?.addSubview(imageView!) } func applicationWillEnterForeground(_ application: UIApplication) { if imageView != nil { imageView?.removeFromSuperview() imageView = nil } } background with black color func applicationDidEnterBackground(_ application: UIApplication) { let blankViewController = UIViewController() blankViewController.view.backgroundColor = UIColor.black window?.rootViewController?.present(blankViewController, animated: false) } func applicationWillEnterForeground(_ application: UIApplication) { window?.rootViewController?.dismiss(animated: false) } A: In iOS 7 you could use the allowScreenShot to stop the ability all together. See: Apple Developer: Configuration Profile Reference: allowScreenShot Boolean Optional. If set to false, users can’t save a screenshot of the display and are prevented from capturing a screen recording; it also prevents the Classroom app from observing remote screens. Defaults to true. Availability: Updated in iOS 9.0 to include screen recordings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Linq expression to get all items in a IList where one field is in another List This collection contains the entire database of products: IList<Products> allProducts; This contains just the guids of all the products for this user: IList<Guid> usersProducts; Below is the psuedo code of what I need, i.e. all the product classes in a IList for a given user and the product is also of type == 1. var filteredProducts = (p from allProducts where p.Id in usersProducts && p.Type == 1).List(); I can't figure out how to do the SQL query "WHERE IN (..., ...,) A: var filteredProducts = (from p in allProducts where usersProducts.Contains(p.Id) && p.Type == 1 select p).ToList(); A: @Samich's answer is correct. It's just a personal preference, but I prefer the method syntax... var filteredProducts = allProducts.Where(p => p.Type == 1 && userProducts.Contains(p.Id)).ToList(); Also, for performance reasons, I swapped the order of your conditionals. If p.Type doesn't equal 1, the Contains won't execute. A: Sounds like you just want a join. var filteredProducts = (from p in allProducts join u in usersProducts on p.Id equals u.Id where p.Type == 1 select p).ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7520080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using ROOT (cern) with mingw32 Can I install Cern's ROOT on win32 without MSVS but with mingw32? I want to develop some C/C++ programs, which will use ROOT. A: As far as I know, compiling with mingw32 is currently not supported. I guess it would technically be possible, as mingw32 is based on gcc, but it would be a lot of work. The best way seems to be to use MSVC++ (even the free express version will do). ROOT builder is a nice tool that uses mingw32 (but the MS compiler) and builds ROOT for you, without the need for the command line. Another option would be to use cygwin, but that is also unsupported, and it's probably slower, because it introduces a layer of indirection to convert posix calls to windows. Here are some links to further information: http://www.muenster.de/~naumana/root.html http://root.cern.ch/root/HowtoWindows.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7520088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }