text
stringlengths
8
267k
meta
dict
Q: Oracle - Insert one row per hour between two times Given two times, how do i insert one row per hour in the Oracle table? Start Time: 3.00 PM End Time: 6.00 PM Name: 'Asdfg' Expected Data to be generated: Name StartTime EndTime ASDFG 3.00 4.00 ASDFG 4.00, 5.00 ASDFG 5.00 6.00 A: This does it without PL/SQL, in one insert. You could parameterize the start and end times and use it in your procedure: INSERT INTO tbl (NAME, starttime, endtime) (SELECT 'ASDFG', t1, t2 FROM (SELECT to_char((to_date('3.00 PM','HH.MI AM')+(LEVEL-1)/24),'HH.MI AM') t1 , to_char((to_date('3.00 PM','HH.MI AM')+LEVEL/24), 'HH.MI AM') t2 FROM dual CONNECT BY LEVEL <= (to_date('6.00 PM','HH.MI AM') - to_date('3.00 PM','HH.MI AM')) * 24)); A: CurrentTime := StartTime; WHILE CurrentTime <= EndTime LOOP INSERT INTO MY_TABLE VALUES (CurrentTime); CurrentTime := CurrentTime + (1 / 24); END LOOP; COMMIT; Should do the trick (I did not try it...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7530537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem with data file of Rocket Framework For a windows form application I want to use Rocket Framework from http://rocketframework.codeplex.com. I downloaded Rocket Framework V 1.0.2. After that I located the datafile inside 'Release V 1.0.2\Release V 1.0.2\MainForm\DB'. Now I need to make a database in MS SQL Server to be used in the code. But the RocketDB data file has extension 'file' and I am not finding a way to make a database in MS SQL Management Studio. I also searched in the code plex link http://rocketframework.codeplex.com but could not find the way to use it. Any one have the idea how to use it? A: I solved this issue by generating the database itself from the entity model(.edmx) file. After that everything ran smoothly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can the Volume Shadow Copy service be used in Windows 7 by a non-administrator I'm trying to use the Volume Shadow Copy service on Windows 7, and have had a look at the MS vshadow code and AlphaVSS. These appear to provide enough detail to do what I need, but I can't make anything work unless in Administration mode - I get "0x80070005 - Access is denied" on the first real COM call after CoInitialize and CoInitializeSecurity if in normal user mode, even if the user is a member of Backup Operators. An entry in the application event log suggests this is a COM issue:- The COM Server with CLSID {0b5a2c52-3eb9-470a-96e2-6c6d4570e40f} and name VssSnapshotMgmt cannot be started. [0x80070005, Access is denied.] but I can't find any such server as VssSnapshotMgmt so I've no idea how to change access to it for users. I also believe that it can be done, since Backup works on my machine without elevating priviliges. The application is intended for dumb clients (in every sense) so I'm against using administration mode if at all possible. Any clues on how to connect to this service? A: The command-line tools/samples that Microsoft ships with VSS: vshadow.exe on older versions (upto Windows Server 2008) and diskshadow.exe on newer versions both require to be executed with Administrator privileges. Though it is not explicitly mentioned that invoking the VSS COM APIs should have administrator privileges - considering the fact that Microsoft's own (supported) utilities have this restriction, it would be safe to assume that end-user applications that use the VSS COM APIs would require the same privileges.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Indexing FTP document with solrj I want to index some documents with solrj API's but the URL of these documents is FTP. How to set username and password for FTP acount in solrj? A: UpdateRequest - stream.url does not support authentication We had to add a custom patch to add authentication to it @ https://issues.apache.org/jira/browse/SOLR-2240 Suggestions - 1. Expose the content through http without authentication and use stream.url 2. Read the file from ftp with auth in java and use the stream.body to pass the content as stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does the ESP referring to the address in a stack jumps 4h each time? Why doesn't the Extended Stack Pointer (ESP) jump 1h in each PUSH or POP operation? A: That's because PUSH pushes one whole register to the stack. On 32bit machines, that's four byte's worth of data. PUSHQ would change RSP by 8 in x86_64 because it pushes 64 bits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XPath to find nodes with text + all their descendants & siblings that match certain criteria Background: I'm trying to improve on a Greasemonkey script I found. The script marks prices in foreign currencies and can translate them into the currency of your choice. The main problem: How to make the script handle when prices are listed with tags, such as: <b><i>9.</i></b><sup>95</sup>EUR (Newegg.com does this, for example - they write their prices like so: <span>$</span>174<sup>.99</sup>). Currently, the script only finds prices that are listed in the same text node since the XPath expression being used is: document.evaluate("//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null) Since the script needs to be fast, I'm trying to avoid stepping through the DOM too much... Are there any XPath gurus who could help out with some smart solutions for this purpose? More detailed description of the problem: The code I now have for finding the text nodes: var re_skip = /^(SCRIPT|IFRAME|TEXTAREA|STYLE|OPTION|TITLE|HEAD|NOSCRIPT)$/; // List of elements whose text node-children can be skipped text = document.evaluate("//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); var i = text.snapshotLength; while (i--) { el = text.snapshotItem(i); if (!el.parentNode || re_skip.test(el.parentNode.nodeName.toUpperCase()) || el.parentNode.className == 'autocurrency') { continue; } // ... // (RegEx logic to check if prices can be found in the text) } * *The check to discard text nodes whose parent elements are listed in "re_skip" could be done in the XPath expression as well (using the "not" notation), right? And this would give a speed-increase? *If an ordered XPath type is used instead, I guess I no longer will have to include a check to see if the parent of the text node being parsed is <span class="autocurrency"> (that is, the <span> that the script adds around matched prices). *If I've understood things correctly, normalize-space() (as suggested here), cannot be used in this case, since the script adds a <span class="autocurrency"> around the matched amount and we need to retain the correct index for where this <span> should be entered. *Is there a way for the XPath to allow only certain (inline) elements to be used in-between the currency values? Or perhaps it could do this: "when a node containing text is found, also include all of its children (and their children and so on) in the match - unless the child node is a block type element." (or perhaps it should read: "...unless the child node is a DIV, P, TABLE, or any of the elements in re_skip") I can re-write the regex to handle text such as "<span>$</span>174<sup>.99</sup>" as long as I find these text strings - preferably using XPath, as I have understood this to be much faster than stepping through the DOM. Thank you very much in advance for any help you can give me with this! -------------------------------------------------------------- EDIT: OK, I realize now that the question could do with some clarification and some examples, so here they come. A web page might look something like this: <body> <div> <span>9.95 <span>EUR</span></span><br /> <span>8.<sup>95</sup></span>AU$<br /> <table> <thead> <tr> <th>Bla</th> </tr> </thead> <tbody> <tr> <td><b>7</b>.95kr</td> </tr> </tbody> </table> <div>Bla bla</div> 6.95 <span>GBP</span> </div> <div><img src="" /><img src=""><span>Bla bla bla</span></div> </body> Now, in that example, the overhead isn't that great - I could just feed the whole source code, as a string, directly to the regex that finds prices. But normally, pages will have lots of non-text elements that would make the script very slow if I didn't use a fast XPath to parse out the texts. So, I'm looking for an XPath expression that would find the different texts in the example above, but not just the text content - since we also need tags that might surround parts of a price (a new <span> will later be created around the matched price, including any inline elements that might surround parts of the price). I don't know exactly what the XPath could be made to return, but somehow I need to grab a hold of the following strings from the example page above: "9.95 <span>EUR</span>" (or possibly: "<span>9.95 <span>EUR</span></span>") "<span>8.<sup>95</sup></span>AU$" "Bla" (or possibly: "<th>Bla</th>") "<b>7</b>.95kr" (or possibly: "<td><b>7</b>.95kr</td>") "Bla bla" (or possibly: "<div>Bla bla</div>") "6.95 <span>GBP</span>" "Bla bla bla" (or possibly: "<span>Bla bla bla</span>") and then these strings can be parsed by the regex that finds prices. A: Well you can certainly use a path like //*[not(self::script | self::textarea | self::style)]//text() to find only those text node descendants of element nodes that are not one of "script", "textarea", "style". So the regular expression test you have is not necessary, you could express that requirement with XPath. Whether that performs better I can't tell, you will have to check with the XPath implementations of the browser(s) you want to use the Greasemonkey script with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS3 Box Shadow not working in Chrome? I'm working on a design for a small page with css3 features being used. For some reason I can't get -webkit-box-shadow working on this page (and just this page). I can't seem to figure out where I went wrong. http://kin.remuria.net/flipfinder/test/ Anyone have any ideas what might be wrong with this page? A: Give your box shadow a color box-shadow: 0px 4px 9px #000000; EDIT: If you want to support older versions of browsers that don't support the more standard box-shadow property then using both proprietary prefixes -moz -webkit in combination with the box-shadow property is fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set converter properties for each row/item of h:dataTable/ui:repeat? I have created a custom ISO date time Converter: public class IsoDateTimeConverter implements Converter, StateHolder { private Class type; private String pattern; private boolean transientValue = false; public void setType(Class type) { this.type = type; } public void setPattern(String pattern) { this.pattern = pattern; } @Override public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { if (StringCheck.isNullOrEmpty(value)) { throw new ConverterException("value not specified"); } try { if (IsoDate.class.equals(type)) { if (WebConst.ISO_DATE_NONE.equals(value)) { return IsoDate.DUMMY; } else { //TODO User spezifische TimeZone auslesen return new IsoDate(value, TimeZone.getDefault().getID()); } } else if (IsoTime.class.equals(type)) { if (WebConst.ISO_TIME_NONE.equals(value)) { return IsoTime.DUMMY; } else { //TODO User spezifische TimeZone auslesen return new IsoTime(value, TimeZone.getDefault().getID()); } } else if (IsoTimestamp.class.equals(type)) { if (WebConst.ISO_TIMESTAMP_NONE.equals(value)) { return IsoTimestamp.DUMMY; } else { //TODO User spezifische TimeZone auslesen return new IsoTimestamp(value, TimeZone.getDefault().getID()); } } else { throw new ConverterException("value not convertible"); } } catch (Exception e) { throw new ConverterException(e.getMessage()); } } @Override public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { if (value == null) { throw new ConverterException("value not specified"); } if (IsoDate.class.equals(value)) { IsoDate isoDate = (IsoDate) value; if (isoDate.isDummy()) { return WebConst.ISO_DATE_NONE; } else { //TODO User spezifische TimeZone auslesen return isoDate.toString(pattern, TimeZone.getDefault().getID(), false); } } else if (IsoTime.class.equals(value)) { IsoTime isoTime = (IsoTime) value; if (isoTime.isDummy()) { return WebConst.ISO_TIME_NONE; } else { //TODO User spezifische TimeZone auslesen return isoTime.toString(pattern, TimeZone.getDefault().getID(), false); } } else if (IsoTimestamp.class.equals(value)) { IsoTimestamp isoTimestamp = (IsoTimestamp) value; if (isoTimestamp.isDummy()) { return WebConst.ISO_TIMESTAMP_NONE; } else { //TODO User spezifische TimeZone auslesen return isoTimestamp.toString(pattern, TimeZone.getDefault().getID(), false); } } else { throw new ConverterException("value not convertible"); } } @Override public Object saveState(FacesContext context) { return new Object[]{type, pattern}; } @Override public void restoreState(FacesContext context, Object state) { type = (Class) ((Object[]) state)[0]; pattern = (String) ((Object[]) state)[1]; } @Override public boolean isTransient() { return transientValue; } @Override public void setTransient(boolean transientValue) { this.transientValue = transientValue; } } And I use the Converter as <mh:IsoDateTimeConverter> in the following view: <p:dataTable value="#{imports.list}" var="item"> <p:column> <h:outputText value="#{item.balanceDate}" immediate="true"> <mh:IsoDateTimeConverter type="#{webConst.ISO_DATE_CLASS}" pattern="#{webConst.ISO_DATE_FORMAT}"/> </h:outputText> </p:column> </p:dataTable> The problem is, when I first open this view, all properties are set in my Converter class only once and then the datatable renders and converts the values based on initial properties. I expected that the properties are set on a per-row basis. How can I achieve this? A: To the point, you expected that the converter's properties are set every time a datatable row is rendered. This is indeed not true. JSF will create only one converter instance per component when the view is to be built, it will not create/reset the converter each time the row is rendered. There are several ways to get it to work. * *Pass the dynamic attributes as <f:attribute> of the component and let the Converter intercept on that. You can find an example here: JSF convertDateTime with timezone in datatable. This can then be used as <h:outputText value="#{item.balanceDate}"> <f:converter converterId="isoDateTimeConverter" /> <f:attribute name="pattern" value="#{item.pattern}" /> </h:outputText> *Use an EL function instead of a Converter. You can find an example here: Facelets and JSTL (Converting a Date to a String for use in a field). This can then be used as <h:outputText value="#{mh:convertIsoDate(item.balanceDate, item.pattern)}" /> *Bind the converter and datatable's DataModel as a property of the same managed bean. This way you will be able to set the converter's properties based on the row data before returning it. Here's a basic kickoff example based on standard JSF components and standard DateTimeConverter (it should work equally good on PrimeFaces components and with your custom converter): <h:dataTable value="#{bean.model}" var="item"> <h:column> <h:outputText value="#{item.date}" converter="#{bean.converter}" /> </h:column> </h:dataTable> with @ManagedBean @ViewScoped public class Bean implements Serializable { private List<Item> items; private DataModel<Item> model; private DateTimeConverter converter; @PostConstruct public void init() { items = Arrays.asList( new Item(new Date(), "dd-MM-yyyy"), new Item(new Date(), "yyyy-MM-dd"), new Item(new Date(), "MM/dd/yyyy")); model = new ListDataModel<Item>(items); converter = new DateTimeConverter(); } public DataModel<Item> getModel() { return model; } public Converter getConverter() { converter.setPattern(model.getRowData().getPattern()); return converter; } } (the Item class is just a bean with two properties Date date and String pattern) this results in 23-09-2011 2011-09-23 09/23/2011 *Use OmniFaces <o:converter> instead. It supports render time evaluation of EL in the attributes. See also the <o:converter> showcase example. <h:outputText value="#{item.balanceDate}"> <o:converter converterId="isoDateTimeConverter" pattern="#{item.pattern}" /> </h:outputText> A: The above excellent (as always) answer from BalusC is comprehensive but didn't quite hit my exact requirement. In my case, I need to bind a Converter to each iteration in a ui:repeat. I need a different Converter depending on each item being repeated. The answer did point me in the right direction, though, so I thought it worth sharing my solution in case it helps anyone else. I use a Converter that delegates all it's work to another Converter object specified in the attribute, as in the first of BalusC's answers. Note that this doesn't help at all if you wish to use converters with parameters, it's aimed at the situation where you would want to bind a Converter to a property of a repeating object. Here's the delegating Converter. It's also a Validator, which works in exactly the same way. // package and imports omitted for brevity @FacesConverter(value="delegatingConverter") @FacesValidator(value="delegatingValidator") public class Delegator implements Converter, Validator { // Constants --------------------------------------------------------------- private static final String CONVERTER_ATTRIBUTE_NAME = "delegateConverter"; private static final String VALIDATOR_ATTRIBUTE_NAME = "delegateValidator"; // Business Methods -------------------------------------------------------- @Override public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { return retrieveDelegate(component, Converter.class, CONVERTER_ATTRIBUTE_NAME) .getAsObject(context, component, value); } @Override public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { return retrieveDelegate(component, Converter.class, CONVERTER_ATTRIBUTE_NAME) .getAsString(context, component, value); } @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { retrieveDelegate(component, Validator.class, VALIDATOR_ATTRIBUTE_NAME) .validate(context, component, value); } private <T> T retrieveDelegate(UIComponent component, Class<T> clazz, String attributeName) { Object delegate = component.getAttributes().get(attributeName); if (delegate == null) { throw new UnsupportedOperationException("No delegate was specified." + " To specify, use an f:attribute tag with: name=\"" + attributeName + "\""); } if (!(clazz.isAssignableFrom(delegate.getClass()))) { throw new UnsupportedOperationException("The specified delegate " + "was not a " + clazz.getSimpleName() + " object. " + "Delegate was: " + delegate.getClass().getName()); } return (T) delegate; } } So now where I would wish to use this code within my ui:repeat, which won't work: <h:outputText value="#{item.balanceDate}"> <f:converter binding="#{item.converter} /> <f:validator binding="#{item.validator} /> </h:outputText> I can instead use this code, which works OK: <h:outputText value="#{item.balanceDate}"> <f:converter converterId="delegatingConverter"/> <f:validator validatorId="delegatingValidator"/> <f:attribute name="delegateConverter" value="#{item.converter}"/> <f:attribute name="delegateValidator" value="#{item.validator}"/> </h:outputText> Assuming that the repeating item has a public Converter getConverter() method and similar for the Validator. This does have the advantage that the same Converters or Validators that are used elsewhere can be re-used without any changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Python decode text to ascii How to decode unicode string like this: what%2527s%2bthe%2btime%252c%2bnow%253f into ascii like this: what's+the+time+now A: in your case, the string was decoded twice, so we need unquote twice to get it back In [1]: import urllib In [2]: urllib.unquote(urllib.unquote("what%2527s%2bthe%2btime%252c%2bnow%253f") ) Out[3]: "what's+the+time,+now?" A: Something like this? title = u"what%2527s%2bthe%2btime%252c%2bnow%253f" print title.encode('ascii','ignore') Also, take a look at this A: You could convert the %(hex) escaped chars with something like this: import re def my_decode(s): re.sub('%([0-9a-fA-F]{2,4})', lambda x: unichr(int(x.group(1), 16)), s) s = u'what%2527s%2bthe%2btime%252c%2bnow%253f' print my_decode(s) results in the unicode string u'what\u2527s+the+time\u252c+now\u253f' Not sure how you'd know to convert \u2527 to a single quote, or drop the \u253f and \u252c chars when converting to ascii
{ "language": "en", "url": "https://stackoverflow.com/questions/7530561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Cannot add a nested relation or an element column to a table containing a SimpleContent column Hi iam write this code " XmlTextReader read = new XmlTextReader("http://msdn.microsoft.com/rss.xml"); DataSet ds = new DataSet(); ds.ReadXml(read); ListView1.DataSource = ds.Tables[4]; ListView1.DataBind(); " and this error is happing "Cannot add a nested relation or an element column to a table containing a SimpleContent column" A: Your problem is you have the same element name with a different structure somewhere in the document. So, for example, if you have <Item>Bicycle</Item> and later in the document you have <Item Type="Sports"><Name>Bicycle</Name></Item> The XSD will fail to generate a proper schema for the second Item attribute structure because it's already defined Item as a SimpleContent column based on the earlier declaration. The solution is to (naturally) avoid using the same element name for different structures within your XML. Obviously in your case that's kind of inconvenient since Microsoft owns the XML in question (hypothetically, since the comment from Deni indicates this site no longer exists.) You'd have to use XMLWriter or some variant to swap out the name of the offending element for something unique. A: It looks like your xml contains an element which has both text children (simple content) and other element children. DataSet does not allow a table to have both simple content columns as well as element columns. See http://msdn2.microsoft.com/en-us/library/zx8h06sz.aspx A: In my case this error appeared on WCF client's side. On WCF server's side it was caused by missing SQL SELECT permission on a function -- System.Data.SqlClient.SqlException. WCF client trying to deserialize a dataset, which was obviously not there, kept displaying "Cannot add a SimpleContent..." error. I would not call it a misleading message, but rather one that must be interpreted properly. A: I think this error will display when you are trying to ReadXml from Responsetext from service calls. In this Case Just Fetch the necessary node attribute which you require in outerxml format . Those who are not neccessary skip that element. E.g var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); XmlDocument doc = new XmlDocument(); DataSet ds = new DataSet(); doc.LoadXml(responseString); foreach (XmlNode node in doc.SelectNodes("result/records")) { doc = new XmlDocument(); doc.LoadXml(node.OuterXml.ToString()); } using (XmlReader reader = new XmlNodeReader(doc.DocumentElement)) { ds.ReadXml(reader); reader.Close(); } In Above example I want only 'records' node in response stream . So that I am fetching only that & given to dataset for processing. I hope it helps!!!!!!!!!!!!!!!!!!!!!!!!!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7530564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Flowplayer jQuery Tools not functioning in IE 7/8 I've noticed an issue which has recently cropped up regarding Flowplayer's jQuery Tools, which do not appear to be functioning in IE 7/8. Please reference here. Works great in Safari/Firefox/IE9, - and was in IE7/8 until recently. Is anyone aware of a conflict between jQuery1.6 and jQueryTools 1.2.5 which might be causing this issue? Any feedback and suggestions is greatly appreciated. A: You can start by fixing the javascript syntax error on this line: <script>var x=0;function sendEmail(x){document.getElementById("rep_email").value=x;document.getElementById("zip_code").value=;document.locate_rep.submit()}function sendButton(){document.email_rep.submit_email.style.width="150px";document.email_rep.submit_email.value="Sending...Please Wait"}$(document).ready(function(){$("input").each(function(){$(this).data("placeholder",$(this).val())});$("input").live("focus",function(){if($(this).val()==$(this).data("placeholder")){$(this).val('')}});$("input").live("blur",function(){if(!$(this).val().length){$(this).val($(this).data("placeholder"))}})});</script> </div> It's this part of that line which is obviously missing the right-hand part of the assignment: document.getElementById("zip_code").value=; Beyond that, can you tell us what functionality on the page isn't working and give us some idea what code might be related to that feature? Please remember that we don't know your page so don't even have an idea where the flow player is on your page or what else might not be working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework complex query i'm trying to learn Entity Framework and I need some help to build my query. I have a Post class like this : public class Post { public int PostID {get;set;} public string Title {get;set;} public string Content {get;set;} public PostStatus Status {get;set;} public IList<Comment> Comments {get; set;} } I also have a Comment class : public class Comment { public int CommentID {get;set;} public string Content {get;set;} public CommentStatus Status {get;set;} } What I want is to retrieve all Article with Status == PostStatus.Published, including Comment with Status == CommentStatus.Published. As you understand, I want to display in a blog all published article with their published comment. I retrieve all published article with all comments, but I only want to get their published comment, not pending ones. var result = from art in context.Posts.Include("Comments") where art.Status == PostStatus.Published select art; Thanks for your help A: well you need to create a new object list with it. Something like this var result = from art in context.Posts.Include("Comments").ToList() where art.Status == PostStatus.Published select new Post { PostID=art.PostID, Title=art.Title, Content=art.Content, Status=art.Status, Comments=art.Comment.Select(comment => comment.Status == CommentStatus.Published).ToList()}; A: Here how to select only Published posts with at least one Published comment: var result = from p in context.Posts .Include("Comments") from c in p.Comments where p.Status == PostStatus.Published && c.Status == CommentStatus.Published select new Post { PostID = p.PostID, // ... other members of Post Comments = p.Comments .Where(c2 => c2.Status == CommentStatus.Published).ToList() }; A: After some research and using your answers, I found that the good way to go is : context.Posts.Where(p=> p.InternalStatus == (int)PostStatus.Published).ToList() .Select(item => new Post { PostID = item.PostID, Title = item.Title, Author = item.Author, Content = item.Content, DateCreation = item.DateCreation, Status = item.Status, Comments = item.Comments.Where( comment => comment.InternalStatus == (int) CommentStatus.Approved).ToList() }).AsQueryable();
{ "language": "en", "url": "https://stackoverflow.com/questions/7530578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Site Authentication Cookie sharing I've got 2 MVC3 Internet websites. One (Site1) uses Windows authentication and is in the Local Intranet Zone. The second (Site2) is publicly available and uses Forms Authentication. Both sites are in the same Domain, but have a different sub-domain. I want to share authentication cookies between the two. In order to do this, they need identical settings in the web config. Sometimes this works, most of the time it doesn't. If anyone hits Site1 from outside our network, they get a 403 error, which is good. If a network user hits Site1, they're allowed in based on their network credentials. I then check their user's roles with the code below. var userName = string.Empty; var winId = (WindowsIdentity)HttpContext.User.Identity; var winPrincipal = new WindowsPrincipal(winId); if(winPrincipal.IsInRole("SiteAdmin")) { FormsAuthentication.SetAuthCookie("siteadmin", false); userName = "siteadmin"; //This is a Forms Auth user } else if(///I check for other roles here and assign like above) Once I've checked the roles, I forward them onto Site2, creating a cookie for them if the user is in one of the roles determined in the if...statement above. if(!string.IsNullOrEmpty(userName)) { //Add a cookie that Site2 will use for Authentication var cookie = FormsAuthentication.GetAuthCookie(userName, false); cookie.Domain = FormsAuthentication.CookieDomain; //This may need to be changed to actually set the Domain to the Domain of the TVAP site. HttpContext.Response.Cookies.Add(cookie); } //Network users not found in roles will simply be forwarded without a cookie and have to login HttpContext.Response.RedirectPermanent(tvapUrl); I've set up in the web.config a matching MachineKey (validationkey, decryptionkey and validation) for each site. They also both have the same authentiation settings, with the exception of the mode. So my config for this looks like this. <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" name=".ASPXFORMSAUTH" protection="All" path="/" domain="mydomain.com" enableCrossAppRedirects="true" timeout="2880" /> </authentication> I think my problem is that the 'authentication' mode is different for each one, so Site2 won't use the authentication cookie from site1. This is just a guess though. Is there anyway I can figure out the issue? According to this article, what I have going here should work. And there have been times where I think it's worked, but it's hard to tell, as I may have cookies cached and their getting reused. I'm hoping someone can see something I'm missing here, or has an alternative solution. UPDATE I checked my authentication cookie on Site2 after logging in normally and found the Domain wasn't set, so I've removed that line of code. Also, I read about cookies expiring when the date isn't set, so I set an Expire Date on my cookie before sending with the request. So, with those two changes, here's where I'm at. It works on Chrome and Firefox, but not with IE. Not sure. I'm going to do some additional testing from another machine and another user so I know I haven't got any residual cookies sitting around. A: I determined my problem was not setting the Expires property of my cookie. According this Microsoft article, cookies won't be written to the client unless the Expires property is set. "If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk." In this case, I needed the cookie to be written to disk since I was doing a server transfer to another site, thereby ending the session for that user. I'm not 100% sure that this was the fix, but it is working now, so I'm assuming that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving a Asp.net WebApp on SQL Server To MySQL what are the potential Issues? The WebApp makes use of Asp.net membership, And roles with session. it also uses LLBLGen Pro as a datalayer. My Question is what are the potential issues that might make this not work ? A: A few of the potential issues that come to mind: * *Security, users, groups/roles *Transactional semantics and boundaries *Porting existing stored procedures, functions, CLR code, etc. *Data type compatibility / semantics *Performance and scalability (each DB has its own areas of strengths and weaknesses) *Error reporting and recovery *Handling dynamic SQL *Lack of step-in debugging from ASP.NET to the DB with MySql *Database schema change management *Support for fulltext search *Differences in SQL queries and commands *Tool support: SQL profiler, Visual Studio T-SQL editor, etc. *Driver support *Multiple active result sets (if needed) *Async command support I'm sure there's more...
{ "language": "en", "url": "https://stackoverflow.com/questions/7530584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML5 Canvas and Line Width I'm drawing line graphs on a canvas. The lines draw fine. The graph is scaled, every segment is drawn, color are ok, etc. My only problem is visually the line width varies. It's almost like the nib of a caligraphy pen. If the stroke is upward the line is thin, if the stroke is horizontal, the line is thicker. My line thickness is constant, and my strokeStyle is set to black. I don't see any other properties of the canvas that affect such a varying line width but there must be. A: Javascript: var badCanvas = document.getElementById("badCanvas"), goodCanvas = document.getElementById("goodCanvas"), bCtx = badCanvas.getContext("2d"), gCtx = goodCanvas.getContext("2d"); badCanvas.width = goodCanvas.width = badCanvas.height = goodCanvas.height = 300; // Line example where the lines are blurry weird ect. // Horizontal bCtx.beginPath(); bCtx.moveTo(10,10); bCtx.lineTo(200,10); bCtx.stroke(); //Verticle bCtx.beginPath(); bCtx.moveTo(30,30); bCtx.lineTo(30,200); bCtx.stroke(); // Proper way to draw them so they are "clear" //Horizontal gCtx.beginPath(); gCtx.moveTo(10.5,10.5); gCtx.lineTo(200.5,10.5); gCtx.stroke(); //Verticle gCtx.beginPath(); gCtx.moveTo(30.5,30); gCtx.lineTo(30.5,200); gCtx.stroke(); // Change the line width bCtx.lineWidth = 4; gCtx.lineWidth = 4; // Line example where the lines are blurry weird ect. // Horizontal bCtx.beginPath(); bCtx.moveTo(10,20.5); bCtx.lineTo(200,20.5); bCtx.stroke(); //Verticle bCtx.beginPath() bCtx.moveTo(50.5,30); bCtx.lineTo(50.5,200); bCtx.stroke(); // Proper way to draw them so they are "clear" //Horizontal gCtx.beginPath(); gCtx.moveTo(10,20); gCtx.lineTo(200,20); gCtx.stroke(); //Verticle gCtx.beginPath(); gCtx.moveTo(50,30); gCtx.lineTo(50,200); gCtx.stroke(); HTML: <h2>BadCanvas</h2> <canvas id="badCanvas"></canvas> <h2>Good Canvas</h2> <canvas id="goodCanvas"></canvas> CSS: canvas{border:1px solid blue;} Live Demo My live demo basically just recreates what the MDN says. For even stroke widths you can use integers for coordinates, for odd stroke widths you want to use .5 to get crisp lines that fill the pixels correctly. From MDN Article If you consider a path from (3,1) to (3,5) with a line thickness of 1.0, you end up with the situation in the second image. The actual area to be filled (dark blue) only extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color. This is what happens with the 1.0 width line in the previous example code. To fix this, you have to be very precise in your path creation. Knowing that a 1.0 width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image — the 1.0 line width ends up completely and precisely filling a single pixel vertical line. A: If linewidth is an odd number, just add 0.5 to x or y. A: Try lineCap = "round" and lineJoin = "round". See "Line Styles" in this PDF to see what these parameters do. Edit 17-July-2015: Great cheat sheet, but the link is dead. As far as I can tell, there's a copy of it at http://www.cheat-sheets.org/saved-copy/HTML5_Canvas_Cheat_Sheet.pdf. A: I just solved a problem of a similar nature. It involved a bug in a For loop. PROBLEM: I had created a for loop to create a series of connected line segments and noticed that the line was thick to start but thinned out significantly by the final segment (no gradients were explicitly used). FIRST, DEAD END THOUGHT: At first I assumed it was the above pixel issue, but the problem persisted even after forcing all the segments to remain at a constant level. OBSERVATION: I noticed that I made a newbie's mistake -- I only used a single "ctx.beginPath()" and "ctx.moveTo(posX,posY)" PRIOR to the For loop and a single "ctx.stroke()" AFTER the For loop and the loop itself wrapped a single ctx.lineTo(). SOLUTION: Once I moved all methods (.beginPath(), .moveTo(), .lineTo() and .stroke()) together into the For loop so they would all be hit on each iteration, the problem went away. My connected line had the desired uniform thickness.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How is ASP.NET finding my class library? I have been asked to update a class library DLL that is being used by an ASP.NET application that someone else created. However, when I looked at the folder structure for the ASP.NET app, I found that the DLL existed under two different folders, and it looks like the app uses one DLL when you first run it, but the other after you restart IIS. I plan on fixing things up so the DLL only exists once in the application, but I'd like to understand what is happening first. Here's the deal - the DLL is called MyLib.DLL and it exists in both a BIN subfolder and a folder called MyLibrary. Here's an example of how an ASPX page in the app calls a method in the class library: Dim oMyClass As New MyLib.MyClass Dim sTemp As String = oMyClass.GetVersion() The application also has this section in the web.config file: <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="MyLib" culture="neutral"/> <codeBase version="1.0.0.0" href="MyLibrary/MyLib.dll"/> </dependentAssembly> </assemblyBinding> </runtime> Since the app had two different copies of MyLib.DLL, I updated both and had the GetVersion function return different results so I could tell which DLL was being used. When I run the app for the very first time, I can see that ASP.NET is creating a folder under the "Temporary ASP.NET Files" folder and it makes a copy of the BIN version of MyLib.DLL. And the app will return "From BIN folder" when calling the GetVersion function. However, if I restart IIS and run the app again, GetVersion will start returning "From MyLibrary folder", indicating that it is now using the DLL from the MyLibrary folder rather than the BIN folder. So, why is ASP.NET using the BIN version of the DLL first, but then using the one specified in the Codebase setting after a restart of IIS? If I wanted to get rid of the BIN version of the DLL, how can I configure the application to only use the copy in the MyLibrary folder? I tried getting rid of the BIN version, but then the app gave me an error that the assembly could not be found. Thanks - I'm new to ASP.NET so I hope this question made sense. A: Have you tried just removing the dependentAssembly call that's pointing to the MyLibrary directory? Personally, I think it makes more sense to use the bin directory since it's standard practice and no additional configuration is necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Http HEAD returning different Last-Modified dates on different servers for same resource, why? We have a Java process that fetches resources over HTTP. I discovered that one resource was not pulling correctly even after a client had modified it. Digging into it I found that on the server the process is running the Last-Modified date of the resource does not match what I see when I view info from a browser. I then tried fetching it from a different server and my laptop and both of those showed the correct date. I've since patched the process to allow the option to Ignore the header date for cases when it exists (but will be incorrect) but I would really love to know why this happens. For reference here is a curl response from the Server that returns the incorrect info. HTTP/1.1 200 OK Server: Sun-ONE-Web-Server/6.1 Date: Fri, 23 Sep 2011 14:16:57 GMT Content-length: 132 Content-type: text/plain Last-modified: Wed, 15 Sep 2010 21:58:20 GMT Etag: "84-4c91417c" Accept-ranges: bytes And then the same request on a different server (also get the same results on my machine) HTTP/1.1 200 OK Server: Sun-ONE-Web-Server/6.1 Date: Fri, 23 Sep 2011 14:18:47 GMT Content-length: 132 Content-type: text/plain Last-modified: Fri, 23 Sep 2011 01:20:43 GMT Etag: "84-4e7bdeeb" Accept-ranges: bytes Both servers are running on Fedora 10. Can anyone shed some light on this for me and how I might be able to fix this long term? A: So you have 2 servers and both return different results, i.e. inconsistency problem (I can basically see this from Etag header)? My first guess would be caching. Are the any caches active? Maybe the invaliation of cache doesn't work correctly or ttl (time-to-live) settings are too long. As test have a try and fresh restart machine with stale data and see whether results change (usually during restart of systems most of the simple cache-setups are flushed). Which kind of backend does the resource come from initially (database, file-system, 3rd party-service)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7530595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bit parity code for odd number of bits I am trying to find the parity of a bitstring so that it returns 1 if x has an odd # of 0's. I can only use basic bitwise operations and what I have so far passes most of the tests, but I'm wondering 2 things: * *Why does x ^ (x + ~1) work? I stumbled upon this, but it seems to give you 1 if there are an odd number of bits and something else if even. Like 7^6 = 1 because 7 = 0b0111 *Is this the right direction of problem solving for this? I'm assuming my problem is stemming from the first operation, specifically (x + ~1) because it would overflow certain 2's complement numbers. Thanks Code: int bitParity(int x) { int first = x ^ (x + ~1); int second = first ^ 1; // if first XOR gave 1 you'll return 0 here int result = !!second; return result; } A: Your parity function doesn't actually work as far as I can tell - it seems to get the answer right about half of the time, which is about as good as returning a random result (or even just returning 0 or 1 all the time). There are several bit level hacks which do actually work at: http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive - you probably want to look at the last one of these: http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel A: I would use actual counting rather than bit-level hacks that exploit the representation of the numbers, that would both feel safer and be more clean and easy to understand. Probably slower, of course, but that's a quite nice trade-off especially when one doesn't know anything about the performance expectations. Do to this, just write code to count the number of 1 bits, the most straight-forward solution generally boils down to a loop. UPDATE: Given the (weird and annoying) limitations, my response would probably be to unwind the loop given in the "naive" solution on the bithacks page. That wouldn't be pretty, but then I could go do something useful. :) A: Bit parity may be done like this: #include <stdio.h> int parity(unsigned int x) { int parity=0; while (x > 0) { parity = (parity + (x & 1)) % 2; x >>= 1; } } int main(int argc, char *argv[]) { unsigned int i; for (i = 0; i < 256; i++) { printf("%d\t%s\n", i, parity(i)?"odd":"even"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Android Web Request Title grab Could you please help me grab the titles from this page : http://golfnews.no/golfpaatv.php , for example ? By titles I mean the Bold text next to the hour scheldule . I need to grab each text and then put it on the device's screen. That's my code : package com.work.webrequest; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class WebRequest extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String trax; String aux = ""; setContentView(R.layout.main); TextView txt = (TextView) findViewById(R.id.textView1); trax=getPage(); aux=title (trax); txt.setText(aux); } private String title (String trax) { String aux = ""; int i,j,n; n=trax.length(); for(i=1;i<=n;i++) { if(trax.charAt(i-1)=='2'&&trax.charAt(i)=='>') { break; } } for(j=i+1;j<=n;j++) { if(trax.charAt(j)=='<'&&trax.charAt(j+1)=='/') { break; } } System.out.println("n ESTE EGAL CU "+n+"i ESTE EGAL CU "+i+" SI j ESTE EGAL CU "+j); aux = trax.substring(i+1, j); return aux; } private String getPage() { String str = "***"; try { HttpClient hc = new DefaultHttpClient(); HttpPost post = new HttpPost("http://golfnews.no/golfpaatv.php"); HttpResponse rp = hc.execute(post); if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(rp.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return str; } } -> the function that I created , private String title (String trax) is not good enough , because it grabs only the first title .. Could you please help me with the reasoning or perhaps , with a better function ? Thanks. A: This is the first time I would do such a thing... But you are welcome By the way, this is the worst way to do this. private String[] title (String trax) { String aux[] = trax.split("program-info"); int n = aux.length; String[] result = new String[i=1]; for(int i=1;i<=n;i++) result[i-1] = aux[i].subString(aux[i].indexOf("<h2>")+4,aux[i].indexOf("</h2>")); return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure ACS Popup or In Page Redirect, What's better? What to get more opinion on something I'm working on right now and what do you think is better in this situation. Right now I'm building a login using the Azure ACS, and I wanted to know which would be better. Option 1 When a user clicks the login they want to use it will open a popup window, and then they can login in there. But I can't close that popup window. Once they logged in I was hoping to close the popup and redirect to a different page from the tab they are on, but I'm not sure if that's possible with ACS. Option 2 There's the in page redirect but that takes the user away from the site, and it's something I really didn't wanna do. Is there a way to get option 1 to work the way I want it to work with Azure ACS? As in: * *User goes to my sign in page *User hits Google or Facebook *Popup open with the respective sign *After you logs in, popup closes *Tab user is on is redirect to user page, and I still have the FormCollection Object to use in that view. Here's the js I'm using. $(function () { $(".signup a").click(function () { var sizes = ["width=850,height=500"]; var url = $(this).attr("class"); var name = "popUp"; var size = sizes[0]; window.open(url, name, size); }); }); A: In your ACS Relying Party configuration you have "Return URL" configuration. This URL is where ACS will post your security token. Or in other words the final redirect location once the user logs in with an identity provider. So what you need to do is set the Return URL to something like: https://mysite/loggedin And in the loggedin page/view reload the page which opened this page and close this page: $(function() { window.opener.location.reload(); self.close(); }); Once the ACS redirects to your site WSFam will create via WSSam the WS Fed session cookie, and once you reload your opener page, your page will be loaded with the WS Fed cookie which means you will have the logged in user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to fax HTML via .NET code I have 1 HTML page in a StringBuilder that consists of a number of tables. After each table I put a page break for printing purposes. Now I need to fax this HTML page. After each page, a break page should be faxed on another page. I need to do this in either VB.NET or C#. How can this be done? A: You need to render the page in order to FAX it (usually storing it in a multipage TIFF file). You can do this by using an off-screen WebBrowser control and rendering it to a Graphics object that is backed by an Image and then encoding it into a TIFF. You might be able to do this with any bitmap format. Then you need to FAX it using this: http://www.codeproject.com/KB/cs/Fax-XP-ing.aspx or this http://faxdotnet.codeplex.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7530610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: override on non-virtual functions The C++11 FDIS it says If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed. [ Example: struct B { virtual void f(int); }; struct D : B { void f(long) override; // error: wrong signature overriding B::f void f(int) override; // OK }; What if B::f would not have been marked virtual? Is the program ill-formed, then? Or is override then to be ignored`. I can not find any handling of this case in the std text. Update 1/2 (merged) I forwarded a request to the C++ Editors to look into things. Thanks Johannes to pointing that out to me. * *"void f(long) override" does not override a function, esp. no virtual one, *therefore it is not virtual *therefore the text "If a virtual function is marked with..." does not apply *therefore the example does not match the text. But by realizing this I found, that the intention of the "override" contextual keyword can not be met: if a typo in the function name or the wrong argument type does make the function itself non-virtual, then the standard's text never applies -- and "override" is rendered useless. The best possible solution may be * *putting "virtual" in front of the example's functions A: What if B::f would not have been marked virtual? Is the program ill-formed, then? Yes, it is. Because in order to override something, that something has to be virtual. Otherwise it's not overriding, it's hiding. So, the positive answer follows from the quote in your question. A: If B:f was non-virtual, then both D:f functions would be ill-formed. A: Yes, the program is ill formed when override is added to any non-virtual function. Generally, functions with differing signatures (overloaded), are as different as functions with different names. The example given in the Spec is not meant to imply that the function name effects override. It's meant to show the common error that override is designed to prevent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How to set custom list view item's height...? I have a custom list view which contains two text views and on button. I have customized the button style. In the list view each row is not fit to show my button properly. I want to change the list item's height. How can i do that..? This is my list view. <ListView android:layout_width="fill_parent" android:scrollbars="none" android:footerDividersEnabled="false" android:minHeight="50dp" android:listSelector="#00000000" android:dividerHeight="0px" android:divider="#00000000" android:layout_height="fill_parent" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_marginRight="5dp" android:id="@+id/list_view" android:cacheColorHint="#00000000" android:background="#00000000" /> my custom view xml <?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="150dp" android:layout_height="wrap_content" android:textColor="#808080" android:text="Subtitle 2" android:id="@+id/text1" android:layout_marginLeft="5dp" android:singleLine="true"/> <TextView android:layout_width="60dp" android:layout_height="wrap_content" android:textColor="#808080" android:text="$ 00.00" android:id="@+id/text2" android:singleLine="true"/> <Button android:layout_width="80dp" android:layout_height="25dp" android:background="@drawable/type10_subbg" android:text="Add" android:textSize="20dp" android:textStyle="bold" android:textColor="#153E7E" android:id="@+id/add" /> </LinearLayout> Here is my getView. @SuppressWarnings("unchecked") @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; pos = position; holder = new ViewHolder(); convertView = inflater.inflate(R.layout.type10_sub, null); holder.text1 = (TextView) convertView.findViewById(R.id.text1); holder.text2 = (TextView) convertView.findViewById(R.id.text2); holder.add = (Button) convertView.findViewById(R.id.add); holder.add.setTag(String.valueOf(position)); holder.add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Button b = (Button)v; int tag = Integer.valueOf((String)b.getTag()); System.out.println("Added at "+tag); System.out.println("Data = "+((HashMap<String,Object>)list.get(tag)).get("text1").toString()); System.out.println("Price = "+((HashMap<String,Object>)list.get(tag)).get("text2").toString()); } }); holder.text1.setText(((HashMap<String,Object>)list.get(position)).get("text1").toString()); holder.text2.setText(((HashMap<String,Object>)list.get(position)).get("text2").toString()); convertView.setTag(holder); return convertView; } Thanks in advance....! A: convertedview.setlayoutparams(new Listview.setlayoutparams(width, height)); First put LinearLayout instead of ListView and then edit that to ListView otherwise it will not work. This is the trick. A: set minHeight in R.layout.type10_sub elements A: Its very easy to hardcode in a new height for the custom view simply specify the layout_height for the highest level item, in this case the LinearLayout. Below I've shown how to set it to 100dp <?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="100dp"> .... </LinearLayout> A: In linear layout give android:layout_height="100dp" instead of wrap_content A: use: if(convertView == null){ convertView = inflater.inflate(R.layout.type10_sub, parent); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to encrypt a string using node.js? I need a node.js equivalent of the following Ruby code: require 'openssl' digest = OpenSSL::Digest::Digest.new('sha1') signature = OpenSSL::HMAC.hexdigest(digest, 'auth secret', 'some string') I tried the following in node.js, but the Ruby signature is different from node's var crypto, signature; crypto = require('crypto'); signature = crypto.createHash("sha1").update('auth secret').update('some string').digest("hex"); A: You're on the right track. You need to use the crypto#createHmac method instead of createHash, and pass it your secret (key) when creating it. This will give you what you're looking for: var crypto = require('crypto') , hmac , signature; hmac = crypto.createHmac("sha1", 'auth secret'); hmac.update('some string'); signature = hmac.digest("hex");
{ "language": "en", "url": "https://stackoverflow.com/questions/7530619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How Blocking IO Affects A Multithreaded Application/Service In Linux Am exploring with several concepts for a web crawler in C on Linux. To decide if i'll use blocking IO, multiplexed OI, AIO, a certain combination, etc., I esp need to know (I probably should discover it for myself practically via some test code, but for expediency I prefer to know from others) when a call to IO in blocking mode is made, is it the particular thread (assuming a multithreaded app/svc) or the whole process itself that is blocked? Even more specifically, in a multitheaded (POSIX) app/service can a thread dedicated to remote read/writes block the entire process? If so, how can I unblock such a thread without terminating the entire process? NB: Whether or not I should use blocking/nonblocking is not really the question here. Kindly A: Blocking calls block only the thread that made them, not the entire process. Whether to use blocking I/O (with one socket per thread) or non-blocking I/O (with each thread managing multiple sockets) is something you are going to have to benchmark. But as a rule of thumb... Linux handles multiple threads reasonably efficiently. So if you are only handling a few dozen sockets, using one thread for each is easy to code and should perform well. If you are handling hundreds of sockets, it is a closer call. And for thousands of sockets, you are almost certainly better off using one thread (or process) to manage large groups. In the latter case, for optimal performance you probably want to use epoll, even though it is Linux-specific.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tinymce initizlising textarea with <> tags Tinymce editor is not rendering editor properly when the content is something like <textarea><p>&lt;sample data&gt;</p></textarea> i.e. <sample data>. When I initialize a TinyMCE editor here, I dont see anything as it looks like it assumes <sample data> is an HTML tag. Please assume I have tinymce.js loaded and I initilize using tinymce.init. Is there a fix for this? Please let me know if it is a server side fix, or is there a tinymce.init option I could give to fix this problem. PS: It does look like this is an HTML Entity encoding related issue but I am hardly an expert in this area. A: Have a look at the tinymce config parameter entity_encoding. If this does not work you may use this workaround // save content var saved_content = document.getElementById('id_of_my_textarea').innerHTML; // init the editor tinyMCE.execCommand('mceAddControl', false, 'id_of_my_textarea'); // after tinymce is fully initialized do // you should use the tinymce configuration parameter "setup" rather than this code here tinymce.get('id_of_my_textarea').setContent(saved_content);
{ "language": "en", "url": "https://stackoverflow.com/questions/7530622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asp.net MVC 3 view engine error I am trying for custom error handling at global level in Application_Error. Exception ex = Server.GetLastError(); Server.ClearError(); AssortmentDefinitionLogManager.LogException(ex); Context.RewritePath("/Error/Error"); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(Context); But i get this error Error Message - The view '~/Views/Shared/Error' or its master was not found or no view engine supports the searched locations. I have also tried this var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); var redirectUrl = urlHelper.Action("Error", "Error"); Response.Redirect(redirectUrl); A: create a controller called ErrorController and inside this controller create an action method called Error which returns an ActionResult (or ViewResult). Then create a view under ~/Views/Error/ called error.cshtml. This will solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: End to end profiling of web/J2EE and client applications Is there a good tool to do end to end profiling of a system that uses J2EE and has clients? I realize that you can easily profile the server and the client seperately. However, I do not know of any tools that'll give you information about the effect of the network connection between the two and how it affect's their performance. [An end-to-end profiler, would take in consideration of when the application is stuck on communicating and when it is processing] A: I am not aware of any profiling agent that provides an out-of-the-box feature to profile applications end-to-end. At least, not at the time of writing this. However, you could consider using DTrace to collect profiling information (not necessarily all the info provided by a typical profiler) from both the client and the server at the same time. An example on how to use this in a Java web-application (with Firefox as the client, and Tomcat as the server) is available in this article. The trick lies in having DTrace instrumentation built into the JVM (running the server) and the client, and in writing a DTrace script that writes the collected information from the traces into a parseable output. Since, the question isn't clear about whether the client is in Java I'll assume that the client is also in Java; if not, the application/executable must support DTrace instrumentation. A few caveats are to be mentioned though: * *DTrace is not available in all operating systems. * *It is currently available in Solaris 10 and Mac OS Leopard. *I'm not aware of Dtrace support in Linux distributions, where SystemTap is the recommended alternative. FreeBSD has an experimental implementation of DTrace. It should be noted that SystemTap is not an implementation of DTrace for Linux, but a wholly different entity in itself. *On MSFT Windows, you're left to fend for yourself, atleast for the moment. *Assumptions about the JVM and the client (since I know that the server runs on a JVM) * *If your client is a JVM then you must use a JVM that has DTrace instrumentation or equivalent (I'm referring to SystemTap here) built into it, or your DTrace/SystemTap scripts will not work. This means that unless the authors of the JRE/JDK for your distribution, have added code to support DTrace/SystemTap, you are constrained to use a JVM that has such a support built in. If it is of importance in your context, OpenJDK 1.6.0 appears have instrumentation support for SystemTap, and the Oracle/Sun Java 6 distributions for Solaris have support for DTrace. On Java 1.4 and 5 on Solaris, you'll need to install a JVMTI agent. *If your client is a web-browser or a thick-client written in a different language, then you must ensure that the process it is running under can support DTrace. For instance, DTrace instrumented Firefox is available on Solaris 10, and presumably on Solaris Express 11 (I have verified DTrace support only on OpenSolaris 2009.06). SystemTap probes haven't been added in Firefox for a lot of Linux distributions, so you'll often need to build Firefox from source, with the appropriate flags in the Firefox build script to add the probes; my previous experience with this process leads me to believe that this is doable, but isn't easy. If you are running a different application (neither Firefox, nor a JVM) as the client, then you'll need to verify DTrace/SystemTap support for it. *Writing good DTrace/SystemTap scripts to collect profiling information is not easy. You'll need to learn another language, and you'll need to ensure that the scripts do not add their own overhead (and validating the Heisenberg Uncertainty Principle in the context of profiling). You can certainly write DTrace/SystemTap scripts that operate over remote clients and servers, but it is not advisable to write the collected instrumentation data to a socket (to avoid the afore-mentioned overhead). A: Since version 8.0, JProfiler has the capability to follow RMI, web services and remote EJB calls between two profiled JVMs. In the JVM that makes the call, call sites have hyperlinks that take you to the execution site in the remote JVM: On the remote side, execution sites are recorded separately for each call sites, so you can inspect the call in isolation. Disclaimer: My company develops JProfiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: HCL color to RGB and backward I need an algorithm to convert the HCL color to RGB and backward RGB to HCL keeping in mind that these color spaces have different gamuts (I need to constrain the HCL colors to those that can be reproduced in RGB color space). What is the algorithm for this (the algorithm is intended to be implemented in Wolfram Mathematica that supports natively only RGB color)? I have no experience in working with color spaces. P.S. Some articles about HCL color: M. Sarifuddin (2005). A new perceptually uniform color space with associated color similarity measure for content–based image and video retrieval. Zeileis, Hornik and Murrell (2009): Escaping RGBland: Selecting Colors for Statistical Graphics // Computational Statistics & Data Analysis Volume 53, Issue 9, 1 July 2009, Pages 3259-3270 UPDATE: As pointed out by Jonathan Jansson, in the above two articles different color spaces are described by the name "HCL": "The second article uses LCh(uv) which is the same as Luv* but described in polar coordiates where h(uv) is the angle of the u* and v* coordinate and C* is the magnitude of that vector". So in fact I need an algorithm for converting RGB to Luv* and backward. A: HCL is a very generic name there are a lot of ways to have a hue, a chroma, and a lightness. Chroma.js for example has something it calls HCL which is polar coord converted Lab (when you look at the actual code). Other implementations, even ones linked from that same site use Polar Luv. Since you can simply borrow the L factor and derive the hue by converting to polar coords these are both valid ways to get those three elements. It is far better to call them Polar Lab and Polar Luv, because of the confusion factor. M. Sarifuddin (2005)'s algorithm is not Polar Luv or Polar Lab and is computationally simpler (you don't need to derive Lab or Luv space first), and may actually be better. There are some things that seem wrong in the paper. For example applying a Euclidean distance to a CIE L*C*H* colorspace. The use of a Hue means it's necessarily round, and just jamming that number into A²+B²+C² is going to give you issues. The same is true to apply a hue-based colorspace to D94 or D00 as these are distance algorithms with built in corrections specific to Lab colorspace. Unless I'm missing something there, I'd disregard figures 6-8. And I question the rejection tolerances in the graphics. You could set a lower threshold and do better, and the numbers between color spaces are not normalized. In any event, despite a few seeming flaws in the paper, the algorithm described is worth a shot. You might want to do Euclidean on RGB if it doesn't really matter much. But, if you're shopping around for color distance algorithms, here you go. Here is HCL as given by M. Sarifuddin implemented in Java. Having read the paper repeatedly I cannot avoid the conclusion that it scales the distance by a factor of between 0.16 and 180.16 with regard to the change in hue in the distance_hcl routine. This is such a profound factor that it almost cannot be right at all. And makes the color matching suck. I have the paper's line commented out and use a line with only the Al factor. Scaling Luminescence by constant ~1.4 factor isn't going to make it unusable. With neither scale factor it ends up being identical to cycldistance. http://w3.uqo.ca/missaoui/Publications/TRColorSpace.zip is corrected and improved version of the paper. static final public double Y0 = 100; static final public double gamma = 3; static final public double Al = 1.4456; static final public double Ach_inc = 0.16; public void rgb2hcl(double[] returnarray, int r, int g, int b) { double min = Math.min(Math.min(r, g), b); double max = Math.max(Math.max(r, g), b); if (max == 0) { returnarray[0] = 0; returnarray[1] = 0; returnarray[2] = 0; return; } double alpha = (min / max) / Y0; double Q = Math.exp(alpha * gamma); double rg = r - g; double gb = g - b; double br = b - r; double L = ((Q * max) + ((1 - Q) * min)) / 2; double C = Q * (Math.abs(rg) + Math.abs(gb) + Math.abs(br)) / 3; double H = Math.toDegrees(Math.atan2(gb, rg)); /* //the formulae given in paper, don't work. if (rg >= 0 && gb >= 0) { H = 2 * H / 3; } else if (rg >= 0 && gb < 0) { H = 4 * H / 3; } else if (rg < 0 && gb >= 0) { H = 180 + 4 * H / 3; } else if (rg < 0 && gb < 0) { H = 2 * H / 3 - 180; } // 180 causes the parts to overlap (green == red) and it oddly crumples up bits of the hue for no good reason. 2/3H and 4/3H expanding and contracting quandrants. */ if (rg < 0) { if (gb >= 0) H = 90 + H; else { H = H - 90; } } //works returnarray[0] = H; returnarray[1] = C; returnarray[2] = L; } public double cycldistance(double[] hcl1, double[] hcl2) { double dL = hcl1[2] - hcl2[2]; double dH = Math.abs(hcl1[0] - hcl2[0]); double C1 = hcl1[1]; double C2 = hcl2[1]; return Math.sqrt(dL*dL + C1*C1 + C2*C2 - 2*C1*C2*Math.cos(Math.toRadians(dH))); } public double distance_hcl(double[] hcl1, double[] hcl2) { double c1 = hcl1[1]; double c2 = hcl2[1]; double Dh = Math.abs(hcl1[0] - hcl2[0]); if (Dh > 180) Dh = 360 - Dh; double Ach = Dh + Ach_inc; double AlDl = Al * Math.abs(hcl1[2] - hcl2[2]); return Math.sqrt(AlDl * AlDl + (c1 * c1 + c2 * c2 - 2 * c1 * c2 * Math.cos(Math.toRadians(Dh)))); //return Math.sqrt(AlDl * AlDl + Ach * (c1 * c1 + c2 * c2 - 2 * c1 * c2 * Math.cos(Math.toRadians(Dh)))); } A: I'm familiar with quite a few color spaces, but this one is new to me. Alas, Mathematica's ColorConvert doesn't know it either. I found an rgb2hcl routine here, but no routine going the other way. A more comprehensive colorspace conversion package can be found here. It seems to be able to do conversions to and from all kinds of color spaces. Look for the file colorspace.c in colorspace_1.1-0.tar.gz\colorspace_1.1-0.tar\colorspace\src. Note that HCL is known as PolarLUV in this package. A: As mentioned in other answers, there are a lot of ways to implement an HCL colorspace and map that into RGB. HSLuv ended up being what I used, and has MIT-licensed implementations in C, C#, Go, Java, PHP, and several other languages. It's similar to CIELUV LCh but fully maps to RGB. The implementations are available on GitHub. Here's a short graphic from the website describing the HSLuv color space, with the implementation output in the right two panels: A: I was looking to interpolate colors on the web and found HCL to be the most fitting color space, I couldn't find any library making the conversion straightforward and performant so I wrote my own. There's many constants at play, and some of them vary significantly depending on where you source them from. My target being the web, I figured I'd be better off matching the chromium source code. Here's a minimized snippet written in Typescript, the sRGB XYZ matrix is precomputed and all constants are inlined. const rgb255 = (v: number) => (v < 255 ? (v > 0 ? v : 0) : 255); const b1 = (v: number) => (v > 0.0031308 ? v ** (1 / 2.4) * 269.025 - 14.025 : v * 3294.6); const b2 = (v: number) => (v > 0.2068965 ? v ** 3 : (v - 4 / 29) * (108 / 841)); const a1 = (v: number) => (v > 10.314724 ? ((v + 14.025) / 269.025) ** 2.4 : v / 3294.6); const a2 = (v: number) => (v > 0.0088564 ? v ** (1 / 3) : v / (108 / 841) + 4 / 29); function fromHCL(h: number, c: number, l: number): RGB { const y = b2((l = (l + 16) / 116)); const x = b2(l + (c / 500) * Math.cos((h *= Math.PI / 180))); const z = b2(l - (c / 200) * Math.sin(h)); return [ rgb255(b1(x * 3.021973625 - y * 1.617392459 - z * 0.404875592)), rgb255(b1(x * -0.943766287 + y * 1.916279586 + z * 0.027607165)), rgb255(b1(x * 0.069407491 - y * 0.22898585 + z * 1.159737864)), ]; } function toHCL(r: number, g: number, b: number) { const y = a2((r = a1(r)) * 0.222488403 + (g = a1(g)) * 0.716873169 + (b = a1(b)) * 0.06060791); const l = 500 * (a2(r * 0.452247074 + g * 0.399439023 + b * 0.148375274) - y); const q = 200 * (y - a2(r * 0.016863605 + g * 0.117638439 + b * 0.865350722)); const h = Math.atan2(q, l) * (180 / Math.PI); return [h < 0 ? h + 360 : h, Math.sqrt(l * l + q * q), 116 * y - 16]; } Here's a playground for the above snippet. It includes d3's interpolateHCL and the browser native css transition for comparaison. https://svelte.dev/repl/0a40a8348f8841d0b7007c58e4d9b54c Here's a gist to do the conversion to and from any web color format and interpolate it in the HCL color space. https://gist.github.com/pushkine/c8ba98294233d32ab71b7e19a0ebdbb9 A: I was just learing about the HCL colorspace too. The colorspace used in the two articles in your question seems to be different color spaces though. The second article uses L*C*h(uv) which is the same as L*u*v* but described in polar coordiates where h(uv) is the angle of the u* and v* coordiate and C* is the magnitude of that vector. The LCH color space in the first article seems to describe another color space than that uses a more algorithmical conversion. There is also another version of the first paper here: http://isjd.pdii.lipi.go.id/admin/jurnal/14209102121.pdf If you meant to use the CIE L*u*v* you need to first convert sRGB to CIE XYZ and then convert to CIE L*u*v*. RGB actually refers to sRGB in most cases so there is no need to convert from RGB to sRGB. All source code needed Good article about how conversion to XYZ works Nice online converter But I can't answer your question about how to constrain the colors to the sRGB space. You could just throw away RGB colors which are outside the range 0 to 1 after conversion. Just clamping colors can give quite weird results. Try to go to the converter and enter the color RGB 0 0 255 and convert to L*a*b* (similar to L*u*v*) and then increase L* to say 70 and convert it back and the result is certainly not blue anymore. Edit: Corrected the URL Edit: Merged another answer into this answer A: I think if (rg < 0) { if (gb >= 0) H = 90 + H; else { H = H - 90; } } //works is not really necessary because of atan2(,) instead of atan(/) from paper (but dont now anything about java atan2(,) especially
{ "language": "en", "url": "https://stackoverflow.com/questions/7530627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: UML Event Tables: Differences between Event & Trigger, Intermidiate Responses Suppose the event/use-case "Buy Online", in the event table, the entry may look like * *Event: Customer buys products online *Trigger: Same as Event? *Source: Customer *Use Case: Buy Online *Response: Confirmation Code, Validate Credit Card *Destination: Customer, Payment Verification System If a Payment Verification System is called in the process to Validate Credit Card, do I include it? It isit the final response? A: No, it is not the final response, but only a part of this use case. The Validate Credit Card is an extension (not an include) of the main use case, as it is optional (there are other way to pay online).
{ "language": "en", "url": "https://stackoverflow.com/questions/7530633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Duration set up with CATransform3DMakeTranslation my first question on stack overflow :) I want to make a y axis translation on a CALayer. I got a big background : 320x4000px. The translation is working with the following code : NSNumber *deplacement = [NSNumber numberWithFloat:([app.session.progression floatValue] * HAUTEUR_FOND) /100]; self.backgroundLayer.transform = CATransform3DMakeTranslation(0, -[deplacement floatValue], 0); But with this code, it's impossible to set up a duration ... I tried with that : CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"position.y"]; transformAnimation.duration = 5.0f; transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, -[deplacement floatValue], 0)]; [self.backgroundLayer addAnimation:transformAnimation forKey:@"position.y"]; but it does not work ... Thanks for help :) A: Ok, here is the answer, maybe it will help someone :) NSNumber *deplacement = [NSNumber numberWithFloat:([app.session.progression floatValue] * HAUTEUR_FOND) /100]; DebugLog(@"deplacement : %@", deplacement); if(!backgroundPositionMemo) backgroundPositionMemo = 0; CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"transform"]; transformAnimation.duration = 1.0f; transformAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, -backgroundPositionMemo, 0)]; transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, -[deplacement floatValue], 0)]; transformAnimation.removedOnCompletion = NO; transformAnimation.fillMode = kCAFillModeForwards; [self.backgroundLayer addAnimation:transformAnimation forKey:@"transform"]; backgroundPositionMemo = [deplacement floatValue];
{ "language": "en", "url": "https://stackoverflow.com/questions/7530634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel 2003 Links Paths not including drive I have an Excel 2003 Spreadsheet which reference other add-ins. The add-ins are installed in the same location in all PCs at C:\program files\MyPlugins\ Now I moved the spreadsheet to a Network Drive P: When I try to open the spreadsheet from the P: drive it is giving me an errors that it can't find the add-ins. I looked in the Links and it is now looking at P:\program files\MyPlugins\ and obviously can't find it. I believe somehow the spreadsheet is using relative paths instead of including the full path and the drive letter. Any ideas how to fix this? A: This is a common issue when moving or emailing files. If its only a few links in one file then you can remap them manually from P:\ to C:\ via Edit - Links For lots of files a utility is the way to go. You can use Bill Manville's LinkManager, available here to re-map from your UNC path. A: I wrote something about that problem, 2 years ago. It's in French, but the formulae are in English, and you can have it automatically translated for what it's worth...
{ "language": "en", "url": "https://stackoverflow.com/questions/7530635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: distributing own python, cross-linux I have the following problem. I need to distribute our own version of python with some magic in it. In order to do this, the process is the following: * *I build the python interpreter (on a redhat linux) *install it somewhere *tar.gz the whole thing *when it's time to make the user-package, unpack the tar.gz into the directory which will become the user package *tar.gz the user package directory *put the tar.gz on the web This is the method I have to use. Good, bad? I don't know, I have little experience as a packager, and in any case I can't propose a change. This is the way they always did. It turns out that when the user unpacks this tar.gz on suse, and tries to run the python setuptools (which has been installed together with python), the hashlib module raises an exception. What I found out is that building python on redhat, the python configure script finds the openssl library, which in turns makes it skip the building of the shamodule.c, md5.c and so on, and compiles hashmodule.c to attach to the openssl library. apparently, the openssl 0.9.7 on suse and the 0.9.8 on redhat are somehow different, meaning that, for some reason, the _hashlib module, when imported on suse, raises an import error, leading hashlib try to import _md5, _sha, _sha256, which are not there because on the redhat there was no reason to compile them (since openssl was jolly good there). Does anyone know how to solve this problem. As I said, my experience as a packager is the bare minimum, so any hint and proposal are welcome, and I will try to deploy it as much as I am allowed by our legacy. A: Does anyone know how to solve this problem. You can't, really. If it's not the OpenSSL library that's a problem, it could be the C library itself, or some other critical component. Your best solutions are either: (A) Build a version of Python for each operating system you wish to support, or (B) Rework your code to use the native system Python on each platform. Your alternative is to create a completely self-contained build environment so that when building under RedHat you're not using the system OpenSSL library, but are instead using one that you built yourself. This will work for just about everything other than the C library, but it can be tricky to set up. The idea is to minimize the relationship between your package and the system libraries. If you're only supporting RedHat and SUSE, you could conceivably pursue option (A) by crafting an appropriate spec file and building binary packages for each platform. This would be a nice way to package everything up. A: You should consider distributing a source RPM of your version of Python, rather than a binary tarball. You can take an existing Python release and repackage it with a patch of your changes. There's more detail on how to do this in the RPM Book.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Video event listener not working properly (Google Chrome extension - Javascript) I am trying to track when video stops, pauses, etc in Google Chrome extension. This is example page (html5 video): http://www.kaltura.org/apis/html5lib/kplayer-examples/Player_Themable.html This is the code: var player = document.getElementById("pid_mwe_v0") || null; if (player !== null) { console.log("VIDEO FOUND!!!!!!!"); player.addEventListener("pause", function(event){ console.log("pause"); },false); player.addEventListener("play", function(event){ console.log("play"); },false); player.addEventListener("play", logger, false); player.addEventListener("pause", logger, false); } else{ console.log("NO VIDEO"); } * *Why It doesn't detect this video by it's id and it detects it with: document.getElementsByTagName("video")[0] and how to detect it by id? *Even When video is detected it doesn't fire play and pause events when I click play/pause. How to do it properly?
{ "language": "en", "url": "https://stackoverflow.com/questions/7530647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EF return parent entity only I'm having an issue when trying to serialise an entity. An error is being through saying that the query may result in a circular query. Ideally I just want to pull out the entity with no relationships attached. I've seen some examples where you can set the relation accessor to Internal but this causes other issues. Is there a way to do this in straight LINQ? Thanks for the help. A: Try returning a single entity using FirstOrDefault() The reason that you are getting the circular error is probably due to your data model where a row points to the parent which could be the same row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tab control with datagridview is not working in winforms I have a form 1 with 2 datagrid view controls and tab control with two tabs. When I click on the datagridview cell I want to load something into two tabs. First Tab I want to display the selected datagridview row values in text boxes in first tab.... this was working fine.... Second tab I want to populate the other datagridview in this tab depending on the selected row value (cell [0] value) in main the datagridview in form But this is not working. This is what I have done so far... private void dgvCorporatedetails_CellClick(object sender, DataGridViewCellEventArgs e) { textboxreadonly(false); btnAdd.Enabled = false; if (e.RowIndex >= 0) { int.TryParse(dgvCorporatedetails.Rows[e.RowIndex].Cells[0].Value.ToString(), out corporateid); if (corporateid > 0 && tccorporates.SelectedTab == tpDetails) { getselectedrecord(corporateid); } if (corporateid > 0 && tccorporates.SelectedTab == tpmembers) { Getmembersdetails(corporateid); } } } It does not enter into this condition if (corporateid > 0 && tccorporates.SelectedTab == tpmembers) even if I click on the datagridview cell and then I select the tab2(tpmembers) datagridview does not load in this tab page (tpmembers) would any one pls help on this... A: Place a breakpoint on that line then. Is corporateid greater than 0? Is the SelectedTab set to tpmembers? If your first if statement runs, indicating that the currently selected tab is tpDetails, then the second if statement will not run. Your if statements, as written, are mutually exclusive. The way you've got it now, if the user is on tab1 and selects a row in the grid, then only tab1 will show data regarding the selected row. If they want to view the data in tab2, they have to click on your grid again to load data into that tab. How about just loading all the data into both tabs at once, regardless of which one is currently selected? int corporateid; if (e.RowIndex >= 0 && int.TryParse(dgvCorporatedetails.Rows[e.RowIndex].Cells[0].Value.ToString(), out corporateid)) { if (corporateid > 0) { getselectedrecord(corporateid); // load data into tpdetails tab Getmembersdetails(corporateid); // load data into tpmembers tab } } Just omit the tccorporates.SelectedTab == tpDetails and tccorporates.SelectedTab == tpmembers statements from your if blocks. When the user clicks on tab2, everything will already be loaded for them. A: Try to implement the SelectedIndexChanged event for the tabcontrol. So when you switch between the tab pages, update the respective controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show annotation AFTER the pin is dropped? I have been checking a couple of related posts regarding the callout behaviour. I know didAddAnnotationViews could bring annotation view along with the pin when it starts dropping. But what I actually want is show the annotation AFTER the pin is dropped onto the map, just like when you search an address in "Maps" application on iPhone, the pin drops on the map, and then the annotation pops up. Does anyone know how to do that? Do I need to do some customisation on the annotation view? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rendererAdd function for Spark DataGrid? Like we have rendererAdd function/hook for a Spark List which is dispatched when an itemrenderer is added to the container ? Do we have any similar method/hook at DataGrid level also ? Thanks in Advance A: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/supportClasses/ListBase.html#itemAdded()
{ "language": "en", "url": "https://stackoverflow.com/questions/7530655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Positioning of a pop up All divs change position horizontally if you make the browser window larger. Is there way to prevent this happening? Any help greatly appreciated. Thanks A: I see you're using jQuery on the page, why don't you try the jQuery UI position utility: http://jqueryui.com/demos/position/ This allows you to position any element relative to another element. A: setPositionPopUp: function ($posObj, $dlg, topOff, leftOff) { var dl = $dlg.get(0); if ($dlg.length == 0) { return; } if (topOff == null) topOff = 20; if (leftOff == null) leftOff = 20; var v = $posObj.offset(); dl.style.position = "absolute"; dl.style.top = (v.top + topOff) + 'px'; dl.style.left = (v.left + leftOff) + 'px'; dl.style.zIndex = "10000"; $dlg.fadeIn("slow"); } I have used the above code to achieve what you want. If you dont want to include the whole jquery ui file. You can call it like follows: setPositionPopup($('.colors_box'), $('img')); Choose your selectors correctly obviously.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this.init = function() called every time file is loaded? I can't find a definitive answer if an init function is called automatically when the file is loaded. Is this a built-in part of JS/Jquery, or am I missing where it's getting called from in some location of another file? If it is being called automatically, is this reoccurring every time the file is loaded? Example of the particular setup: ExampleClass = function() { this.init = function() { //... } } A: no init is not called automatically when file is loaded. A: Something else is calling it, that is not a behavior of javascript. A: Init is called when DOM is ready, not called default or automatically when file is loaded. Please see below link for more understanding.You will definitely like it. Click me
{ "language": "en", "url": "https://stackoverflow.com/questions/7530661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to add another layout to display in OnActivityResult()? I have an app that has a user take a picture and have it uploaded to a website. I have this code right now: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_PIC_REQUESTED) { if(resultCode == RESULT_OK) { // Maybe add the additional code here? picture = convertImageUriToFile(imageUri, this); Thread thread = new Thread(null, uploader, "MagentoBackground"); thread.start(); m_ProgressDialog = ProgressDialog.show(pictures.this, "Please wait...", "Uploading data ...", true, true); } } else if (requestCode == EXPERIMENT_CODE) { if (resultCode == Activity.RESULT_OK) { experimentInput.setText("" + data.getExtras().getInt("edu.cs.h.exp_id")); } } } However, before the image is downloaded, I want to add a layout that brings up a Spinner (drop down menu) with a list of items that a user can choose from to describe the picture. What should I add to the code so that before the picture is uploaded, a new layout is displayed, a user makes a selection and hits the OK button on that layout, and then returns back to this piece of code to continue the upload process? A: static final int _MY_DIALOG_ = 11; if(resultCode == RESULT_OK) { showDialog(_MY_DIALOG_); } @Override protected Dialog onCreateDialog(int id) { if(id==_MY_DIALOG_){ CharSequence[] shush = new CharSequence[10]; //initialize shush Dialog dialog = new AlertDialog.Builder(this).setTitle("Select Animation") .setSingleChoiceItems(shush, 0, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //the user has selected which!!! dialog.dismiss(); } }).create(); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface arg0) { //do what you want now since the user selected! picture = convertImageUriToFile(imageUri, this); Thread thread = new Thread(null, uploader, "MagentoBackground"); thread.start(); m_ProgressDialog = ProgressDialog.show(pictures.this, "Please wait...", "Uploading data ...", true, true); } }); return dialog; } return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update a TClientDataSet with changes made to the DB without it knowing? I have a simple TClientDataSet component that I use to populate some data-aware components. However, if I insert data into my database using this dataset, I can't seem to find a proper way to sync it back into my TClientDataSet component. How do I achieve this? A: The TClientDataSet component has a Refresh method that does exactly that. Took some time for me to find this out in the docs, though. :) From the docs: From DB.pas procedure Refresh; Re-fetches data from the database to update a dataset's view of data. Call Refresh to ensure that an application has the latest data from a database. For example, when an application turns off filtering for a dataset, it should immediately call Refresh to display all records in the dataset, not just those that used to meet the filter condition. Note: The Refresh method does not work for all TDataSet descendants. In particular, TQuery components do not support the Refresh method if the query is not "live". To refresh a static TQuery, close and reopen the dataset. TDataSet generates a BeforeRefresh event before refreshing the records and an AfterRefresh event afterwards. Note: Most datasets try to maintain the current record position when you call refresh. However, this is not always possible. For example, the current record may have been deleted from the server by another user. Unidirectional datasets have no mechanism for locating the current record after a refresh, and always move back to the first record. Warning: Unidirectional datasets refresh the data by closing and reopening the cursor. This can have unintended side effects if, for example, you have code in the BeforeClose, AfterClose, BeforeOpen, or AfterOpen event handlers. A: Closing and opening the CDS didn't work for me. I'm using Delphi XE2, Update 3, with ADO tables connecting to an Access 2007 database. The only way I could refresh the data in my CDS was this: procedure TForm1.PeopleRefreshButtonClick(Sender: TObject); // this actually re-loads the data from the table! begin DM1.PeopleTable.Close; DM1.PeopleTable.Open; DM1.PeopleCDS.Refresh; end; A refresh button on the form closes, then opens the table. Then I refresh the ClientDataSet. A: Basically, you must close the TClientDataset and then open it, loading the data from the database the same way you did originally. If the TClientDataset is connected to a TDataSetProvider, which is connected to a TDataset/TQuery descendant, all you have to do is close TClientDataset then open it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing gridview from a non GridView event I have a button outside a gridview called "UpdateAll", i need to be able to click on such button and find an item template "DropDownList" and update the database with that value for each record, I am not sure how to go about this any ideas? public void UpdateAll_Click(object sender, EventArgs e) { } Now I know I can access the drop down in the GridView_RowCommand something like this GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer); Myddl = row.FindControl("Quantity") as DropDownList; But i am not sure how to do that from an outside event that is not GridView related, I can not do the one above because it accesses the e.CommandSource. Please help. A: You can do something like this; for(int rowIndex =0; rowIndex<gv.rows.count; rowIndex++) { Myddl = gv.rows[rowIndex].FindControl("Quantity") as DropDownList; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Tab Disappears on Click? In my Android application I have three tabs in TabHost. Tab number 2 and 3 loads some data that will take around 4-5 seconds to load. When I click on any of these tabs, the tab disappeared until the data got loaded. Is there any reason for that? How can I handle this disappearing tab ? One more thing that I should have to mention here is that I am creating Custom Tabs. But no rocket science in custom tabs just follow this links tutorial: http://joshclemm.com/blog/?p=136. A: Well I have fixed the problem and find it out what I have done wrong. The tab_bg_selector.xml file in the example is using android:state_pressed="true" and android:state_focused="true" item states which I have copy/paste in my code as it is. When the Tab is pressed the android:drawable="@android:color/transparent" will make the image transparent until the selected Image will display So both these item are removed from the .xml file and now it working good :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7530674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use setInterval and clearInterval for a simple slideshow jQuery i managed to get a simple slideshow working that has two main "features": * *automatically sliding to the next image *showing the desired image on clicking the according indicator the interval is set to display the next image after 5 seconds. however, when i choose a specific image by clicking its indicator, this timer should be reset so i can display the desired image for 5 seconds before the next image is shown. right now the timer is not reset and it might happen that i can only look at the image for a very short time... so far i have the following: $('#keyvisualslides li:first-child').show(); $('#keyvisualpager li:first-child a').addClass('keyvisualactive'); var reload = setInterval(function(){ // get position of a element var mbr_total = $('#keyvisualpager li a').length; var mbr_index = $('#keyvisualpager li .keyvisualactive').parent().prevAll().length; var mbr_targetkeyvisual = mbr_index + 2; if (mbr_targetkeyvisual > mbr_total) { mbr_targetkeyvisual = 1; } // hide current image and show the target image $('#keyvisualslides li:visible').hide(); $('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show(); // remove active class from current indicator and add the same class to target indicator $('#keyvisualpager li a').removeClass('keyvisualactive'); $('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive'); }, 5000); $('#keyvisualpager li a').click(function () { var mbr_index = $(this).parent().prevAll().length; var mbr_targetkeyvisual = mbr_index + 1; $('#keyvisualslides li:visible').hide(); $('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show() $('#keyvisualpager li a').removeClass('keyvisualactive'); $('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive'); // // from now on wait 5 seconds until next image is automatically displayed // }); btw: i have to use jquery 1.2.1, no other version possible. thanks a lot A: $('#keyvisualslides li:first-child').show(); $('#keyvisualpager li:first-child a').addClass('keyvisualactive'); function showNextImage(){ // get position of a element var mbr_total = $('#keyvisualpager li a').length; var mbr_index = $('#keyvisualpager li .keyvisualactive').parent().prevAll().length; var mbr_targetkeyvisual = mbr_index + 2; if (mbr_targetkeyvisual > mbr_total) { mbr_targetkeyvisual = 1; } // hide current image and show the target image $('#keyvisualslides li:visible').hide(); $('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show(); // remove active class from current indicator and add the same class to target indicator $('#keyvisualpager li a').removeClass('keyvisualactive'); $('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive'); } var reload = setInterval(showNextImage, 5000); $('#keyvisualpager li a').click(function () { clearInterval(reload); var mbr_index = $(this).parent().prevAll().length; var mbr_targetkeyvisual = mbr_index + 1; $('#keyvisualslides li:visible').hide(); $('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show() $('#keyvisualpager li a').removeClass('keyvisualactive'); $('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive'); reload = setInterval(showNextImage, 5000); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7530677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript variable scope issue with jquery click event I am trying to assign a series of objects stored in an array to jquery click event handlers. The problem is , when the event fires, I only ever references the last object in the array. I have put together a simple example to show the problem: function dothis() { this.btns = new Array('#button1', '#button2'); } // Add click handler to each button in array: dothis.prototype.ClickEvents = function () { //get each item in array: for (var i in this.btns) { var btn = this.btns[i]; console.debug('Adding click handler to button: ' + btn); $(btn).click(function () { alert('You clicked : ' + btn); return false; }); } } var doit = new dothis(); doit.ClickEvents(); The HTML form contains a couple of buttons: <input type="submit" name="button1" value="Button1" id="button1" /> <input type="submit" name="button2" value="Button2" id="button2" /> When button1 is clicked, it says "You clicked #Button2" It seems that both button click handlers are pointing to the same object inside var btn. Considering the variable is inside the for loop, I cannot understand why. Any ideas? A: You need a function factory to close the loop variable, such as this: //get each item in array: for (var i=0; i<this.btns.length; i++) { $(this.btns[i]).click(function(item) { return function () { alert('You clicked : ' + item); return false; } }(this.btns[i])); } Another good option is to let jquery help you. Use jQuery.each(). The variable btn here is local to the handler function, and so isn't reused between iterations. This allows you to close it and have it keep its value. $.each(this.btns, function() { var btn = this; $(this).click(function () { alert('You clicked : ' + btn); return false; } }); A: within an event handler, 'this' usually refers to the element firing the event, in this case, it would be your button so the solution to your problem is fairly easy, instead of referencing the btn variable, which lives in a higher scope and gets mutated long before the event handler fires, we simply reference the element that fired the event and grab its ID $(btn).click(function () { alert('You clicked : #' + this.id); return false; }); Note: if your array contains other selectors that just the ID, this will obviously not reflect that and simply continue to show the ID Lucky, the click handler (and all other event handlers afaik) take an extra parameter for eventData, useful like so: $(btn).click(btn, function (event) { alert('You clicked : #' + event.data); return false; }); User an array if you're passing multiple things: $(btn).click(['foo', 'bar'], function (event) { alert('this should be "foo": ' + event.data[0]); alert('this should be "bar": ' + event.data[1]); return false; }); A: Your problem is here: alert('You clicked : ' + btn); btn retains the value from the last time it was called in the loop. Read the value from the button in the event. $(btn).data('selector', btn).click(function () { alert('You clicked : ' + $(this).data('selector')); return false; }); http://jsfiddle.net/Mc9Jr/1/ A: you have to use closures for this. i'm not sure if i remember the correct syntax but you could try this: $(btn).click(function () { return function() { alert('You clicked : ' + btn); return false; } }); A: maybe you need to change just the click binding: $(btn).click(function () { alert('You clicked : ' + $(this).attr('id')); return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7530678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Primitive int array to list I am trying to solve the following problem. There are two arrays A of size n and B of size n+1. A and B have all elements same. B has one extra element. Find the element. My logic is to convert the array to list and check if each element in B is present in A. But when I am using the primitive arrays my logic is not working. If I am using Integer [] a ={1,4,2,3,6,5}; Integer [] b = {2,4,1,3,5,6,7}; My code is working fine. public static void main(String [] args) { int [] a ={1,4,2,3,6,5}; int [] b = {2,4,1,3,5,6,7}; List<Integer> l1 = new ArrayList(Arrays.asList(a)); List<Integer> l2 = new ArrayList(Arrays.asList(b)); for(Integer i :l2) { if(!l1.contains(i)) { System.out.println(i); } } } And also My logic is O(n+1). Is there any better algo. Thanks A: Calculate the sum of each array. Sum(B) - Sum(A) will give you the extra element in B. A: The contains method of an ArrayList is in fact not so efficient. This allone has a runtime of O(n), so your algorithm has runtime O(n^2). I suggest to put one array in a HashSet (with a contains() runtime of O(1)). You can leave the other array as it is and iterate through the array directly. Then your runtime is O(n). Update: From the HashSet API doc: This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. I think the default Integer hash function fullfills the requirements. A: The reason it is not working for primitive arrays, is that Arrays.asList when given an int[ ] returns a List<Integer[ ]> rather than a List<Integer>. Guava has an answer to this in the Ints class. Is has an asList method that will take an int[ ] and return a List<Integer> Update int[] a = ...; int[] b = ...; List<Integer> aList = Ints.asList(a); List<Integer> bList = Ints.asList(b); The above will allow your code to work properly for int[ ] as it works for Integer[ ]. Check out Ints API A: Just for interest because it would be a bit complex because of arrays concatenation operation, but another operations would take O(n) * *Put both arrays into a single array *XOR items *All the same items will be self-removed and single element will be the last one. A: You could construct two Set<Integer> objects from your two arrays, and then use removeAll() to find the extra element. P.S. Your method is not O(n) as you seem to think. For the overall method to be O(n), each iteration of the loop has to execute in constant time; I leave it as an exercise for the reader to figure out whether this is the case. A: Construct a single Set<Integer> object. Since a Set can't have duplicate elements, add all of A, then you can use the Add function to find the one entry that returns true in B. Nice and easy. A: The fastest approach is to use int[], use Arrays.sort and merge the results. I suspect it homework, so I will leave the actual solution to yourself. This is O(n * log(n)) but the constant is lower than using wrapper objects and sets. If you know the range of values is limited, you can use a BitSet. This would detect more than one difference and still be O(n) If you know there is one and only one difference, compare the sums as @rossum suggests. A: Only for those that are interested, solution typical to the logic of rossum. But in case wen we have big numbers then it could be possible to have some overflow issue. The alg is simple, we start with w zero value and from once array we substract from another we add to it the elements, at the end we add our n+1 element. This will work in O(n) (the n is n+1) I assume that array b have more elements. long result = 0; for(int i =0; i < a.length; i++) { result -= a[i]; result += b[i]; } result += b[a.length]; And in the result we have our difference. EDIT: Even better solution proposed by harold, where we don't need to worry about memory. int result = 0; for(int i =0; i < a.length; i++) { result ^= a[i] ^ b[i]; } result ^= b[a.length]; A: If you want to convert an int array (not Integer), use IntStream: int[] arr = {15, 13, 7, 4, 1, 5, 19, 18, 7, 7, 12, 15}; List<Integer> arrayList = IntStream.of(arr).boxed().collect(Collectors.toList()); System.out.println(arrayList);
{ "language": "en", "url": "https://stackoverflow.com/questions/7530680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C# interfaces with same method name I dont know if what I'd like to do is simply not possible: or I'm not thinking about it in the correct way. I'm trying to construct a repository interface class which accepts a generic type and uses this as the basis for the return on most of its methods, ie: public interface IRepository<T> { void Add(T source); T Find(int id); } This would then be inherited by an actual repository class, like so: public class TestClientRepository : IRepository<ClientEmailAddress>, IRepository<ClientAccount> { } The idea is that within a ClientRepository, for example, I will want to perform operations against a few different object types (ClientAccount, ClientEmailAddress etc); but in the main the types of operations needed are all the same. When I try to use the TestClientRepository (after implementing the Interfaces explicitly) I cannot see the multiple Find and Add methods. Can anyone help? Thanks. A: Sure - all you've got to do is use it as the appropriate interface: TestClientRepository repo = new TestClientRepository(); IRepository<ClientEmailAddress> addrRepo = repo; ClientEmailAddress address = addrRepo.Find(10); IRepository<ClientAccount> accountRepo = repo; ClientAccount accoutn = accountRepo.Find(5); Basically explicitly implemented interface methods can only be called on an expression of the interface type, not on the concrete type that implements the interface. A: You said: (after implementing the Interfaces explicitly) When you implement an interface explicitly, the only way to "see" those methods is to have the object cast to the explicitly-implemented type. So if you wanted to use it as IRepository<ClientEmailAddress>, you'd have to cast it as such. Using it as TestClientRepository won't let you see any explicitly-implemented methods. A: Since generic parameters in inherited interfaces differ, you do not actually need the Explicit Interface Implementation for Add. Unfortunately the generic parameter does not influence the signature of Find, but you can still pick one of two Finds to be "default". For example: interface IRepository<T> { void Add(T source); T Find(int id); } class ClientEmailAddress { } class ClientAccount { } class TestClientRepository : IRepository<ClientEmailAddress>, IRepository<ClientAccount> { public void Add(ClientEmailAddress source) { throw new NotImplementedException(); } public void Add(ClientAccount source) { throw new NotImplementedException(); } public ClientAccount Find(int id) { throw new NotImplementedException(); } ClientEmailAddress IRepository<ClientEmailAddress>.Find(int id) { throw new NotImplementedException(); } } // ... var x = new TestClientRepository(); x.Find(0); // Calls IRepository<ClientAccount>.Find. ((IRepository<ClientAccount>)x).Find(0); // Same as above. ((IRepository<ClientEmailAddress>)x).Find(0); // Calls IRepository<ClientEmailAddress>.Find. A: When I explicitly implemented the interface for one of the interfaces, I was not able to use the var keyword var tcr = new TestClientRepository(); tcr. -- nothing there. When I specified the type this works as expected. IRepository<ClientAccount> ca = new TestClientRepository(); ca.Add(new ClientAccount { AccountName = "test2" }); IRepository<ClientEmailAddress> cea = new TestClientRepository(); cea.Add(new ClientEmailAddress { Email = "test2@test.com" });
{ "language": "en", "url": "https://stackoverflow.com/questions/7530683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: CGContextDrawPDFPage Leak 100% I try to Draw a pdf with CoreGraphics, everything work fine but in instrument there is a 100% leak on : CGContextDrawPDFPage(ctx, page2); I release with CGPDFDocumentRelease(); everytime i use CGPDFDocumentCreateWithURL(); There is any solution to release : CGContextDrawPDFPage ? - (void)drawRect:(CGRect)rect { if (state == 0) { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSaveGState(ctx); [[UIColor whiteColor] set]; CGContextFillRect(ctx, CGRectMake(0, 0, rect.size.width, rect.size.height)); CGContextGetCTM(ctx); CGContextScaleCTM(ctx, 1, -1); CGContextTranslateCTM(ctx, 45, -rect.size.height); CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(((CFURLRef)url)); CGPDFPageRef page = CGPDFDocumentGetPage(pdf, currentPage); CGRect mediaRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox); CGContextScaleCTM(ctx, (678) / mediaRect.size.width, (rect.size.height ) / (mediaRect.size.height)); CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh); CGContextSetRenderingIntent(ctx, kCGRenderingIntentDefault); CGContextDrawPDFPage(ctx, page); CGPDFDocumentRelease(pdf); CGContextRestoreGState(ctx); } else { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSaveGState(ctx); [[UIColor whiteColor] set]; CGContextFillRect(ctx, CGRectMake(0, 0, rect.size.width, rect.size.height)); CGContextGetCTM(ctx); CGContextScaleCTM(ctx, 1, -1); CGContextTranslateCTM(ctx, 6, -rect.size.height); CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(((CFURLRef)url)); CGPDFPageRef page = CGPDFDocumentGetPage(pdf, currentPage); CGRect mediaRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox); CGContextScaleCTM(ctx, (497) / mediaRect.size.width, (rect.size.height ) / (mediaRect.size.height)); // draw it CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh); CGContextSetRenderingIntent(ctx, kCGRenderingIntentDefault); CGContextDrawPDFPage(ctx, page); CGPDFDocumentRelease(pdf); CGContextRestoreGState(ctx); // CGContextSaveGState(ctx); CGContextGetCTM(ctx); CGContextScaleCTM(ctx, 1, -1); CGContextTranslateCTM(ctx, 506, -rect.size.height); CGPDFDocumentRef pdf2 = CGPDFDocumentCreateWithURL(((CFURLRef)url)); CGPDFPageRef page2 = CGPDFDocumentGetPage(pdf2, (currentPage + 1)); CGContextScaleCTM(ctx, (497) / mediaRect.size.width, (rect.size.height ) / (mediaRect.size.height)); CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh); CGContextSetRenderingIntent(ctx, kCGRenderingIntentDefault); //Leak 100% CGContextDrawPDFPage(ctx, page2); CGPDFDocumentRelease(pdf2); CGContextRestoreGState(ctx); } } And I don't know why. Any idea? This is the only leak of my app :( I don't see where the leak come from :s PS : state = 0 = portrait orientation state = 1 = landscape so I draw 2 pages in landscape orientation. A: Looks like you're not releasing the CGPDFPageRef instances you're getting from CGPDFDocumentGetPage. CGPDFPageRelease(page); Add that for page and page2 at the appropriate locations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change background color on elements with the same color I'm trying to create a simple theme system here. I have few elements with red background color. I also have a button that will change the elements background color to green. I'm trying to code but I couldn't figure out how can I select and change the bg color of all red elements to green! For example, I have 4 divs. Two of these have a red header, and when I click the button these headers background color must be changed to green. It's Ok here, but the problem is that the divs are dynamically generated, so do I have do loop all the page to find the red bg color? Could someone enlight me? =) Thanks a lot! =) A: I think the best solution would be to use different stylesheet for each theme and keep the current theme value in SESSION or COOKIE or just pass it as URL argument. But that would be a server side solution. On Client side, you can just use different classes for each theme and toggle them on the button push event using .toggleClass() $('.green').toggleClass('red green'); A: The easiest way to do this would be to have a specific CSS class for each background color you're using. ex: .color-red{ background-color: #FF0000; } .color-green{ background-color: #00FF00; } Once you do that you can select on the CSS class as well as set the CSS class: $('#button-togreen').click(function(){ $('.color-red').removeClass('color-red').addClass('color-green'); } It's kind of a round-about way of doing it, however there is no easy way to select on a CSS attribute (to do that you'd have to select all elements of the page and then check each one of them for the background color attribute which would be scarily inefficient...) A: I don't know what you mean by headers, but I think this should do what you want: $('.myDivs').filter(function(index){ return $(this).css('color') == 'red'; }).css('color', 'green');
{ "language": "en", "url": "https://stackoverflow.com/questions/7530686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I force IE users to install Google Chrome Frame Plugin I am using google visualization for charts, which doesn't render very well in IE8, and doesn't work at all in IE6. I added google chrome frame, and if the user installs the plug-in google visualization works flawlessly. Is there a way that I can force IE users to install GFC? Right now it is optional. I read the documentation, and there does not seem to be a way to configure this through the GFCInstall.check() function call. Here is my current code: <!--[if IE]> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script> <style> .chromeFrameInstallDefaultStyle { border: 5px solid blue; top:55%; } </style> <script> // The conditional ensures that this code will only execute in IE, // Therefore we can use the IE-specific attachEvent without worry window.attachEvent("onload", function() { CFInstall.check({ mode: "inline" }); }); </script> <![endif]--> A: It would almost certainly be better to do this via capability-sniffing. Assuming that the feature you need to get nice visualisations is <canvas> support, sniff for that rather than a specific browser: if (!('width' in document.createElement('canvas'))) { document.write( 'The visualisations on this page don\'t work well in your current browser. '+ 'Please upgrade to a modern browser such as IE9, Firefox, Opera, Safari or '+ 'Chrome, or install Chrome Frame for earlier IE versions.' ); } A: No you cannot force the user - your best options from the Google Chrome Frame FAQ: How do I tell if a user has Google Chrome Frame installed? Google Chrome Frame adds a ‘chromeframe/X.X.X.X’ token to the User-Agent header so you can check for its presence that way. If Google Chrome Frame isn’t present, you can choose to either prompt or show fallback content. See http://www.chromium.org/developers/how-tos/chrome-frame-getting-started/understanding-chrome-frame-user-agent for more information on the User-Agent header. We've also provided a JavaScript library you can use to test whether Google Chrome Frame is installed and if not, to prompt the user to install it. See http://www.chromium.org/developers/how-tos/chrome-frame-getting-started for more details on how to use and customize the JavaScript library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you draw an arrow at the end of a bezier curve in SVG / raphael? I have a curve generated by this: var path = ["M", x1.toFixed(3), y1.toFixed(3), "L", arrow_left_x, arrow_left_y, "L", arrow_right_x, arrow_right_y, "L", x1.toFixed(3), y1.toFixed(3), "C", x2, y2, x3, y3, x4.toFixed(3), y4.toFixed(3)].join(","); but my arrow is not correctly done. - it only points to the right, and doesn't point the same direction as the slope of the curve at the end of the bezier. - it is not filled now, I know I'm not doing the math correctly here, but mainly, I just want to know how to fill the triangle at the end of the line. thanks! For demo purposes: arrow_left_x = (x1 - 8); arrow_left_y = (y1 - 8); arrow_right_x = (x1 - 8); arrow_right_y = (y1 + 8); that is the code for getting the the coordinates I use. A: I guess you should use markers for your purpose. See an example here. Edit: You need to create a marker in the defs section: var defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs'); var marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker'); marker.setAttribute('id', 'Triangle'); marker.setAttribute('viewBox', '0 0 16 16'); marker.setAttribute('refX', '0'); marker.setAttribute('refY', '6'); marker.setAttribute('markerUnits', 'strokeWidth'); marker.setAttribute('markerWidth', '16'); marker.setAttribute('markerHeight', '12'); marker.setAttribute('orient', 'auto'); var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); marker.appendChild(path); path.setAttribute('d', 'M 0 0 L 16 8 L 0 16 z'); path.setAttribute('stroke', '#000'); path.setAttribute('stroke-width', '1'); path.setAttribute('style', ' marker-start :none; marker-end :none; '); document.getElementById( id_of_svg_placeholder ).getElementsByTagName('svg')[0].appendChild(defs); defs.appendChild(marker); and referense it in CSS: path {marker-start:url("#Triangle")} or as an attribute: <path d="..." marker-start="url(#Triangle)" /> Here's the resulting jsfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7530689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Should I port my WebBroker projects to Indy Long ago I started some "web applications" using Delphi 2007 and WebBroker (TWebModule). At the time I assumed you needed a webserver such as Apache or Microsoft IIS in order to create any sort of website. Additionally I don't use most of the Apache features (except for Virtual Server so I can have multiple domains on a single ip address and SSL). So to me Apache is just an extra layer and makes makes debugging difficult. Now enter Indy (TIdHTTPServer). If I understand correctly, Indy IS a webserver. So by using Indy I am no longer bound to use Apache or some other webserver. Is this correct? Will I have any issues supporting the Virtual Servers in an Indy environment? And what about SSL. I have searched the literature and from what I can see it fully supports SSL certificates. I am now in the process of porting some of my application from WebBroker to Indy. This mostly entails replacing within my code references of Request: TWebRequest with ARequestInfo: TIdHTTPRequestInfo and references to Response: TWebResponse with AResponseInfo: TIdHTTPResponseInfo. Is there anyway to use the TWebModule architecture within Indy so that I don't need to do all of this rewriting? Lastly is there anything else I need to be concerned with? My goal is to take Apache out of the loop. A: Yes, you can use Indy's TidHTTPServer as a webserver, but it's much lower-level than IIS or Apache. There is no concept of virtual servers - this you would have to implement yourself. Indy does support SSL as well via the OpenSSL dll's. I imagine the biggest concerns you will have will be security related...there are millions and millions of sites running Apache or IIS and there are a ton of people devoted to finding flaws in those platforms, with a bunch of people fixing some of those flaws as they come up. Not so with Indy... there's one or two guys that respond on newsgroups to bugs that you discover. (One guy in particular, who will probably respond to your question here as well.) Now, I use Indy HTTP server (along with SecureBlackBox SSL support) and I find it to be great for my purposes. A: Indy HTTP server calls the WinSock API, and is able to implement: * *A full HTTP/1.1 server; *A full HTTPS server (using either OpenSSL libraries or other third parties, like SecureBlackBox). AFAIK you can use Indy to publish web modules. See http://www.2p.cz/files/2p.cz/downloads/howto/indy_soap_web_services_in_delphi.pdf You can also use other servers, for instance directly the kernel-mode http.sys server, which is used by ISS and .Net WCF for instance, and known to be very stable and efficient (it bypasses the WinSock APIs). Of course, it will serve HTTPS conent, if needed. It is available in standard since Windows XP SP2, and therefore in Vista and Seven. Using this component will let Microsoft will do all the debugging work for you, and it will be updated with the host OS. I use it for instance in our Client-Server ORM, or directly to replace a deprecated DCOM connection, with very good speed and stability on customer side. A: Regarding virtual servers - the HTTP 1.1 spec requires clients to send a Host request header so virtual servers know which domain is being used specifically to handle the case when multiple domains have the same IP. TIdHTTPRequestInfo has a Host property for that value. In fact, TIdHTTPServer internally validates to makes sure that an HTTP 1.1 request has the Host header before firing any of its OnCommand... events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Question about ASP.NET gridviews I have a gridview. Is it possible to modify the gridview so that I can have multiple rows in the column headers? For example, the following code generates the table in the picture below. <asp:GridView ID="productsGridView" Runat="server" DataSourceID="productDataSource" AutoGenerateColumns="False" AllowSorting="True" BorderWidth="2px" BackColor="White" GridLines="None" CellPadding="3" CellSpacing="1" BorderStyle="Ridge" BorderColor="White" AllowPaging="True"> <FooterStyle ForeColor="Black" BackColor="#C6C3C6"></FooterStyle> <PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#C6C3C6"></PagerStyle> <HeaderStyle ForeColor="#E7E7FF" Font-Bold="True" BackColor="#4A3C8C"></HeaderStyle> <Columns> <asp:BoundField HeaderText="Product" DataField="ProductName" SortExpression="ProductName"></asp:BoundField> <asp:BoundField HeaderText="Unit Price" DataField="UnitPrice" SortExpression="UnitPrice" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="Right"></ItemStyle> </asp:BoundField> <asp:BoundField HeaderText="Units In Stock" DataField="UnitsInStock" SortExpression="UnitsInStock" DataFormatString="{0:d}"> <ItemStyle HorizontalAlign="Right"></ItemStyle> </asp:BoundField> <asp:BoundField HeaderText="Quantity Per Unit" DataField="QuantityPerUnit"></asp:BoundField> </Columns> <SelectedRowStyle ForeColor="White" Font-Bold="True" BackColor="#9471DE"></SelectedRowStyle> <RowStyle ForeColor="Black" BackColor="#DEDFDE"></RowStyle> </asp:GridView> This table only has one row in the column header. What I am looking for is something like this: Any Ideas on how I can achieve this? Is this even possible? A: If you use a TemplateField instead, you can control the header template as well, which can be custom ASPX markup. The downside is that you have to display the data manually with Labels instead of using the simpler BoundField properties. However, this also allows you to layout the data in a custom layout to fit with the heading: <Columns> <asp:TemplateField> <HeaderTemplate> Weight<br /> Date | Time<br /> Product </HeaderTemplate> <ItemTemplate> <asp:Label runat="server" Text='<%#Eval("Weight") %>'></asp:Label><br /> <asp:Label runat="server" Text='<%#Eval("Date") %>'></asp:Label> | <asp:Label runat="server" Text='<%#Eval("Time") %>'></asp:Label><br /> <asp:Label runat="server" Text='<%#Eval("Product") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns>
{ "language": "en", "url": "https://stackoverflow.com/questions/7530702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connection string from SqlException "network-related or instance-specific error?" Some of my sites are reporting the following error: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) The site switches connection string dynamically and I suspect the issue is that it is not doing this correctly. If I can extract the server name it is failing to connect to, I can investigate further. Is there any way to do this in, say, Application_Error in the global.asax? A: This can be caused by the SQL Server service stopping running. Open SQL Server Configuration Manager and restart the SQL Server service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Animation when changing ContentTemplate I have a window where different controls had to be displayed over time. I searched for a solution with using the mvvm pattern and ended up with this <ContentControl Content="{Binding}"> <ContentControl.Style> <Style TargetType="ContentControl"> <Style.Triggers> <DataTrigger Binding="{Binding ViewType}" Value="RecipeList"> <Setter Property="ContentTemplate" Value="{StaticResource RecipeTemplate}"/> </DataTrigger> <DataTrigger Binding="{Binding ViewType}" Value="Default"> <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}"/> </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style> </ContentControl> This works fine so far but i'm curious about two things: * *is there a better approach with mvvm? *how can i execute an animation for the items in the new datatemplate that is about to be shown? A: Since Animations are View-Specific actions, they should be run from the Code-Behind the View, not the ViewModel. In the past, I've hooked into an Event and just run the following from the code-behind: Storyboard animation = (Storyboard)panel.FindResource("MyAnimation"); animation.Begin(); As for question #1, I don't see any problem with your code for displaying a different View based on a property in the ViewModel. A: For the question #2: You could use EventTrigger in controls within you templates to start animation like it is done below: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.Triggers> <EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard> <Storyboard x:Name="SomeStoryBoard"/> </BeginStoryboard> </EventTrigger> </Grid.Triggers> </Grid> </Window>
{ "language": "en", "url": "https://stackoverflow.com/questions/7530708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Node.js "new Socket" create a Unix file socket? I've been working with node.js for the past couple of weeks and I need to implement the FAST-CGI protocol. The problem is that when I create a UNIX socket (via "new Socket") I need to get the filename, or file descriptor. But socket.fd is null (default parameter). My question is: Does "new Socket" creates a operating system socket object file, and if so, how can I get the Socket File Descriptor or File Name? I'm not sure if this is how I should create a Socket, but here is the case: node: var net = require(net) var socket = new net.Socket() console.log(socket); { bufferSize: 0, fd:null, type: null, allowHalfOpen: false, _writeImpl: [Function], _readImpl: [Function], _shutdownImpl: [Function] } A: Well when you connect a socket, socket.fd is not null, at least not in my case, so provide an example case please. Note that you can also specify existing file descriptor at socket creation. Edit: var net = require('net'), fs = require('fs'), sock; // Create socket file fs.open('/tmp/node.test.sock', 'w+', function(err, fdesc){ if (err || !fdesc) { throw 'Error: ' + (err || 'No fdesc'); } // Create socket sock = new net.Socket({ fd : fdesc }); console.log(sock); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7530709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I preserve html as is when using Javascript's innerHTML everything is working fine, decodeURIComponent(xmlhttp.responseText) comes back as html from parsing script as checked with alert, no errors in the console, but replacing the html to the editor with retHTML.innerHTML =decodeURIComponent(xmlhttp.responseText); seems to have a "feature" of translating my html to encoded html(& to &amp;) etc.. I'm not sure why a command that says it is the inner html would prevent you from actually using html? innerText simply amplifies this rather then returning the html free text as implied. How do I get the returned html back to the div as the html I am requesting? function setHTML(retHTML) { retHTML.innerText =retHTML.innerHTML; } function setTEXT(retHTML) { var tmpTXT =encodeURIComponent(retHTML.innerText); var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { retHTML.innerHTML =decodeURIComponent(xmlhttp.responseText); } xmlhttp.open("POST","path.php",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send('send=' + tmpTXT); } test markup as follows <object width="853" height="510"> <param name="movie" value="http://www.youtube.com/v/iaysTVcounI?version=3&amp;hl=en_US&amp;rel=0"> <param name="allowFullScreen" value="true"> <param name="allowscriptaccess" value="always"> <embed src="http://www.youtube.com/v/iaysTVcounI?version=3&amp;hl=en_US&amp;rel=0&amp;autoplay=1" type="application/x-shockwave-flash" width="853" height="510" allowscriptaccess="always" allowfullscreen="true"> </object> should be <object width="853" height="510"> <param name="movie" value="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0"> <param name="allowFullScreen" value="true"> <param name="allowscriptaccess" value="always"> <embed src="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" width="853" height="510" allowscriptaccess="always" allowfullscreen="true"> </object> A: innerHTML is a parser when you write to it and a serialiser when you read, not a simple property that stores text. When you write to innerHTML, it converts the HTML source text into DOM objects like Element, Attr and TextNode. It is these DOM objects that reflect the real live state of the document in the browser window, and not anything that looks like HTML source. On writing, any information that is not significant to the ‘information set’ stored in the DOM is lost. This includes things like case (whether your tag was <b> or <B>), order of attributes, whitespace inside tags, entity and character references (ie whether you said café, caf&#233; or caf&eacute;—it's all the same to an HTML parser), and much more. Reading back the innerHTML you just wrote will re-serialise the parsed DOM and give you something back that won't necessarily be the same string as what you put in. If you made mistakes in your original HTML, you'll also find that the output has been corrected to reflect what the HTML parser did to be able to read what you put in. So an invalid bare ampersand will necessarily turn into &amp;. (I'm not sure what kind of ‘editor’ you're referring to, but if it's a <textarea> then that will additionally fix up < to &lt; in any HTML you write to it, because a textarea can't contain markup. It's also rather odd and unnecessary that you would be passing back URL-encoded data in a responseText; are you sure that's what's happening?) ETA: should be value="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0" No it shouldn't. That's not valid HTML. Escaping the &s to &amp; is absolutely the correct, required thing to do. A: I feel this is kinda ghetto but ultimately the following will be my fix. I recomend this as an alternative to innerHTML for literal replacement of the string. retHTML.innerHTML =''; retHTML.execCommand('insertHTML',false,xmlhttp.responseText);
{ "language": "en", "url": "https://stackoverflow.com/questions/7530712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AbstractFactory with generic types in Java: a design problem I have the following 2 interfaces accordingly to abstract factory pattern: public interface GenericObjectInterface<T extends Number>{ public T getResult(); } public interface AbstractFactoryInterface{ public <T extends Number> GenericObjectInterface<T> createGenericObject(); } I have an abstract class implementing GenericObject, but it's still unaware of the concrete type (it does only generic operations on Number): public abstract class GenericAbstractClass<T extends Number> implements GenericObjectInterface<T>{ } Then I have a series of concrete class extending that perform generic parameter substitution: public class IntegerObject extends GenericAbstractClass<Integer>{ public Integer getResult(){} } .... Now, from inside an implementation of the factory I build the concrete type, that's implementing GenericObjectInterface but has lost it's generic parameter: public class ConcreteFactory{ public <T extends Number> GenericObjectInterface<T> greateGenericObject(Class<T> c){ if (c.class.isInstance(Integer.class)){ IntegerObject obj = new IntegerObject(); //I would like to return obj GenericObjectInterface<T> a = new IntegerObject(); //errror GenericAbstractClass<T> a = new IntegerObject(); //errror return a; }else if (c.class.isInstance(Double.class)){ } } } I would like to return obj that implements GenericObjectInterface but I don't know how can I do it. how can I solve this? I'm used to abstract factory but I've never used it with generics. Am I doing some mistakes in interpreting the pattern? A: If your method returns an IntegerObject why don't you just return GenericObjectInterface<Integer>? You already know the parameter type. In that case, just add a generic parameter to AbstractFactoryInterface, too: public interface AbstractFactoryInterface<T extends Number> { ... } public class ConcreteFactory implements AbstractFactoryInterface<Integer> { ... } In your implementation the type of T would be inferred from the assignment, and thus you could do this: GenericObjectInterface<Double> g = new ConcreteFactory().greateGenericObject(); In that case T would be Double but you'd use Integer internally, resulting in this: GenericObjectInterface<Double> a = new IntegerCell(); Since the compiler can't ensure that T will always be of type Integer it won't allow you to do that assignment. A: Abstract factory is characterized by the factory method returning an interface or abstract class reference instead of the concrete reference. It does not extend to type parameters. Think of it this way: should you be able to do this? public class ConcreteListFactory { public <T> List<T> createList() { return new ArrayList<String>(); } } What if the caller wanted a List<Integer>? If you want your factory to return a generified type, you should have your concrete class accept the type parameter. Otherwise have your factory method return a GenericObjectInterface<Integer>. Alternatively, you could have your method accept a type token (Integer.class). For example: public <T extends Number> GenericObjectInterface<T> createGenericObject(Class<T> clazz) { if ( clazz.equals(Integer.class) ) { return (GenericObjectInterface<T>) new IntegerObject(); } } This will result in an unchecked cast warning but you can prove to yourself that it is safe, and thus suppress the warning or ignore it. A: Generally, factories are not implemented as generics because you can't examine the type of the generic to determine the type of object to create (you can't do T.getClass) which is why @Mark's example causes the class to be passed in as an argument. I think, more usually you would have multiple concrete factories. One for each Number type that you intend to support. public interface AbstractFactoryInterface<T extends Number> { public GenericObjectInterface<T> createGenericObject(); } class IntegerFactory implements AbstractFactoryInterface<Integer>... class LongFactory implements AbstractFactoryInterface<Long>... You could then create a Map<Class, AbstractFactoryInterface>... Map<Class, AbstractFactoryInterface> myMap = ...; myMap.put(Integer.class, new IntegerFactory()); myMap.put(Long.class, new LongFactory ()); A: casting is perfectly fine here. if c==Integer.class, then T=Integer, casting GOI<Object> to GOI<T> is absolutely correct. It is a checked cast because you have checked that T=Integer before casting, therefore the unchecked warning can be legitimately suppressed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pass a Control to a Method I'm trying to create a method that will custom validate any TextBox control passed to it. Here's what I've got so far: A Custom Validator protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args) { CustomValidator ThisValidator = sender as CustomValidator; TextBox MyBox = FindControl(ThisValidator.ControlToValidate) as TextBox; args.IsValid = isValid(MyBox); } Validation Method protected bool isValid(System.Web.UI.WebControls.TextBox MyBox) { bool is_valid = MyBox.Text != ""; MyBox.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink; return is_valid; } The code compiles OK but I get a NullReferenceException was unhandled by user code on bool is_valid = MyBox.Text != ""; When I run the validation. I know I'm close (well I think I am) but where am I going wrong? A: you first need to check that the object itself exist, after casting: bool is_valid = MyBox != null; and after that you can check its text property A: Your problem is the FindControl() method is not recursive, therefore MyBox is null. You'll have to write a recursive FindControl() method like the one here if you want it to work correctly. You'll probably also want to check if MyBox is null and return out of the method if it is. A: For completeness this code did the trick for me: protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args) { args.IsValid = isValid(txtDeliveryLastName); } protected bool isValid(System.Web.UI.WebControls.TextBox MyBox) { bool is_valid = MyBox.Text != ""; MyBox.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink; return is_valid; } A: You are trying to validate an empty text box. You can't validate an empty string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Js searching object with a key I have a json string which is resulted by an ajax call which looks like this [ { "name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0" }, { "name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0" }] The page on my web app uses "id" value as the identification of an object. So I want to display the name of the user where ever users' name is required. What is the fastest way of getting the right user object to output the name or other values of user using the id value. Thanks in advance. A: Ok... this answer provides for a lot of overhead at the start, but then makes it faster to reference by id later. It basically makes an array that has each item at the same index of its id. Like I said, a lot of overhead at first but little for later processing var data = [{"name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0" }, {"name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0" }, {"name":"sourabh", "userid":"sourabhbajaj", "id":"27", "has_profile_image":"0" }, {"name":"sourabh", "userid":"sourabhbajaj", "id":"3", "has_profile_image":"0" }, {"name":"myname", "userid":"myuserid", "id":"5", "has_profile_image":"0" }, {"name":"sourabh", "userid":"sourabhbajaj", "id":"2", "has_profile_image":"0" }] arr = []; data.sort(function(a,b){return Number(a.id) - Number(b.id);}) var k = 0; var offset = Number(data[0].id); for(var i = offset; i <= Number(data[data.length - 1].id);i++) if(Number(data[k].id) === i) arr.push(data[k++]); else arr.push({}) //now you can reference like so: alert(arr[5 - offset].name) // alerts "myname" A: Make the result from ajax call like this: { "11": { "name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0" }, "12": { "name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0" }} this way you can use it from javascript like this: userName = jsonResponse[id].name A: Either search the array each time function getUser(users, id) { var user = null; $.each(users, function() { if (this.id === id) { user = this; return false; // break out of loop } }); return user } or create a reusable lookup table (assumes unique user ids): function toLookup(users) { var lookup = {}; $.each(users, function() { lookup[this.id] = this; }); return lookup; } function getUser(lookup, id) { return lookup[id] || null; } A: var data = [{"name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0" }, {"name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0" }] for(var i in data) if(data[i]["id"] == 11) alert(data[i].name); It's very simple :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7530721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++: How to init members of std::pair in constructor I have the following class: typedef std::pair<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket> socket_pair; class ConnectionPair { private: socket_pair _sockPair; public: ConnectionPair(boost::asio::io_service &ios); } How do I init the sockets in the pair in the constructor ? the following won't compile: ConnectionPair::ConnectionPair(asio::io_service &ios): _ios(ios), _sockPair(asio::ip::tcp::socket(ios), asio::ip::tcp::socket(ios)){ } EDIT: Here is the compiler error. Enjoy: /boost_1_47_0/boost/asio/basic_io_object.hpp: In copy constructor ‘boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >::basic_socket(const boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >&)’: /boost_1_47_0/boost/asio/basic_socket.hpp:43:1: instantiated from ‘std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = boost::asio::basic_stream_socket<boost::asio::ip::tcp>, _T2 = boost::asio::basic_stream_socket<boost::asio::ip::tcp>]’ /devel/msm1/connection.cpp:8:67: instantiated from here /boost_1_47_0/boost/asio/basic_io_object.hpp:163:3: error: ‘boost::asio::basic_io_object<IoObjectService>::basic_io_object(const boost::asio::basic_io_object<IoObjectService>&) [with IoObjectService = boost::asio::stream_socket_service<boost::asio::ip::tcp>, boost::asio::basic_io_object<IoObjectService> = boost::asio::basic_io_object<boost::asio::stream_socket_service<boost::asio::ip::tcp> >]’ is private /boost_1_47_0/boost/asio/basic_socket.hpp:43:1: error: within this context In file included from /boost_1_47_0/boost/asio.hpp:30:0, A: If the type is copy-constructible, your code would have worked. I guess (and only guess, because you didn't specify the compiler error) that a socket is not copy-constructible. Since std::pair does not allow in-place factories, you'll have to make your pair a pair of boost::optional's and use in-place factories. See the boost documentation for more details. A: Does boost::asio::ip::tcp::socket support copy? I wouldn't expect it. And types in an std::pair must be copyable. A: You can initialize the pair like you are trying to do, but you have a couple of other errors in your code. * *No semi colon on the end of your class declaration. *_ios member variable does not exist. Unfortunately I don't have boost installed, but this compiles for me using G++ 4.1.2 #include <utility> typedef std::pair<int, int> socket_pair; class ConnectionPair { private: socket_pair _sockPair; public: ConnectionPair(const int x); }; ConnectionPair::ConnectionPair(const int x): _sockPair(x, x) { } int main(int argc, const char *argv[]) { ConnectionPair c(10); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive I'm trying to up load my site and I'm getting this error message: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. <compilation debug="true" targetFramework="4.0"> The site works fine on my local PC but won't open when I loaded it to my host and tried to view it online. A: for IIS 7 try according to the given picture ... mark me helpful if it works for you. A: Registering the framework with IIS is what worked for me: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i A: I had to register ASP.Net in IIS to get it resolved in the Windows Server 2008 R2. Sreenshot of the commands attched below cd /d C:\Windows\Microsoft.NET\Framework\v4.0.30319 iisreset /stop aspnet_regiis -i iisreset /start %systemroot%\system32\inetsrv\appcmd set config /section:isapiCgiRestriction /[path='%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll'].allowed:True %systemroot%\system32\inetsrv\appcmd set config /section:isapiCgiRestriction /[path='%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll'].allowed:True A: I'm using IIS Express, rather than IIS. The problem was in the applicationhost.config file located in: {solution_folder}\.vs\config\applicationhost.config. One of the application pool entries had a managedRuntimeVersion value of "v2.0". I changed it to "v4.0", and it worked properly. I'm fairly sure the root cause was one of the NuGet packages I had installed recently. <system.applicationHost> <applicationPools> <add name="BadAppPool1" managedRuntimeVersion="v2.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" /> </applicationPools> </system.applicationHost> A: This typically happens when you have an attribute of targetFramework="4.0" in the web.config but the App Pool is set to run ASP.NET 2.0. The targetFramework attribute is entirely unrecognized by ASP.NET 2.0 - so changing it to 2.0 won't have the desired effect. Contact Support / Your Administrator and have the AppPool switched to 4.0. You could also remove the attribute entirely, however if your site was coded with the 4.0 Framework, then I'm sure something else will cause an error as well. A: Change the application pool to target framework 4.0 instead of classic . * *RC website ->manage website->advanced setting> *the first option change from classic to framework 4 integrated. A: In IIS Click on Application Pools Right Click on DefaultAppPool --->> Set Application Pool Default....--->>Change .Net Version to V 4.0. A: open your IIS (type inetmgr in run) and change your Application pool setting,To view large this Image Right Click Image and open image in new tab A: Open Project -> press Shift + F4 (Open properties page) -> Chose Build -> in Target Framework chose .NET Framework 4 -> OK A: I also got the same issue while running my application locally which is pointing to .Net Framework 4.7.1. The bug was "Unrecognized attribute TargetFrameWork" as shown below. But none of the above answers helped me. At last when I changed my present port (1413) number to some other value(60179) as shown below it worked fine for me.But I am not sure for the actual reason behind this , but it worked. A: Create a new pool by selecting .Net Framework v4.0.3xxxxx use the Manage Pipeline Mode: Integrated Assign it to your site and done. A: In Visual Studio menu: Website -> Start Options -> build tab -> Select Target Framework in Dropdown box (.NET FrameWork 4) A: To fix this problem simply click the ASP.NET Version icon in the Site Tools section of Control Panel to switch the framework to 4.0. A: I had this error from a failed MSBuild compile, in a project file converted from an earlier version of VS into VS2010 and .NET 4.0. It was actually a Web Deployment project, and the solution that worked for me was adding the following entries into the PropertyGroup section at the start of the MSBuild file: <ProductVersion>10.0.11107</ProductVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> Maybe these get automatically updated when other types of project are converted in VS2010, but they were missing from my Web Deployment project file after it was converted. A: What I did: I did change the value of Application Pool to DefaultAppPool from a previous value. You do this in the Advanced Settings (Website --> Manage Website --> Advanced Setting>. A: I was facing the same issue while publishing my 1'st web services. I resolved it by simply doing this: * *Open IIS *Click on Application Pools *Right Click on DefaultAppPool => Set Application Pool Default => Change .Net Version to V 4.0. (You can also change .Net Framework Version of your application specifically) Hope, it'll work. A: Just had this in VS 2010. Fixed by editing the .sln file and changing the TargetFrameworkMoniker to have the value ".NETFramework,Version%3Dv4.0" assigned to it. A: If you're using IIS Express, it creates a new configuration for each site that you run, and it's bound to the url (host/port). However, when it opens a new project using the same port it doesn't refresh the configuration. This means that if you have a project using CLR 2.0 (.NET Framework 2.0 to 3.5) running on some port and then later you open another project in the same port using CLR 4 (.NET Framework 4.x+) the new project will try to run using CLR 2, which fails - and in case it doesn't even recognize the "targetFramework" attribute. One solution is cleaning IIS Express sites, but the easiest method is changing the port so that IIS Express will create a new site (using CLR 4) for your project. A: If you compile the files and the value of the "targetFramework" is set as being a particular version i.e. 4.0, Make sure the host is running .net framework as the same version stated. If not, download the .net framework. After downloading, if it is not automatic being set in the IIS manager to be using the extension of the newly downloaded version of .net framework, add the extension manually by going to the folder of the recently downloaded .net framework THROUGH IIS manager: 1.right-click website folder 2.go to "Properties" 3.under "virtual directory" , click "configuration" 4.edit the executable path of extension ".aspx" (of which the path being pointed to version other than the version of the recently downloaded .net framework) to the correct path which is the folder of the NEWLY downloaded version of .net framework and then select the "aspnet_isapi.dll" file. 5.click ok! A: Just Remove the "Target Framework 4.0" and close the bracket. It will Work A: Follow these two steps: Register the .net framework version version 4.0 (if it is not registered) * *C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i *In the app pool change the .net framework to v4.0 A: If you install the IIS after the installation of .Net FrameWork. You need install the .net framework again for IIS. So all we need to do is run aspnet_regiis -i. Hope it is helpful. A: Saw the error "Unrecognized attribute 'targetFramework'" in the 'Console output' page of Jenkins on a build server. This was after I changed the 'target framework' for several projects from '.NET Framework 3.5' to '.NET Framework 4' and committed my changes. In Jenkins the project settings had to be changed. For the solution the 'MSBuild Version' had to be changed from 'v3.5' to 'v4.0'. A: Just had this issue deploying a new app to an old IIS box. The investigation led to the v4.5.1 run-time being installed but the app requiring v4.5.2 Nothing apart from installing the correct version of ASP .Net run-time was required. A: It could be that you have your own MSBUILD proj file and are using the <AspNetCompiler> task. In which case you should add the ToolPath for .NET4. <AspNetCompiler VirtualPath="/MyFacade" PhysicalPath="$(MSBuildProjectDirectory)\MyFacade\" TargetPath="$(MSBuildProjectDirectory)\Release\MyFacade" Updateable="true" Force="true" Debug="false" Clean="true" ToolPath="C:\Windows\Microsoft.NET\Framework\v4.0.30319\"> </AspNetCompiler> A: For layering, Just change the version of targetFramework in web.config file only, the other things no need change. A: I had the same issue and I found this nice poweshell script to update all of your app pools at the same time: https://gallery.technet.microsoft.com/scriptcenter/How-to-set-the-IIS-9c295a20 Make sure to set you $IISAppPoolDotNetVersion = "v4.0" variable at the top. A: following 2 steps will force refresh Visual Studio and IIS Express cache and usually resolve my similar issues: * *Simply switch Project framework from 4+ to .Net framework 3.5 and run it *If it ran successfully you can revert it back to your desired 4+ target framework and see that it will probably work again. A: Changing the port number for the local development helped me Thanks @Rinay Ashokan. I have done all the trouble shooting and finally found that the project configurations are stored in the IIS express for the port number. A: For anyone having this who doesn't have IIS running on their dev PC, here's what happened to me: I had one website on, overwrote with files from a diff website that was 4 while the previous was 3.5. Got this error. Fixed it simply by changing the directory name of the website, which on a dev PC can be anything, so no problem. The above are probably more elegant to be sure, but sometimes simple works, IF you can get away with it, i.e., you're in dev rather than QA or Prod.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "431" }
Q: Maven multi-project dependency management for checkstyle plugin I'm trying to use the maven-checkstyle plugin for a multi-module project here is my projec structure |pom-root | -- my-checkstyles | |-- pom.xml | |-- checkstyles | |-- checkstyles.xml | -- my-war | |-- pom.xml | -- my-ejb | |-- pom.xml | -- my-ear | |-- pom.xml | -- pom.xml and here is the pom.xml for my pom-root project : <project xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <modelVersion>4.0.0</modelVersion> <groupId>test</groupId> <artifactId>pom-root</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>my-checkstyles</module> <module>my-ear</module> <module>my-ejb</module> <module>my-war</module> </modules> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.5</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins </groupId> <artifactId> maven-site-plugin </artifactId> <version>3.0-beta-3</version> <dependencies> <dependency> <groupId>com.puppycrawl.tools</groupId> <artifactId>checkstyle</artifactId> <version>5.4</version> </dependency> <dependency> <groupId>fr.info.saone</groupId> <artifactId>info-saone-checkstyle</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <configuration> <outputEncoding>UTF-8</outputEncoding> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.7</version> <configuration> <cacheFile>target/cachefile</cacheFile> <configLocation>checkstyles/checkstyle_vnf.xml</configLocation> <linkXRef>true</linkXRef> </configuration> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> </project> When I execute mvn site it fails unless I have the checkstyle project installed in the repository, which is pretty annoying because if a make a slight change in the file I need to install it again in the repo. I know Maven is supposed to work this way, but is there a way to configure the root pom to resolve the dependency to the checkstyle project at compile time and not get it from the repo? I tried using maven options "--also-make" and "-pl" but I couldn't get it working. Also I know I can tell checkfile to look for the checkstyle file using the file:/// protocol (thats how I'm doing it now) but I would rather find an alternative way. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7530730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error while implementing KMLViewer in my project I have included the class KMLParser.m of Apple's KML Viewer in my project.The problem that I have is that when I try to build the project i get two errors like these: _CLLocationCoordinate2DMake,referenced from: _strToCoords in KMLParser.o _CLLocationCoordinate2DisValid, referenced from: _strToCoords in KMLParser.m I don't have any idea why this error occurs, because i have left the files KMLParser.m and KMLParser.h intact, I haven't made any change to them.When I build KML Viewer, everything is fine. Please,illuminate me. A: I am also working on implementing KMLViewer in my project. Turns out that accidentally linking with the incorrect target will cause the same errors. For XCode 4.x, under the list of Targets, it could be that there are multiple targets, such as MyApp and MyAppTests. Select the correct target (e.g., MyApp), then add the framework(s). A: You need to add the Core Location framework to your project (an #import alone is not enough). For Xcode 3.x, right-click on the project file and go to Add - Existing Frameworks. For Xcode 4.x, see How to "add existing frameworks" in Xcode 4?.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a cookie outside of a web-browser (E.g., With VBScript) A very random request - and trust me, I wish I didn't have to do it either. Essentially, a customers users are using a website that plays up with some other technology we roll out. We've exhausted all other routes in getting things to work properly, so I'm now in workaround / bodge territory. I've found an option on the website which does make things work. However, it's undesirable (And needless convoluted unfortunately) for us to direct the users to configure this themselves. Therefore, what I'd like / need to do is to set a cookie on computer logon. All the cookie contains is "0:-" which just disables the feature we need to disable. Again, I realise this is highly undesirable but assuming I can find a way out of this, then I'll be out of the woods. Ideally in VBScript, but really anything that is invisible to the users is good. Just for context, this is a Server 2008 R2 domain with Vista and Windows 7 Clients running IE8 and IE9. That is the scope for work and all I need to get working! I'm happy to hear alternative suggestions, but the end result is that we want to automatically disable this websites feature for our users. Any help gratefully received. Edit: I've tagged C# as I'm reasonably familiar with that too (From a SysAdmin PoV) Thanks, Dan A: Well, I think I may have cracked it in C#. Here are my code extracts: [DllImport("ieframe.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool IESetProtectedModeCookie(string url, string name, string data, int flags); public static bool SetWinINETCookieString() { IESetProtectedModeCookie("http://url.co.uk", "name", "data=blah; expires = Sat,01-Jan-2012 00:00:00 GMT; path=/", 0x10); IESetProtectedModeCookie("http://url.co.uk", "name", "data=blah; expires = Sat,01-Jan-2012 00:00:00 GMT; path=/", 0); return true; } It seems to have to set the cookie twice (With two different flags) in order to get consistent behaviour regardless of whether the website has been visited before or not. Added the following lines to catch non-protected mode, too. This appears to cover all bases and works on IE9 and IE8: [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool InternetSetCookie(string url, string name, string data); InternetSetCookie("http://url.co.uk", "Name", "data=blah; expires = Sat,01-Jan-2012 00:00:00 GMT; path=/"); A: [Update: Since my initial reply was completely rubbish...] * *Generally speaking, cookies are plain text. *IE cookies are built like that [You probably want to read this, too - since you need FILETIME values to build your own cookie]. *Then, on Win7, you'll find cookies stored in %userprofile%\AppData\Roaming\Microsoft\Windows\Cookies\Low With these building blocks, you now should be able to build a solution that fits your needs. [And another update: You should take also take a look at the interaction of IE's index.dat - a cookie (file) registry - and the cookie itself. Maybe you need to a) register your cookie in index.dat manually, or - if this doesn't work - b) delete index.dat after you created the cookie file (IE will rebuild it then when the browser starts the next time).] A: You cannnot disable the features if no cookie one found. So when a user opens the application and doesn't have a cookie yet you disable the functionality? Maybe make a different logon url for those users that sends some control variable or accesses a different url as opposed to the normal users. You could direct them to this url by a link on their desktop for example?
{ "language": "en", "url": "https://stackoverflow.com/questions/7530734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding functions to GUI in Matlab I used simpletab.m from MatlabCentral to make simple tabs in GUI Matlab, now I wanted to add another function so that the result of the added function is displayed when I press the GUI tab buttons. For example I want to add a function to every tab, when I press "tab 1" that function output (in this case a graph) is displayed. Update 1 THANKS FOR YOUR PROMPT REPLY. It worked good, but what if I don't want to the "Tab 1 function" to appear when I press the Tab button..straight away I want my graphs to be properly listed when I press tab 1 button. Update 2 I have written the modified function that you told me but still I get the tab name 'Tab 1 function' when I press the tab 1 button. Moreover I want two sub tabs to appear straight under the tab 1 button when I press the tab 1 button..one sub tab will display data on one graph for all sensors and one tab will display data on individual graphs. Do I have to write two separate functions and two separate subcall functions for each sub tab? I hope you have understood what I am trying to say. I'm really running out of time..:(..feeling lost A: Simply add your function to the appropriate callback (see end of file): % --- Executes on button press in tab1button. function tab1button_Callback(hObject, eventdata, handles) figure(); plot(1:10); % --- Executes on button press in tab2button. function tab2button_Callback(hObject, eventdata, handles) disp('Button from Tab 2 was pressed') figure(); plot(11:20); % --- Executes on button press in tab3button. function tab3button_Callback(hObject, eventdata, handles) figure(); plot(11:20); Now, if you press tab2, you'll see the message 'Button from Tab 2 was pressed' AND a new figure will open with a line going from 11:20. All you have to do now is to customize your plotting in the according callback function. EDIT: I've modified 'tab1button_Callback' so that only the plotting function will be executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Devexpress - AspxCallbackPanel controls have no values after postback I am having some issues with some DevExpress controls which are sitting inside an AspxCallbackPanel. At the point of clicking the "Submit" button, everything has a value (Text boxes, combos etc) - once I check the server side code I find that everything inside my AspxCallbackPanel has lost it's value (string.empty and null), but everything outside of the AspxCallbackPanel has retained it's value. Some wierdness with the panel I am sure - but totally has me stumped. Any ideas? The callback panel is refreshed from a bit of javascript attached to button click events - and doesn't affect many of the values which have been cleared. A: You need to use "if (!IsCallback)" in the page load to avoid the controls being altered if there is any code in the page load event so that the code is not fired in the event of a callback. Also, to ensure it's not the fault of the panel, comment out any code that is writing to the potentially cleared controls and test it. Make sure it's in more of a read-only mode to try and isolate the issue. Perhaps even create a test project with just a callbackpanel and a few simple controls and do some testing on how it works in its simplest form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# add event handler literal code block Is it possible to add a literal code block as an event handler in C#? Something like: Timer t = new Timer(1000); t.Elapsed += new ElapsedEventHandler({ Console.WriteLine("Tick"); }); You can do this in PowerShell, so I thought there might be some way to do this in C# too. A: t.Elapsed += delegate(object sender, ElapsedEventArgs args) { Console.WriteLine["Tick"]; }); Or, you could also use lambda syntax: t.Elapsed += (sender, args) => { Console.WriteLine["Tick"]; }; A: You can use a lambda expression (C# 3.0 and higher): t.Elapsed += (sender, args) => Console.WriteLine("Tick"); or an anonymous method (C# 2.0 and higher): // If you don't need the parameter values t.Elapsed += delegate { Console.WriteLine("Tick"); }; // If you do need the parameter values t.Elapsed += delegate(Object sender, ElapsedEventArgs args) { Console.WriteLine("Tick from {0}", sender); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7530743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what does kernel do behind the scene I would like to know the exact sequence of steps that the OS does, when I type simple command like "ls -l" in any directory. What actually happens behind the scene ? I would like to know what kernel does behind the scene while executing even a simple command like this. A: You could look at an strace strace ls -l
{ "language": "en", "url": "https://stackoverflow.com/questions/7530745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RegEx Replacement in JavaScript I have a piece of code which replaces tokens in a string. I have the replacement values stored in an array. Essentially, I would like to analyse the string and replace it by array key. For example, I want to replace any instance of [my_forename] with replacements['my_forname']. The keys in the array are identical to whatever is between the squared brackets in the string. A more comprehensive view: replacements['my_forename'] = 'Ben'; replacements['my_surname'] = 'Major'; replacements['my_verbose_name'] = 'Ben Major'; // The following is the input string: // 'My name is [my_forename] [my_surname], or [my_verbose_name].'; // And it should output: // 'My name is Ben Major, or Ben Major.'; If anyone can offer a RegEx that will handle the replacement, I would be grateful. It is possible that there will be more than one instance of the same token, but I have handled that using the following replaceAll function: String.prototype.replaceAll = function(needle, replacement) { return this.replace(new RegExp(needle, 'g'), replacement); } This causes a max stack limit though, because creating a RegExp object from anything containing [] causes issues. Any help would be gratefully received! A: function tmpl(s, o) { return s.replace(/\[(.+?)\]/g, function (_, k) { return o[k] }) } Here's a demo. A: Why not use sprintf() or vsprintf()? Check this page for reference: http://www.diveintojavascript.com/projects/javascript-sprintf Rather than replace tokens, you have placeholders in a string that are replaced automatically with values, or in the case of vsprintf(), values straight from an array. A: I always use the following site to build Regex: http://gskinner.com/RegExr/
{ "language": "en", "url": "https://stackoverflow.com/questions/7530748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GXT: How enable paginator? I have working proxy: proxy = new RpcProxy<List<EmpDTO>>() { @Override protected void load(Object loadConfig, final AsyncCallback<List<EmpDTO>> callback) { EmpDTO empDTO = new EmpDTO(); empService.findByExample(empDTO, new AsyncCallback<List<EmpDTO>>() { @Override public void onFailure(Throwable ex) { callback.onFailure(ex); } @Override public void onSuccess(List<EmpDTO> result) { callback.onSuccess(result); } }); } }; BeanModelReader reader = new BeanModelReader(); loader = new BaseListLoader(proxy, reader); store = new ListStore(loader); How to integrate pagination? A: Here is an example that should answer your question, http://www.sencha.com/examples/explorer.html#paging Click the "source" tab at the bottom.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where do I put classes on CLASSPATH? I complied Ref.java into ref.class and put it in the directory as specified below. I'm having a devil of a time figuring out how to use CLASSPATH. If anyone can point out my (probably stupid) error, I would be most happy. I have a class "Ref.java" as below: package utility.myapp; public class Ref { static public void print(String s) { // do something here } } My CLASSPATH includes: C:\Eclipse\classes I stored the class as file: C:\Eclipse\classes\utility\myapp\Ref.class From my main project I import as: import utility.myapp.* in file "Main.java" below: package com.reftest; import android.app.Activity; import android.os.Bundle; import utility.myapp.*; public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } Eclipse says: The import utility cannot be resolved I have tried every variation on this theme I could think of, but still no joy. Any help appreciated. BTW - I didn't omit or simplify anything: I tried to build this actual and majorly trivial project just to get the structure right. A: This all sounds terribly wrong to me. C:\Eclipse\classes is simply wrong. You should create a new project, and the place where your .class files end up ought to be relative to your project root. You should be able to right click on your Eclipse project and set up directories where JAR files live, etc. Eclipse ought to tell you a default place where it'll put .class files when you compile your .java; make sure it's relative to your project root. You'd better not have an environment variable CLASSPATH. That's the wrong way to do it. A: You need to make sure that your compiled class files are on the CLASSPATH. Try putting Ref.class into C:\Eclipse\classes\utility\myapp\ A: Thanks to all who provided input. As a service to the community, I provide a consolidation of all I learned below. There are two cases where a CLASSPATH is used. 1. During the build/debug cycle (inside Eclipse) 2. Running the app standalone (outside Eclipse). For #2 above, the environment variable CLASSPATH is consulted. It is a semicolon-delimited list of directories as well-documented everywhere. Setting it does not interfere with Eclipse - it is ignored. For #1, the classpath is stored in file ".classpath" in the root of your project in the workspace. To add an external directory for class search, add a line of the format: <classpathentry kind="lib" path="yourclasspath"/> My .classpath entry looks like this <classpathentry kind="lib" path="C:/Eclipse/classes"/> This can also be set in the Eclipse GUI by right-clicking on the project, selecting Properties->Java Build Path. Then select Add External Class Folder and enter the directory where you want to store your classes. Hope this is useful to others. -John
{ "language": "en", "url": "https://stackoverflow.com/questions/7530751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keep running a SQL procedure while browsing elsewhere in the application I am facing a technical issue on a web-app development : Here is the goal : By clicking on a button, the user launches a SQL/Oracle procedure that takes about 5 to 10 minutes to come to an end successfully. The procedure is composed of 4 steps : * *deleting users ... *deleting data ... *copying users ... *copying datas ... While the procedure is running, the user can't launch a second one, but any other thing can be done (browsing elsewhere in the application, even shutting-down the browser). In every situation, the procedure completes in the background. Here is the technical challenge for me : After clicking, if any user access or stay on the launching page, I want the user to see the monitoring of the execution progressing (the 4 steps). Thus, I've got to think about some kind of a refresh of the page when the user stays on it. Technologies of the web-app : * *Java/Java EE, Struts, Spring, Oracle SQL9i *NO AJAX Do you have any suggestion on how to make it work ? Thanks. A: The simplest possible approach would be to have your application submit a job using the DBMS_JOB package that ran the four steps in a separate session. You could either use the DBMS_APPLICATION_INFO package to instrument your code so that the front end can report on the current status or you could write to a separate log table and query that log table from the front-end. You could prevent a second job from being submitted either by having the job acquire a user-defined lock using the DBMS_LOCK package (which would be more robust) or by having the front-end check to see if there was a job already submitted in the DBA_JOBS table. Your front-end could then just automatically refresh the page and display the current status.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add OpenGL libraries to software package I have developed a scientific code package (for collisional/gravitational N-body simulations). It does not require any libraries to run. People can download it and simply type make to compile it. I want to keep it that simple. I added OpenGL as an option to visualize the simulation in real time. It looks really great. However, some people don't have an OpenGL/GLUT library installed on their machine. What is the easiest way to allow those users to use my code without having to install external libraries manually. I have the feeling that if I write a sentence like "Please install OpenGL/GLUT." in the manual, it will put off many people. Can I just add freeglut to my source package? Is that a good idea, or do you have any other suggestions? A: OpenGL is not really a library, despite the name. I suggest reading the L of OpenGL as "Layer". OpenGL comes as part of the GPUs drivers. In that case the dynamic library installed on the system provides an API to the drivers, but next to no internal functionality. So there it makes no sense shipping an OpenGL "library" with your program. You just make it dependent on opengl32.dll/libGL.so/OpenGLFramework. If use of OpenGL is optional, there is the possibility to load the API access library dynamically, but this is quite a mess. A: OpenGL is normally shipped with graphics card drivers so provided the end users have correct drivers they will have the libs installed already. But it will depend on what platform they are running. Windows includes an OpenGL implementation out of the box since Windows 95. I believe its a software rending fallback (although newer ones might be DirectX wrappers) and it's a fairly old OpenGL version (1.1) since it predates their own attempt to dominate the market via Direct3D. Of course most newer features won't work well in software since they are things like shaders that require specialized hardware. It will really depend on how graphics intensive your program is. Mac OS has official support or OpenGL since OS9 (various OpenGL versions depending on the OS version), OSX 10.7 has OpenGL 3.2 but it seems 1.1->2.1 is likely depending on what hardware/OSX version). Most modern desktop Linux implementations will have some OpenGL support, possibly via the proprietary official ATI/nVidia/Intel drivers. There are also some opensource drivers like Nouveau . Unfortunately there are also many platforms with broken implementations, no freesofware implementations (some distro/endusers refuse to use closed components), or no acceleration. For example the Intel GMA500 chipset is currently fairly broken. If you still want to include a fallback try looking at Mesa. It is an opensource cross platform software rendering OpenGL implementation. It is possible that you might be able to include that. It supports OpenGL versions 2.1 and they are working on 3.0+ with some extensions already available. Things like shaders will be slow (there is a project called LLVMpipe that might offer improvements but it's fairly experiential and it's only going to be able to do so much). There's also the ANGLE project which is an OpenGL ES 2.0 DirectX 9.0 wrapper. I believe it's from Google with an intent to support Chrome/Chromium's WebGL on Windows. But it is of course OpenGL ES now the full OpenGL and will only help you with Windows. Chances are your best option is to just disable the OpenGL simulation option unless they have the libs installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is this control possible in windows application(Winforms) please check the image below I would like to know if this kind of control is possible in windows application(Winforms). I tried grid-control but couldn't achieve this. Basically Col Name is populated from database. Detail Column is not populated from DB,it's column to receive inputs(from text-box & text area) Detail column is must contain multiple line regarding to it's adjacent column(ie. Col Name). as shown in figure above. Here in the Detail column four sub row are present.but i would like to increase the sub row as per user input say if 6 inputs are to be inputted,2 additional sub row should be generated dynamically. Basically in a grid view, new row input can be added dynamically. i want something similar like that but in a different context as explained above. Please let me know if this kinda of control is possible?? if so please help me out. A: It's called a DataRepeater control, which is not part of the normal visual studio controls. It's in the PowerPack. See: DataRepeater Class To Download: Microsoft Visual Basic Power Packs 3.0 A: Very Simple. Create a user control for one set (for e.g. ColumnName-A, 4-TextBoxes and 4-TextAreas). Use it for three times.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the index of the values of one vector in another? I would guess this is a duplicate, but I can't find that so here goes... I'd like to return the index of second in first: first = c( "a" , "c" , "b" ) second = c( "c" , "b" , "a" ) result = c( 2 , 3 , 1 ) I guarantee that first and second have unique values, and the same values between the two. A: Getting indexes of values is what match() is for. first = c( "a" , "c" , "b" ) second = c( "c" , "b" , "a" ) match(second, first) [1] 2 3 1 A: I was solving related problem, selecting the elements of a vector based on a pattern. Lets say we have vector 'a' and we would like to find the occurrences of vector 'b'. Can be used in filtering data tables by a multiply search patterns. a=c(1, 1, 27, 9, 0, 9, 6, 5, 7) b=c(1, 9) match(a, b) [1] 1 1 NA 2 NA 2 NA NA NA So match() it is not really useful here. Applying binary operator %in% is more convenient: a %in% b [1] TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE FALSE a[a %in% b] [1] 1 1 9 9 Actually from the match() help %in% is just a wrap around match() function: "%in%" <- function(x, table) match(x, table, nomatch = 0) > 0 A: here is another not efficient solution with which and sapply: sapply(second, function(x) which(first==x)[1]) for every element of the second returns the first index found in first. if no match found NA is returned for that element
{ "language": "en", "url": "https://stackoverflow.com/questions/7530765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Sencha touch vertical scroll content in a horizontal carousel I want to have a horizontal carousel where the content of each panel is able to scroll vertically. Currently the content is chopped off at the bottom of the screen and I am unable to scroll down the content. I use this code for the carousel: Pages.Portfolio = new Ext.Carousel({ title: 'Portfolio' }); And add new items to it by: Pages.Portfolio.add( new Ext.Panel({ html: response.responseText }) ); Layout to fixed does not seem to solve the problem. Anyone an idea how to solve this problem? A: try this: Pages.Portfolio = new Ext.Carousel({ title: 'Portfolio', fullscreen:true }); and Pages.Portfolio.add( new Ext.Panel({ html: response.responseText, scroll:'vertical' }) ); A: try it! Ext.application({ name:'ehmm', launch:function(){ Ext.create('Ext.Carousel', { fullscreen: true, defaults: { styleHtmlContent: true }, scroll:'vertical', items: [ { html : 'Item 1', style: 'background-color: #5E99CC' }, { html : 'Item 2', style: 'background-color: #759E60' }, { html : 'Item 3', style:'background-color:red;' }, { html:'contohnya', style:'background-color:pink;' }, ] }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7530770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Switch to another running process Can someone please explain how I would go about switching to another running program via C#? For example if i create a new application with a button event - i would like to use the button to say call an open application like internet explorer or word. I know how to start applications but not quite sure how to call them when they are already running. This is what have been working on so far: if (System.Diagnostics.Process.GetProcessesByName("ExternalApplication").Length >= 1) { foreach (Process ObjProcess in System.Diagnostics.Process.GetProcessesByName("ExternalApplication")) { ActivateApplication(ObjProcess.Id); Interaction.AppActivate(ObjProcess.Id); SendKeys.SendWait("~"); } } A: I had to solve a similar problem, and I had to do some pInvoking to get it done. See code below. delegate bool EnumWindowsProc(IntPtr hWnd, int lParam); public static class WindowEnumerator { [DllImport("user32.dll", SetLastError = true)] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("USER32.DLL")] private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam); [DllImport("USER32.DLL")] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("USER32.DLL")] private static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("USER32.DLL")] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("USER32.DLL")] private static extern IntPtr GetShellWindow(); public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID) { IntPtr hShellWindow = GetShellWindow(); Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>(); EnumWindows(delegate(IntPtr hWnd, int lParam) { if (hWnd == hShellWindow) return true; if (!IsWindowVisible(hWnd)) return true; int length = GetWindowTextLength(hWnd); if (length == 0) return true; uint windowPid; GetWindowThreadProcessId(hWnd, out windowPid); if (windowPid != processID) return true; StringBuilder stringBuilder = new StringBuilder(length); GetWindowText(hWnd, stringBuilder, length + 1); dictWindows.Add(hWnd, stringBuilder.ToString()); return true; }, 0); return dictWindows; } } ... [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); ... Process yourProcess = ???; Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id); IntPtr mainWindowHandle = IntPtr.Zero; foreach (KeyValuePair<IntPtr, string> pair in windows) { if (pair.Value.ToUpperInvariant() == "Main Window Title") { mainWindowHandle = pair.Key; break; } } if (mainWindowHandle != IntPtr.Zero) { if (IsIconic(mainWindowHandle)) { ShowWindow(mainWindowHandle, 9); } SetForegroundWindow(mainWindowHandle); } A: below code worked for me using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; namespace SingleInstanceWindow { static class Program { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var me = Process.GetCurrentProcess(); var arrProcesses = Process.GetProcessesByName(me.ProcessName); if (arrProcesses.Length > 1) { SetForegroundWindow(arrProcesses[0].MainWindowHandle); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } above code doesn't work if window is minimized code: [DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); usage: SwitchToThisWindow(arrProcesses[0].MainWindowHandle, true); A: I am using the following but i dont think have defined the process name correctly on line 31. 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.Diagnostics; using System.Runtime.InteropServices; namespace test_winform_app { public partial class Form2 : Form { public Form2() { InitializeComponent(); } [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); private void button1_Click(object sender, EventArgs e) { Process yourProcess = Process.GetProcessesByName("notepad"); Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id); IntPtr mainWindowHandle = IntPtr.Zero; foreach (KeyValuePair<IntPtr, string> pair in windows) { if (pair.Value.ToUpperInvariant() == "Main Window Title") { mainWindowHandle = pair.Key; break; } } if (mainWindowHandle != IntPtr.Zero) { if (IsIconic(mainWindowHandle)) { ShowWindow(mainWindowHandle, 9); } SetForegroundWindow(mainWindowHandle); } } delegate bool EnumWindowsProc(IntPtr hWnd, int lParam); public static class WindowEnumerator { [DllImport("user32.dll", SetLastError = true)] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("USER32.DLL")] private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam); [DllImport("USER32.DLL")] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("USER32.DLL")] private static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("USER32.DLL")] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("USER32.DLL")] private static extern IntPtr GetShellWindow(); public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID) { IntPtr hShellWindow = GetShellWindow(); Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>(); EnumWindows(delegate(IntPtr hWnd, int lParam) { if (hWnd == hShellWindow) return true; if (!IsWindowVisible(hWnd)) return true; int length = GetWindowTextLength(hWnd); if (length == 0) return true; uint windowPid; GetWindowThreadProcessId(hWnd, out windowPid); if (windowPid != processID) return true; StringBuilder stringBuilder = new StringBuilder(length); GetWindowText(hWnd, stringBuilder, length + 1); dictWindows.Add(hWnd, stringBuilder.ToString()); return true; }, 0); return dictWindows; } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Border Radius / Overflow Problem in Chrome I have a site that uses a lot of border-radius for layout. The issue is compared to a working version (Firefox) in the screenshot below (also I did NOT design this awful thing). All the code follows the same format for border radius: border-top-left-radius: 25% 54%; border-bottom-left-radius: 19% 54%; The only thing I can see is the grey boxes ("main_area") border-radius is actually controlled by a parent, so maybe the grey background is overflowing. Here is the link Also note the same error occurs in Opera. I am not using prefixes, just the above css. The layout is also fine in IE9. Thanks A: Percentage dimensions are calculated based on the default font-size, so use a reset stylesheet or add browser specific font-sizes to the selectors which use percentages, such as: div#container > #main > #main_area > .content > .holder { font-size: 10px; } /* Firefox reset */ @-moz-document url-prefix() { div#container > #main > #main_area > .content > .holder { font-size: inherit; } } /* IE9 reset */ @media all and (monochrome: 0) { div#container > #main > #main_area > .content > .holder { font-size: inherit; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7530780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: image magick center on canvas and color I am running a script to crop an image,, set the correct dpi and resize it slightly smaller.. this first command works perfectly convert tmp_image/o_1316646627.jpg -strip -crop 1676.404494382x1200+0+0 -quality 100 -units pixelsperinch -density 239.48635634029 -resample 239.48635634029x239.48635634029 -resize 1556.6613162119x tmp_image/p_1316646627.jpg this second command places the image on a sligntly larger canvas, and is supposed to change the background color and center the image on the canvas. it creates the canvas correctly, but the image is placed in the top left corner and the background color is black convert tmp_image/p_1316646627.jpg -background '#460712' -gravity center -extent 1676.404494382x1200 tmp_image/p_1316646627.jpg ive been stuck here for hours.. any ideas would be greatly appreciated! thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7530782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Something unclear with operator delete I am new to C++ and I have something unclear: #include <iostream> using namespace std; double* foo(void) { double* b = new double[100]; return b; } int main() { double* a = foo(); delete [] a; return 0; } Is there something wrong with this code? I mean whether the way I use operator delete is right? I assign the pointer b which points to the allocated memory in foo function to pointer a outside foo, can I release memory by means of delete[]a in main? I don't have any idea how does the compiler calculate the number of bytes to release when execute delete[]. Thanks A: The code is correct (though not usually part of any well-written modern C++ program). Dynamically allocated arrays are stored with hidden information about their size so that delete[] p knows how many elements to delete. If you're curious about the details, you can rig up a little test class and take advantage of the member allocation operators: struct ArrayMe { static void * operator new[](size_t n) throw(std::bad_alloc) { void * p = ::operator new[](n); std::cout << "new[]ed " << n << " bytes at " << p << "." << std::endl; return p; } static void operator delete[](void * p, std::size_t n) throw() { std::cout << "delete[]ing " << n << " bytes at " << p << "." << std::endl; ::operator delete[](p); } double q; }; Now say: std::cout << "sizeof(ArrayMe) = " << sizeof(ArrayMe) << std::endl; ArrayMe * const a = new ArrayMe[10]; delete[] a; A: Call delete [] to delete C-style arrays allocated with operator new []. Delete [] will know how many bytes were allocated by operator new[]. Call delete to delete objects allocated with operator new (no brackets). Never, ever mix them! I.e. never call delete [] on something allocated with operator new, and never call delete on something allocated with operator new [].
{ "language": "en", "url": "https://stackoverflow.com/questions/7530784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it possible to add button on FormLayout I need to display button in the middle of the dialog that uses FormLayout However when I'm adding button to such dialog, it added near standard dialog buttons (OK/Cancel etc.). I do not need to add buton there, I do need to add button in the body of the dialog? I guess my problem is similar to this one http://www.coderanch.com/t/496347/GWT/GXT-Button-near-text-field A: AdapterField should be used to adapt Button from http://tutorialsjava.com/2009/08/22/no-border-around-form-in-ext-gwt/ : FormLayout in Ext-Gwt (GXT) When using a FormLayout/FormPanel you need to be aware of some specific properties for a Form Layout. * *On a FormLayout only widgets that extend Field are displayed. If you want to display a widget that does not extend Field, you first have to wrap it in AdapterField. *When I used a FormPanel it had a border around the form even when setting .setFrame(false) and .setBorders(false) . This is not a bug, you also need to set .setBodyBorder(false) to see no borders around a form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: has_many :through and getting associated items This is a follow-up to this question has_many :through usage, simple, beginner question Basically, I'd like to have a function in my Invoice class that gets all the LineItems but the following is not working: so: > @i=Invoice.find(1) # good > @i.products # good works well > @i.products.line_items # not working, undefined method line_items based upon associations in previous question, should this be working? I think it should if I access products directly: > @p=Product.find(1) # good > @p.line_items # also good How can I get back all the line items based upon this model? thx A: Assuming you have following models: class Invoice has_many :line_items has_many :products, :through => :line_items end class LineItems belongs_to :invoice belongs_to :product end class Product has_many :line_items has_many :invoices, :through => :line_items end You can do the following: @i=Invoice.find(1) # good @i.products # good works well @i.line_items # all the line_items associated with the invoice. A: @i.products returns a collection of Products. You need to collect all the line items: @i.products.collect(&:line_items)
{ "language": "en", "url": "https://stackoverflow.com/questions/7530800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Should validation be on business models or view models? I am trying to figure out where to put validation in my N-Tier Asp.net MVC application On the one hand I feel like validation should be in the business layer with the business objects themselves. This means that when validation rules change I only have to change it in one spot (e.g. right now user display names can be anything but now I want the names to be a minimum of 5 characters and no symbols). This makes it simple to understand where to find validation rules and makes it easier to keep validation rules consistent across processes. On the other hand I also feel like validation should be on the view models because sometimes you need validation for a specific process data that will not be needed on the business object. For example, when a user changes their password you want them to enter their password in the form twice so they don't make a mistake in their password and fail login. Your User business object doesn't need two password fields because it doesn't make sense, as you only need two passwords when changing your current password (or creating a new account). Therefore, it makes sense to me to put validation on view models to make sure process specific validations are run. The downside to this is now when validation rules change you have the potential of MANY spots that this needs to be updated (you have to change the rules on every view model that deals with users). The 3rd option is to split the validation between your business objects and view models where it makes sense. The problem with this is I can see it getting hard to realize if a validation rule is triggering due to the view model validation failure or business object validation failure. A: You have made some good considerations. Personally, I have previously validated in the view and controller layers, but have recently come to realize that this may not be the best approach. While it does make sense to do it in the controller, it can indeed become a repetitive task as you also mentioned. I would vouch for view and business layer. Some things are just good to catch in the view layer before sending a request to the server. For example, it would make sense to check if there are field validation errors before uploading a 100 MB large file only to tell the user that they made a typo. Obviously, view validation should always be backed up by server side validation. The concept referred to as "fat models" puts as much validation within the business layer as possible, which has many advantages; * *Your code will be reusable as it will be wrapped inside every business object, rather than for specific controller actions for instance. Should you need to update a business rule, then you only need to update the related models and not every controller which uses those models (you also made a good point about this yourself) *Your code will be more portable as it will be easier to switch to a different framework for instance if you do not have a business layer that relies on controllers to enforce business logic *Controllers will be easier to understand, hence why the flow in your application will be easier to follow, and new developers will probably find it easier to get up to speed *Writing a validation rule once or twice is less error phone than writing it repeatedly *Debugging and testing is likely to be easier I hope this helps. A: I recommend your third option. Split the validation as appropriate. Using your example of typing the new password twice (to ensure it is typed correctly), it does not make sense to send both passwords along to the business model (especially if this is a distributed/web application) to check that they are the same, when your view model can easily compare the two. Other constraints, like username length, or required fields left blank, can easily be checked in the view when entered, and provide immediate feedback to the user. Some things can't be validated in the view model, and need to be passed to the business model to be checked. One example is uniqueness of username. One thing to be considered is that (especially in web development), is that client side validation is easier to bypass, so even if it is implemented, a malicious/mischevious user could still manage to submit bad data. To cover this case, it is best to check any critical validation constraints server-side. Of course, this leads back to the not-so-DRY problem that led you to this question... EDIT: The primary reason i suggest for any separation is to provide the user with immediate feedback so that they can fix their submission as needed before it is actually submitted to the server for processing. If your dilemma is between one server-side location and another to place your validation code, then I say it is a matter of personal preference, but I recommend NOT separating it. In this case, it would be best to keep it all in one cohesive place, so that you know exactly where to go for updates and bug fixes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use "Passive Mode" with FtpWebRequest We have a process in place to upload a file nightly to a partner FTP site. They now require a passive connection and our uploads now fail. Is it possible for the .NET 4 FtpWebRequest to implement a passive connection instead of an active one? If so, can someone please provide an example? A: Set the UsePassive property to true on the FtpWebRequest. A: Tried setting the UsePassive property on FtpWebRequest? See MSDN. A: Just to add something to an old post - The FtpWebRequest.UsePassive property is True by default, so all requests should use passive already.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Do you uniquely id all of your models? I'm using backbone.js. I get an event from the server that needs to update a particular instance of a model in a collection of models. Should I set the id attribute to achieve this, how do I target a model by its id? Thanks A: yes, every model should have a unique id. when you get the update from the server, find the model via the get method on the collection. as a very simple example: function receiveSomeUpdate(id, data){ var model = myCollection.get(id); model.set(data); } do you have a specific scenario you're trying to support, tho? the details may change the answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7530817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JNI crashes when calling CallVoidMethod I'm trying to call a java method from native C code in an Android Application. This sounds quite simple with the usage of JNI, but my code always crashes when finally calling the method itself. Here's my code: Native C Code: JNIEXPORT void JNICALL Java_com_path_to_my_package_renderStuff(JNIEnv* env, jobject jobj){ //... jclass clazz = env->FindClass("com/path/to/the/class"); jmethodID showCar = env->GetMethodID(clazz,"showCar","()V" ); env->CallVoidMethod(jobj,showCar); //If I comment this out, it won't crash //... } Java Code: public void showCar(){ doSomething() } doSomething() isn't even reached, I can set a breakpoint there, which will never be hit. And as said above, as soon as I comment out the CallVoidMethod call, it won't crash but obviously not call showCar() either. Any hints? A: In my case I was calling a Kotlin function. And to call a kotlin function you need to write @JvmStatic before function name in kotlin. Kotlin code @JvmStatic fun ReceiveDataFromCpp(data: ShortArray) { Log.d("Kotlin array Return -----> ", "arr: " + data .contentToString() ); } Cpp code JNIEnv * g_env; g_env = getEnv(); jmethodID jmethodId = g_env->GetStaticMethodID(clientClass, "ReceiveDataFromCpp", "([S)V"); if (jmethodId == NULL) { return; } jshortArray dataArray = nullptr; dataArray = g_env->NewShortArray(480); g_env->SetShortArrayRegion(dataArray, 0, 480, mData); g_env->CallStaticVoidMethod(clientRecorderClass, jmethodId, dataArray); A: 4 ideas to provide you: ... jclass clazz = env->FindClass("com/path/to/the/class"); Can you confirm the name is not "com/path/to/the/MyClass" where the classname is uppercase 1st character and obviously the name "class" is a reserved word. There is a slight discrepency between the use of the JNI C symbol name "Java_com_path_to_my_package_renderStuff" and the FindClass() lookup on "com/path/to/the/class"in your example. But since your stackoverflow is not a about UnsatisfiedLinkageError I can only guess your example provided is not consistent with itself. Using my example I would expect the JNI C symbol name to be "Java_com_path_to_the_MyClass_renderStuff" and the FindClass() lookup on "com/path/to/the/MyClass". The use of uppercase 1st letter of class and lowercase 1st letter of method name might be important for linkage purposes. ... Are you sure the "jobj" being passed is the same type as the "com/path/to/the/class" you are looking up ? Maybe in your Java code you can wrap your native with: public void renderStuff() { if((this instanceof com.path.to.the.MyClass) == false) throw new RuntimeException("Unexpected class expected: com.path.to.the.MyClass"); renderStuff_internal(); } private native void renderStuff_internal(); Which will ensure that matter in Java code without causing a JVM crash. You would also need to adjust your C symbol name to append the "_1internal" onto the end making "Java_com_path_to_the_MyClass_renderStuff_1internal" (the extra "1" character is intended) ... Maybe try belt and braces exception checking in between each statement you list about: if(env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } This will pickup things like security violations when trying to do reflection when it might not be allowed. ... jclass cls = env->GetObjectClass(jobj); // instead of FindClass jmethodID mid = env->GetMethodID(cls, "showCar", "()V"); if(!mid) return; // whoops method does not exist env->CallVoidMethod(jobj, mid); Another idea to remove the FindClass() call. This would work with any class that GetMethodID worked on, kind of like dyhamic typing / late-binding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Why is my SSIS text logfile formatted in this way? I have configured logging in my SSIS package by using the Text File log provider. The connection string for the provider is the name of a file in my local file system. The package completes and writes data to the log, but it is formatted in a way that I did not expect: If I open it in Notepad++, it looks worse: Is this just the way it is? Or is there some configuration setting in SSIS that I'm overlooking? Notepad and Notepad++ aren't having any issues displaying other files. Thanks in advance. A: Ok, I think I figured this is out. The is ssis 2008. I think if you put some characters in the log file first and then run the ssis package you have this unicode output, space between characters problem. If you are having this problem, delete everything in your log file, save the file in notepad as "ansi" then run your package again and this time your text log file will look normal. I think if you mix ansi and unicode characters, notepad gets confused.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing on IIS6 With Decimal In Route I have a route in my MVC3 project that works perfectly fine locally when run through the debugger and through IIS7. However, our servers are IIS6 and when I move my application out I am getting a "The page cannot be found" error. My guess is it has to do with the decimal in the route.. So I have tried implementing a RouteHandler which seems to be getting called but is not working correctly because the value isn't overwritten in the route? Anyway, here is my route: var route = context.MapRoute( "Management_version", "Management/Version/{versionNumber}/{action}", new { area = "Management", controller = "Version", action = "View" }, new[] { "FRSDashboard.Web.Areas.Management.Controllers" } ); route.RouteHandler = new HyphenatedRouteHandler(); and my route handler: public class HyphenatedRouteHandler : MvcRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { var versionNumberContext = requestContext.RouteData.Values["versionNumber"]; requestContext.RouteData.DataTokens["versionNumber"] = versionNumberContext.ToString().Replace(".", "-"); return base.GetHttpHandler(requestContext); } } Basically, I am trying to replace the decimal point with a hyphen to work around the issue. Any suggestions would be greatly appreicated. A: So it turns out that I also needed to set a Wildcard application map for "aspnet_isapi.dll" in addition to the application extension wildcard. Both wildcards must have the "verify that file exists" option unchecked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a toggle button with 3 options...? I want to create a toggle button with 3 options. I don't want to use radio button or check box. I want to create like this.... How to create this...? Thanks in advance...! A: Create the artwork for the left/middle/right buttons and create three separate buttons next to each other in a horizontal linear layout Then in code get all three references to the buttons. When a button is clicked set a boolean e.g _button1Clicked = true (or use an array?) and set the image to a downstate, check the other buttons, set their images to upstate and reset their booleans to false! Easy!
{ "language": "en", "url": "https://stackoverflow.com/questions/7530836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how do I give a link name to an html table row? I have a table with each row explaining something (an input command). In another place, I am saying from this state with that input command, you go that other state. What I want to do is to link the that input command to the appropriate row of the table. Imagine something like this: ...link to row number <a href="#row2">2</a>... <table ...> <tr> <td>command</td> <td>description</td> <tr> <tr> <a name="row1"></a> <td>A</td> <td>input A</td> <tr> <tr> <a name="row2"></a> <td>B</td> <td>input B</td> <tr> </table> As you can see, I tried putting a <a name="row2"></a> in the <tr> block but that didn't work (it brings me to the top of the table) Is what I want to do possible? A: You do one of two things: 1) Set the id attribute of the <tr>. <tr id="row2">...</tr> OR 2) put the <a> element inside the <td> element. If you put any element inside a <table> but not inside a <th> or <td>, it'll get rendered before the entire table (try it with any element, the browser does its best to correct the invalid HTML) A: Although non-intuitive for me, but I put the <a name="row2"></a> inside the first <td> block and it worked! A: <tr> <td><a name="row2"></a></td> <td>B</td> <td>input B</td> <tr> A: You could do a "dummy" anchor row: <table ...> <tr> <td>command</td> <td>description</td> <tr> <tr> <td colspan="2" style="height: 1px;"><a name="row1"></a></td> <tr> <tr> <td>A</td> <td>input A</td> <tr> <tr> <td colspan="2" style="height: 1px;"><a name="row2"></a></td> <tr> <tr> <td>B</td> <td>input B</td> <tr> </table> If you have styling on your table (borders, background, etc) this might be visible, but you could always style these rows like separators or camouflage them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: MVC3 jQuery.validate not working when submitting form I've been working in MVC3 using the built in jquery validation. Client validation did appear to be working when tabbing through the fields except when I submitted the actual form. Below are my include scripts: <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> I managed to fix this by reverting the jquery version to jquery-1.4.4.min.js so I'm just wondering: Isn't jquery backwards compatible? Also - why would the validation actually work but just fail when an input submits? Could this be a bug in the new version of jQuery? A: At first it seemed to me like jQuery 1.6 would break compatibility. It turned out it was just a little trickier to get unobtrusive validation working than I thought. This is a good tutorial that'll get you a working example: http://www.asp.net/mvc/tutorials/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript You can then switch to jquery 1.6.2 and see that it's still working. For me, what was missing from my nearly identical view was Html.BeginForm. Once I added that, everything started working. A: I think it is a bug and there is no solution for this. A: Is the form posting? If not you may have a validation rule that's being violated but you may not see the error message if you don't have Html.ValidationSummary or Html.ValidationMessageFor enabled. **EDIT: I tried with the latest version of jQuery (1.6.4) and with 1.6.2 with this code without any issues. controller code public class TestViewModel { [Required] public string textTest { get; set; } [Required] public int intTest { get; set; } } public class HomeController : Controller { public ActionResult Index() { return View(new TestViewModel()); } [HttpPost] public ActionResult Index(TestViewModel model) { if (ModelState.IsValid) { return Redirect("http://www.yahoo.com"); } return View(model); } } markup @model MvcApplication39.Controllers.TestViewModel @{ ViewBag.Title = "Index"; } <h2>ViewBag.Title</h2> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>TestViewModel</legend> <div class="editor-label"> @Html.LabelFor(model => model.textTest) </div> <div class="editor-field"> @Html.EditorFor(model => model.textTest) @Html.ValidationMessageFor(model => model.textTest) </div> <div class="editor-label"> @Html.LabelFor(model => model.intTest) </div> <div class="editor-field"> @Html.EditorFor(model => model.intTest) @Html.ValidationMessageFor(model => model.intTest) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7530838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get a list of persistent objects stored in database I should insert a list of objects in a database using a workflow for each object, the inserting process could take several time and waiting for some external input so I have to save persistent state in db, and it works correctly. Now I need to show pending objects in my user interface, how can I retrieve variables of stored data?? Thank you, Marco A: See How to: Deserialize Instance Data Properties
{ "language": "en", "url": "https://stackoverflow.com/questions/7530839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find out where a thread has been blocked In java, i have 2 threads started at the same time. However, i noticed the thread 2 is being blocked but i do not know where. Is there a way in java to find out where a thread has been blocked/waiting? thank u. A: You could use jstack to get the stack traces for all threads. That'll tell you where exactly in the code your thread is blocked. To get a more detailed picture of what's happening inside your process, you could use VisualVM. A: You can use the isAlive() method to verify if the thread is still active or not. Here's a sample code to check all the threads in your memory: public class ThreadStates{ public static void main(String[] args){ Thread t = new Thread(); Thread.State e = t.getState(); Thread.State[] ts = e.values(); for(int i = 0; i < ts.length; i++){ System.out.println(ts[i]); } } } A: You can use jstack to find where a thread is blocked. However if you want to check a thread within the same program you can using thread.getStackTrace()
{ "language": "en", "url": "https://stackoverflow.com/questions/7530843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Aptana 3.0 JS Code Assist not working with namespace that begins with karma We are using Aptana 3.0 to develop our JS application. We are using the dojo toolkit. In the toolkit there is a utility to generate docs, called docscripts. It generates an xml file. We have been able to get Aptana to recognize the file, but something is odd. Our namespace which we are using, "karma", does not seem to "work". When we change the namespace to "foo" or any other string, even "karma2", the code assist works. Is there something against "karma" being used as a namespace? All of the dojo, dijit, and dojox classes are provided thru code assist as expected. Thoughts? A: There is certainly nothing directly blocking that name. If you can file a bug with the XML file you are using, that would be great.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing Strategy pattern with Reflection I'm trying to implement the strategy pattern using reflection, i.e. instantiate a new Concrete Strategy object using it's class name. I want to have a configurable file with the class name in it. We have a database manager that will make changes available during run-time. Here's what I have so far: StrategyInterface intrf = null; try { String className = (String)table.get(someId); intrf = (StrategyInterface) Class.forName(className).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } return intrf; I have a Class ConcreteStrategy which implements StrategyInterface. I have a test running in whcih table.get(someID) returns the String "ConcreteStrategy". My problem is that ClassNotFoundEception is thrown. Why is this happening, and how I could get ConcreteStrategy to be instantiated given a class name? I don't want to use an if-else block because number of concrete strategy objects will increase with time and development. EDIT: I fixed it the following way, String className = (String)table.get(custId); className = TrackingLimiter.class.getPackage().getName() + "." + className; limiter = (TrackingLimiter) Class.forName(className).newInstance(); A: Are you sure you don't forget package name and class ConcreteStrategy is available for classloader? A: Assuming that classname you provide to forName() is fully qualified and correct. ClassNotFoundException means exactly that. So you need to ensure that the ConcreteStrategy.class (or a jar file containing it) is in class path. In case new classes are made available really dynamically, i.e. you know that when YOUR program started, ConcreteStrategy.class did not exist, but a few hours/days later someone implemented it and put the fully qualified class name in the DB table, then along with the class name you also need the resource name (path of ConcreteStrategy.class (or a jar file containing it)). Once you have both, you can use URLClassLoader to create an instance of ConcreteStrategy from ConcreteStrategy.class file or jar_with_ConcreteStrategy_class.jar. URLClassLoader example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Application installation problem on iPhone with developer account I am installing application on iPhone using developer certificates. When i install application it do not go ahead after default page. and if i exit the application and then i open application from iPhone then it works fine but the problem is that i have to use debugging and it is only possible when when app is running from XCode. so please help me. this is a big issue for me A: Its solution is to update the xcode. when i updated my xcode my app start working good with iPhone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7530860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cant get jQuery ajax POST to work If I set type to 'GET' in the code below it works, but I cant get it to work with 'POST'. ajaxPostTest.html... <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url: "ajaxPostTest_server.php", data: {"fruit1": "rasp", "fruit2": "bramble"}, type: 'POST', dataType: 'json', contentType: "application/json; charset=utf-8", success: function(data){ $("#returned").append(data.fruit1); }, error: function(jqXHR, textStatus, errorThrown){ alert("error") ; } }); }); </script> </head> <body> <div id="returned">returned: </div> </body> </html> ajaxPostTest_server.php... <?php echo json_encode($_REQUEST); ?> The expected output on the browser is... returned: rasp I'm actually attempting to interact with an ASP.NET web server and I want to confirm my ajax is working (and I understand ajax properly) first - hence this simplified code. Firebug debugging... Response Headersview source Date Fri, 23 Sep 2011 14:57:37 GMT Server Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 X-Powered-By PHP/5.3.1 Keep-Alive timeout=5, max=99 Connection Keep-Alive Transfer-Encoding chunked Content-Type text/html Request Headersview source Host localhost User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18 Accept application/json, text/javascript, */*; q=0.01 Accept-Language en-gb,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 115 Connection keep-alive Content-Type application/json; charset=utf-8 X-Requested-With XMLHttpRequest Referer http://localhost/My_Webs/temp/ajaxPostText1.html Content-Length 26 Cookie PHPSESSID=mgvoacnluh3kad5pakafrd5kd1 All I get in the 'response' tab is... {"PHPSESSID":"mgvoacnluh3kad5pakafrd5kd1"} I.e. I cant find where the data I send to the server is going to. A: Because your sending your data as "application/json", PHP does not populate $_POST / $_REQUEST. You need to send the request as "application/x-www-form-urlencoded" (you can leave out the "Content-Type" parameter because this is the default type). A: use $_POST instead of $_REQUEST
{ "language": "en", "url": "https://stackoverflow.com/questions/7530862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: moving back to the position of a div is not correct jquery I have a div and then move the div by using drag function of Jquery. after dropping the item, I made it such a way that if I click on the item, it will be back to the old position. I saved the initial position of the div: offset() and then set it again. I check on the debug data, the initial and the position after moving back are the same but the div is not located at the same as it was. where could be the problem? Thanks in advance A: Probabley the div is in a diffrent DOM location meaning its parent has changed unless it is position:absolute, try to save the parent element and the use the append method to append it the starting parent,
{ "language": "en", "url": "https://stackoverflow.com/questions/7530863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }