text
stringlengths
8
267k
meta
dict
Q: Get width from the center of an element to the edge of viewport Essentially the idea is to make Element-B and Element-C to cover the area horizontally starting from center of Element-A and ending at the edge of viewport. So, I guess i want to get the distance value from the center of Element-A to the edge of viewport Additional notes: * *Element-A doesnt have static position or size. *Element-B and Element-C verticalposition or height is irrelevant. I was thinking something like this: * *Calculate width of Element-A and divide it by two ( Or just get half the width if theres a way. ) *Get the distance from the edge of Element-A to the edge of Viewport *Add up these calculated values. ( Of course unless theres way to get that this width straight up ) I was trying to look for a way to do list item 2. but couldnt find a way to do that.. and that more or less screws up my idea.. I have no starting point except the basic set-up for the images http://jsfiddle.net/nsEth/ Any ideas? A: Something like this? http://jsfiddle.net/nsEth/1/ var a = $('#Element-A'), b = $('#Element-B'), c = $('#Element-C'), aw; $(window).resize(function() { b.width( aw = a.offset().left + a.width()/2 ); c.width( $(window).width() - aw).css('left', aw); }).resize();
{ "language": "en", "url": "https://stackoverflow.com/questions/7548827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how i can change the master page at runtime I want from my website to change its master page dynamically every postback . i wrote this code protected void Page_PreInit(object sender, EventArgs e) { if (IsPostBack) MasterPageFile = (MapPath(this.MasterPageFile) == MapPath("MasterPage1.master"))?"MasterPage2.master":"MasterPage1.master"; } but when the form posted back the first time ,the master page changed , but the second time didn't !! . I think this because when the page reload ,the main (the first one )master page back !! how i can solve this problem ?? A: The problem is that ASP.NET parses page every time (that is for every request) from scratch, and sets master page to the one that is declared in the .aspx markup. Page's previous state is loaded after the initialization phase, when the master page is already set. That means that if page declaration includes something like <%@ Page ... MasterPageFile="MasterPage1.master" ... %> then on the PreInit event MasterPageFile property will always be set to "MasterPage1.master", no matter what was the previous master page. With your current code everything works like that. On first loading of the page master is MasterPage1.master, so it is changed to MasterPage2.master, everything works as expected. However on the second load master is still MasterPage1.master (as it is declared in .aspx), so it is changed again to MasterPage2.master, and it looks like nothing has changed. To work this around please look into this answer. Since ViewState is not available on PreInit, session is used there to decide on what master page should be loaded. You might want to extend this code by storing in session previous master page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Menu loading off-screen in Internet Explorer I am in the process of writing a website for my sister, and I'm running into a little trouble with cross-browser compatibility. Namely, the menu I am using is loading half off-screen in Internet Explorer, while it looks fine in Chrome. I've tried messing with the alignments, and I've sort of hit a wall and can't figure out how to make it load in the same spot regardless of what browser you are using. You'll see what I mean when you look at the site: www.claireharbage.com. the menu above the gallery should be aligned with the left side of the gallery. Thanks in advance for your help with this, it's greatly appreciated. Here is the section of code that includes the menu: <table width="900" height="704" bgcolor="#222222"> <tr> <td width="76" height="39" valign="baseline">&nbsp;</td> <td width="629" valign="baseline"></td> <p class="heading"><a href="http://www.claireharbage.com">CLAIRE HARBAGE</a></p> <td width="50" valign="baseline"> <div id="menu"> <ul class="menu"> <li><a href="#" class="parent"><span>Work</span></a> <div><ul> <li><a href="/Something.html"><span>Something to Hold On To</span></a></li> <li><a href="/graf_town.html"><span>Graf-Town</span></a></li> <li><a href="/Leaving.html"><span>Leaving Neverland</span></a></li> <li><a href="/punk.html"><span>Pittsburgh Punk</span></a></li> <li><a href="/5.html"><span>A Place to Stay</span></a></li> </ul></div> </li> <li><a href=""><span>About</span></a> </li> <li><a href="#"><span>Wedding</span></a></li> <li class="last"><a href="http://claireharbage.blogspot.com/"><span>Blog</span></a></li> </ul> and here is the CSS code that affects the position of the menu: #menu { position:relative; z-index:100; height:16px; } div#menu { top:40px; left:-630px; width:450px; } #menu .menu { position:relative; top: -1px; } #menu * { list-style:none; border:0; padding:0; margin:0; } #menu a { display:block; padding:8px 14px 8px 14px; white-space:nowrap; } #menu li { float:left; background:#fff; } A: To start, personally I don't really recommend the use of tables for controlling site layout. Instead I prefer CSS. You also use a lot of inline styling on the table which makes it difficult to debug. I can't pinpoint the troublesome CSS for some reason, but it looks like the content in your table is center aligned. You then use a negative left css property to pull the menu content back to the edge of the table. I don't actually see in your site layout where tables are necessary at all. It is very basic. So something like: <div id="header" /> <div id="menu" /> <div id="slideshow /> <div id="footer" /> Should get you the content layout you want without all the hassle of the table. A: I'm surprised your menu is even showing at all in any browser when you're pushing it to the left by -630px. If you're looking to position your menu div just use margins as top/left positioning, if not properly set relative to a container, will push things relative to the body of your page. So, change this: div#menu { top:40px; left:-630px; width:450px; } To something like this: div#menu { margin:40px 0 0 20px; //position as you see fit width:450px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ODBC: Data source name not found and no default driver specified I'm trying to make a connection to a sql server on a local lan but I keep getting the following error, sqlTest: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source) at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source) at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source) at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source) at net.sourceforge.squirrel_sql.fw.sql.SQLDriverManager.getConnection(SQLDriverManager.java:133) at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand.execute(OpenConnectionCommand.java:97) at net.sourceforge.squirrel_sql.client.mainframe.action.ConnectToAliasCommand$SheetHandler.run(ConnectToAliasCommand.java:281) at net.sourceforge.squirrel_sql.client.mainframe.action.ConnectToAliasCommand$SheetHandler.performOK(ConnectToAliasCommand.java:238) at net.sourceforge.squirrel_sql.client.gui.db.ConnectionInternalFrame.connect(ConnectionInternalFrame.java:311) at net.sourceforge.squirrel_sql.client.gui.db.ConnectionInternalFrame.access$300(ConnectionInternalFrame.java:56) at net.sourceforge.squirrel_sql.client.gui.db.ConnectionInternalFrame$MyOkClosePanelListener.okPressed(ConnectionInternalFrame.java:461) at net.sourceforge.squirrel_sql.client.gui.OkClosePanel.fireButtonPressed(OkClosePanel.java:148) at net.sourceforge.squirrel_sql.client.gui.OkClosePanel.access$100(OkClosePanel.java:33) at net.sourceforge.squirrel_sql.client.gui.OkClosePanel$1.actionPerformed(OkClosePanel.java:174) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$000(Unknown Source) at java.awt.EventQueue$1.run(Unknown Source) at java.awt.EventQueue$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source) at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$2.run(Unknown Source) at java.awt.EventQueue$2.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at net.sourceforge.squirrel_sql.client.Main$1.dispatchEvent(Main.java:93) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) I'm running SQuirreL SQL Client Version 3.2.1 as administrator on Windows 7 x64 using JRE 1.6 u27. I try to connect to SQL server 5.1 on ubuntu 10.04. My connection settings, Not sure if it's the url or what. Also I tried to connect while wireshark was monitoring and it didn't pick up any packets. A: Do you want to use ODBC-JDBC bridge? I think you should use native JDBC drivers. If you use MySQL then connect string to your database may be like: jdbc:mysql://10.11.12.1:3306/mybase
{ "language": "en", "url": "https://stackoverflow.com/questions/7548831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS CSS opacity + visibility transition Take a look at the following test in a desktop browser (JSFiddle): a { background: gray; display: block; margin: 100px; padding: 100px; } a span { opacity: 0; -webkit-transition: 0.5s; visibility: hidden; } a:hover span { opacity: 1; -webkit-transition: 0.5s; visibility: visible; } <a href="#">a <span>span</span></a> You hover over the anchor element and the span element fades in like it should. Now take a look via an iOS device. Result: it does nothing. Facts: * *If the transition property is absent, it works. *If either the opacity or visibility property is absent, it works. *There is no webkitTransitionEnd event being fired for the opacity or visibility property. Is there any workaround? A: Only opacity on transition sucks. Since that on iPhone you need to tap in order to focus an element this is how I've fixed my problem: .mydiv { visibility:hidden; opacity: 0; transition: all 1s ease-out; -webkit-transition: all 1s ease-out; -moz-transition: all 1s ease-out; -o-transition: all 1s ease-out; } .mydiv:hover { visibility:visible; opacity: 1; } .mydiv:active { -webkit-transition: opacity 1s ease-out; } I've added the opacity transition to :active. This way it works with all transition animation (consider that you want to apply animation to height or something else) on Chrome, Firefox and iPhone (on tap). Thanks to Grezzo and Michael Martin-Smucker for spotting out about the opacity transition. (copy/paste of my response from CSS animation visibility: visible; works on Chrome and Safari, but not on iOS) A: With some minor modifications to the transition property, this can work on iOS. On :hover, limit the transition to only the opacity property, like so: a:hover span { opacity:1; -webkit-transition: opacity 0.5s; transition: opacity 0.5s; visibility:visible; }​ While visibility is an animatable property, there seems to be a bug in the iOS implementation. When you try to transition visibility, it seems like the entire transition doesn't happen. If you simply limit your transition to opacity, things work as expected. To be clear: Leave the visibility property in your CSS, just don't try to transition it if you want things to work in Mobile Safari. For reference, here's your updated fiddle, which I tested on an iPad: a { background: gray; display: block; margin: 100px; padding: 100px; } a span { opacity: 0; -webkit-transition: 0.5s; visibility: hidden; } a:hover span { opacity: 1; -webkit-transition: opacity 0.5s; visibility: visible; } <a href="#">a <span>span</span></a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What are the most important things to do to make a safe PHP/MySQL website? This is a bit of an opinion question, but overall, what safety precautions would be ideal for a PHP-based website using a MySQL database? This site would include registration and login, and need to protect users' personal information. A: You have to know main things: * *Users are stupid like monkeys. They click anything anytime. *HTTPS *Good programing skills *HASH + salt *PHP bugs *All possible ways of hacking website over PHP and MySQL. Fight fire with fire. A: This is a very huge question, and there are dozens of books written solely to answer this question, but here are some important things: 1- Never EVER trust user input data ($_GET and $_POST). Always sanitize everything before printing/saving to the database. 2- Avoid concatenating parameters directly on the SQL. Always use $db->bindParam() or some other similar function. 3- Never store plain text passwords. Use a hashing algorithm always. And to be safe, use a Salt as well. 4- Always expect the worst scenario to happen. Because it will. 5- Read something about XSS, CSRF. And make sure you guard your app against those. 6- Get experienced =) A: Golden rule of secure web development: Filter Input, Escape Output Here is a nice article that sums it up actually: http://shiflett.org/blog/2005/feb/more-on-filtering-input-and-escaping-output A: The main problems are: SQL injection XSS when outputting data Here are some links: How does the SQL injection from the "Bobby Tables" XKCD comic work? How to prevent SQL injection with dynamic tablenames? htmlentities() vs. htmlspecialchars() Salting my hashes with PHP and MySQL How should I ethically approach user password storage for later plaintext retrieval? Read them I hope you will follow the advice in the many answers. A: A lot of answers came in while I was typing this. I guess they type faster. :-p All are great answers and I don't know how you'll choose the best one, but most are about the same. * *NEVER STORE PASSWORDS IN PLAIN TEXT. Use SHA-2 algorithms with a salt. Store the hash and the salt. *Never trust user input. Sanitize everything that goes into the database before you store it AND anytime you use it. *Use prepared statements. Look into PDO. *Use HTTPS when possible. These are just a few things to bare in mind. Most important of all Study you @ss off. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Round a double to 3 significant figures Does anybody know how I can round a double value to 3 significant figures like the examples on this website http://www.purplemath.com/modules/rounding2.htm Note: significant figures are not the same as decimal places A: double d = ...; BigDecimal bd = new BigDecimal(d); bd = bd.round(new MathContext(3)); double rounded = bd.doubleValue(); A: If you want to do it by hand: import java.lang.Math; public class SigDig { public static void main(String[] args) { System.out.println(" -123.456 rounded up to 2 sig figures is " + sigDigRounder(-123.456, 2, 1)); System.out.println(" -0.03394 rounded down to 3 sig figures is " + sigDigRounder(-0.03394, 3, -1)); System.out.println(" 474 rounded up to 2 sig figures is " + sigDigRounder(474, 2, 1)); System.out.println("3004001 rounded down to 4 sig figures is " + sigDigRounder(3004001, 4, -1)); } public static double sigDigRounder(double value, int nSigDig, int dir) { double intermediate = value/Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1)); if(dir > 0) intermediate = Math.ceil(intermediate); else if (dir< 0) intermediate = Math.floor(intermediate); else intermediate = Math.round(intermediate); double result = intermediate * Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1)); return(result); } } The above method rounds a double to a desired number of significant figures, handles negative numbers, and can be explicitly told to round up or down A: There's nothing wrong with the answer given by Sean Owen (https://stackoverflow.com/a/7548871/274677). However depending on your use case you might want to arrive at a String representation. In that case, IMO it is best to convert while still in BigDecimal space using: bd.toPlainString(); ... if that's your use case then you might be frustrated that the code adapted from Owen's answer will produce the following: d = 0.99, significantDigits = 3 ==> 0.99 ... instead of the strictly more accurate 0.990. If such things are important in your use case then I suggest the following adaptation to Owen's answer ; you can obviously also return the BigDecimal itself instead of calling toPlainString() — I just provide it this way for completeness. public static String setSignificanDigits(double value, int significantDigits) { if (significantDigits < 0) throw new IllegalArgumentException(); // this is more precise than simply doing "new BigDecimal(value);" BigDecimal bd = new BigDecimal(value, MathContext.DECIMAL64); bd = bd.round(new MathContext(significantDigits, RoundingMode.HALF_UP)); final int precision = bd.precision(); if (precision < significantDigits) bd = bd.setScale(bd.scale() + (significantDigits-precision)); return bd.toPlainString(); } A: public String toSignificantFiguresString(BigDecimal bd, int significantFigures ){ String test = String.format("%."+significantFigures+"G", bd); if (test.contains("E+")){ test = String.format(Locale.US, "%.0f", Double.valueOf(String.format("%."+significantFigures+"G", bd))); } return test; } A: double d=3.142568; System.out.printf("Answer : %.3f", d); A: how I can round a double value to 3 significant figures You can't. Doubles are representing in binary. They do not have decimal places to be rounded to. The only way you can get a specific number of decimal places is to convert it to a decimal radix and leave it there. The moment you convert it back to double you have lost the decimal precision again. For all the fans, here and elsewhere, of converting to other radixes and back, or multiplying and dividing by powers of ten, please display the resulting double value % 0.001 or whatever the required precision dictates, and explain the result. EDIT: Specifically, the proponents of those techniques need to explain the 92% failure rate of the following code: public class RoundingCounterExample { static float roundOff(float x, int position) { float a = x; double temp = Math.pow(10.0, position); a *= temp; a = Math.round(a); return (a / (float)temp); } public static void main(String[] args) { float a = roundOff(0.0009434f,3); System.out.println("a="+a+" (a % .0001)="+(a % 0.001)); int count = 0, errors = 0; for (double x = 0.0; x < 1; x += 0.0001) { count++; double d = x; int scale = 2; double factor = Math.pow(10, scale); d = Math.round(d * factor) / factor; if ((d % 0.01) != 0.0) { System.out.println(d + " " + (d % 0.01)); errors++; } } System.out.println(count + " trials " + errors + " errors"); } } A: I usually don't round the number itself but round the String representation of the number when I need to display it because usually it's the display that matters, that needs the rounding (although this may not be true in situations, and perhaps yours, but you need to elaborate on this if so). This way, my number retains its accuracy, but it's display is simplified and easier to read. To do this, one can use a DecimalFormat object, say initialzed with a "0.000" String (new DecimalFormat("0.000")), or use String.format("%.3f", myDouble), or several other ways. For example: // yeah, I know this is just Math.PI. double myDouble = 3.141592653589793; DecimalFormat myFormat = new DecimalFormat("0.000"); String myDoubleString = myFormat.format(myDouble); System.out.println("My number is: " + myDoubleString); // or you can use printf which works like String.format: System.out.printf("My number is: %.3f%n", myDouble);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Character encoding cross-reference I have just migrated a database containing Latin American place names from MS Access to my MySQL. In the process, every instance of á has been changed to ‡. Here is my question: Does there exist some sort of reference for looking up which character encoding has been translated to which other? For example, a place where I can enter a character and see how it would be misrepresented after a variety of erroneous encoding translations (e.g. ASCII to ISO 8859-1, ISO 8859-1 to UTF-8, etc.)? A: Not that I'm aware of, but if you have a list of possible encodings, you can write a simple program like: for x in ENCODINGS: for y in ENCODINGS: try: if 'á'.encode(x) == '‡'.encode(y): print(x, '→', y) except UnicodeError: pass Doing that, it appears in your case that the original encoding is one of: * *mac_arabic *mac_centeuro *mac_croatian *mac_farsi *mac_iceland *mac_latin2 *mac_roman *mac_romanian *mac_turkish and the misinterpreted encoding is one of: * *cp1250 *cp1251 *cp1252 *cp1253 *cp1254 *cp1255 *cp1256 *cp1257 *cp1258 *palmos If you live in a "Western" locale, then mac_roman → cp1252 is the most likely possibility.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 2 jcarousels influencing one another I have 2 jcarousels: First that acts like thumbnails limited to 4 Second that shows big image, only one when clicked on the thumbnail the second jcarousel scrolls to the appropriate image, now that i manage to do. the second jcarousel has prev/next buttons, when clicked it will scroll to the prev/next image, now the problem is that now the first (thumbnail) jcarousel should scroll to the appropriate thumbnail. EDIT: How to send position of second jcarousel to the first one and change postion (on first jC)? When next/prev button is pressed on the second carousel, how to manipulate the first carousel? See the demo http://www.mediafire.com/file/jj684d8uu6ycpa9/jcarousel_test.zip (press on the thumbnailas, it will change the position of the second carousel, i need now to change the position of the selected thumbnail (thumbnail carousel) when the prev/next is clicked on second carousel) JS: function mycarousel_initCallback(carousel) { jQuery('.jcarousel-control a').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('rel'))); jQuery('.jcarousel-control a').removeClass('active'); jQuery(this).addClass('active'); jQuery('.jcarousel-item').removeClass('highliht'); jQuery('.jcarousel-item-'+jQuery(this).attr('rel')).addClass('highliht'); return false; }); jQuery('#mycarousel li.jcarousel-item').click(function() { jQuery('.jcarousel-item').removeClass('highliht'); jQuery(this).addClass('highliht'); jQuery('.jcarousel-control a').removeClass('active'); jQuery('.jcarousel-control a#cnt-'+jQuery(this).attr('jcarouselindex')).addClass('active'); carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('jcarouselindex'))); return false; }); jQuery('.jcarousel-skin-showcase div.jcarousel-next').click(function(){ //chage position on mycarousel }); } jQuery(document).ready(function() { //set border on first thumbnail & control jQuery('.jcarousel-control a#cnt-1').addClass('active'); jQuery('#mycarousel li:first').addClass('highliht'); jQuery('#mycarousel').jcarousel({ scroll: 4, initCallback: mycarousel_initCallback }); jQuery('#showcasecarousel').jcarousel({ scroll: 1, initCallback: mycarousel_initCallback }); }); The HTML and CSS (demo): http://www.mediafire.com/file/jj684d8uu6ycpa9/jcarousel_test.zip A: You have attached same cllback functions for both carousel. Specify the callback function for each carousel in document.ready() as different functions as: mycarousel_initCallback and mycarousel_initCallbackanother jQuery(document).ready(function() { jQuery('.jcarousel-control a#cnt-1').addClass('active'); jQuery('#mycarousel li:first').addClass('highliht'); jQuery('#mycarousel').jcarousel({ scroll: 4, initCallback: mycarousel_initCallback }); jQuery('#showcasecarousel').jcarousel({ scroll: 1, initCallback: mycarousel_initCallbackanother }); }); extract the code for the #showcasecarousel from mycarousel_initCallback and put it as a separate function: as function mycarousel_initCallbackanother(carousel) { jQuery('.jcarousel-skin-showcase div.jcarousel-next').click(function(){ //chage position on mycarousel }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding on RotateTransform Angle in DataTemplate not taking effect In my WPF UserControl I have this resource, please observe the comments in the Xml sample. <UserControl.Resources> <DataTemplate x:Key="AxisXLabelTemplate"> <ContentPresenter Content="{Binding Path=Content}"> <ContentPresenter.LayoutTransform> <RotateTransform Angle="{Binding XAxisLabelRotation, UpdateSourceTrigger=PropertyChanged}" /> <!-- This does not work --> <!-- <RotateTransform Angle="-90" /> This works --> </ContentPresenter.LayoutTransform> </ContentPresenter> </DataTemplate> </UserControl.Resources> In the code I have a dependency property defined as follows: class MyChart: INotifyPropertyChanged { public static readonly DependencyProperty XAxisLabelRotationProperty = DependencyProperty.Register("XAxisLabelRotation", typeof(RotateTransform), typeof(BarChart), new FrameworkPropertyMetadata((RotateTransform)new RotateTransform(-90.0))); public RotateTransform XAxisLabelRotation { get { return (RotateTransform)GetValue(XAxisLabelRotationProperty); } set { SetValue(XAxisLabelRotationProperty, value); } } ... } The AxisXLabelTemplate DataTemplate is assigned to an element farther below as follows: <chart:AxisLabel ElementTemplate="{StaticResource AxisXLabelTemplate}"/> The problem is that when I use the unbound value for Angle and hard-code it to -90, it works beautifully, and when I try with the bound value to XAxisLabelRotation it doesn't. Can anyone please help? A: I recreated similar setting as you and it did not work for me either. Curiously there are no binding errors. I did relativesource binding too and it didnt work. Although if I bind tooltip <ContentPresenter ToolTip="{Binding XAxisLabelRotation, RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}, UpdateSourceTrigger=PropertyChanged}" ..> shows the tooltip to me. So I changed the rotate transform, <RotateTransform Angle="{Binding XAxisLabelRotation, RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}, UpdateSourceTrigger=PropertyChanged}" ..> But still the transform did not work. Still no binding errors. Then I introduced a dummy converter ... public class AngleConverter : IValueConverter { public object Convert(...) { return value; } .... } <RotateTransform Angle="{Binding XAxisLabelRotation, RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource AngleConverter}}" ..> and it worked miraculously!!! Unexplanable world of WPF??? A: You need to bind the angle like this: <RotateTransform Angle="{Binding Path=FontSize, RelativeSource={RelativeSource TemplatedParent}}"/> Source A: Is the DataContext correct? If this rotation is part of the Content you bound to earlier you either need to change the DataContext or add that to the binding path of the rotation, i.e. make it {Binding Content.XAxisLabelRotation}. Do you know how to debug bindings? As you did not present any binding errors i would assume you do not, so if this is the case please read this article and make sure that you do provide the errors if you cannot debug a binding yourself in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails remote form loaded via Ajax after document ready is not submitting I have a remote form using form_tag and :remote => true that is loaded from a partial. When I load the form through its own view as normal, it works as intended. However, then I try loading the partial on another page through AJAX after document ready. When I try to submit this form, nothing happens. I've tried a regular submit button and calling form.submit(). Is there some javascript initialization to remote forms that Rails does that I have to duplicate? Or is there something else going on here? A: The only thing that I can think of off the top of my head is the CSRF token left out of the form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Problem with echo values from database I inserted on a row of database table values, now I want echo them with json_encode, but I have following error: PHP: $name_tour = $this->input->post('tour_name'); $query = $this->db->query("SELECT * FROM tour_foreign WHERE name LIKE '$name_tour' ORDER BY id desc"); $data = array(); foreach ($query->result() as $row) { $data_rp = json_decode($row->residence_p, true); $data[] = array( 'residence_p' => $data_rp, ); } echo json_encode($data); echo '<p>'; var_dump($data); Output above php code: [{"residence_p":null}] // This is output of json_encode($data) array(1) { [0]=> array(1) { ["residence_p"]=> NULL } } // This is output of var_dump($data) Data in database:(this data insert by json_encode) [{ "start_date": ["1111", "2222"], "end_date": ["1111", "2222"], "price_change": ["1111", "2222"] }, { "start_date": ["3333", "444"], "end_date": ["3333", "4444"], "price_change": ["3333", "4444"] }, { "start_date": ["5555", "6666"], "end_date": ["5555", "6666"], "price_change": ["5555", "6666"] },] What do i do? A: Why are you doing this? $data_rp = json_decode($row->residence_p, true); Did you really store json data in your database? I doubt it, but if you did DON'T! Doing that defeats the entire purpose of having a database with columns. A: You should remove the , before the last ], otherwise the data is invalid JSON which cannot be correctly parsed by json_decode().
{ "language": "en", "url": "https://stackoverflow.com/questions/7548870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the email and name from Azure ACS? I'm using the Azure ACS, and I've been looking for away to get the email and name from the SAML 2.0 response or something. But I dont see any options for it, I redirect the user to localhost:8000/acc/completesigninup/ There I have the XML from the FormCollection object, I see the Email and Name in the xml but I'm not sure how to get it. Is there a parser that's included in the Identity dll to get that info? A: Since you are mentioning of FormCollection I assume you are programming in windows with .Net. Then the easiest thing would be using WIF (http://msdn.microsoft.com/en-us/security/aa570351). This way you don't have to parse the token, validate it, set the User Identity, and then create a cookie representing the information from the token. WIF, once you install and configure it (its SDK comes with a Visual Studio extension to do this), will do these for you automatically. You can look at some samples using WIF with MVC. One sample is ACS with MVC3 which you can find at: http://msdn.microsoft.com/en-us/library/hh127794.aspx Once you do this in your controllers you can access to user's identity and get the claim values e.g.: ((IClaimsPrincipal)HttpContext.User).Identity.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.Email) Note that Windows Live IDP in ACS will NOT give out e-mail addresses of users as claims due to Windows Live privacy policy. A: Atacan is correct about everything but one detail: There appears to be a way to get the desired information from Windows Live, but it's different than the way used for Google, Facebook, and Yahoo accounts. The JavaScript Windows Live API includes support for getting information like the user's first name (link). I haven't tried this, so I don't know what else is required, but that may be what you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Identifying start and end XY vector of characters on image I'm trying to recollect some information about letters to start some kind of OCR with Neural Networks. I've yet to really join all the things together, however, the problem I'm having right now is how to differentiate characters and separate them. Something like http://pp19dd.com/tesseract-ocr-chopper/?i=ocrFTYzRJ (nothing fancy, just common fonts) I believe the better way is to make a big amount of for-loops to get top, lowest x and y considering each character and number have black pixels that join each other (although i is an exception). Is there any kind of library or algorithm that can aid me with this? I'm using Cimg for image processing. Is this really hard? A: It sounds like you are looking for a connected component labeler. The idea is to scan the image for groups of pixels that are connected to one another, and return a collection of objects (usually called "blobs") where each object contains a list of the pixels in that blob. I do not recommend trying to write your own. OpenCV has one built in that works very well and is based on F.Chang,C.-J.Chen,andC.-J.Lu, "A linear-time component-labeling algorithm using contour tracing technique," Computer Vision and Image Understanding, vol. 93, no. 2, pp. 206–220, 2004. There very well may be a better solution that is specifically geared to finding letters. A: Have you checked out the OpenCV project? Here is a tutorial for doing number OCR with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TextBox within DataTemplate, on GotFocus cannot assign SelectionStart? I have a logic with my textbox which says, on focus move the selection start to the last character, so that the editing person can just continue writing. This worked perfectly with this: private void TextBox_GotFocus(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox == null) return; textBox.SelectionStart = textBox.Text.Length; } and <Style TargetType="{x:Type TextBox}"> <EventSetter Event="GotFocus" Handler="TextBox_GotFocus"/> </Style> and <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <TextBox Name="SomeTextBox" Text="{Binding Path=Pressure, UpdateSourceTrigger=PropertyChanged}" Padding="2,0,0,0" /> <DataTemplate.Triggers> <Trigger SourceName="SomeTextBox" Property="IsVisible" Value="True"> <Setter TargetName="SomeTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=SomeTextBox}"/> </Trigger> </DataTemplate.Triggers> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> but when I moved this to: <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ContentControl Content="{Binding Path=Pressure, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ContentTemplate="{StaticResource DataGridTextBoxEdit}" /> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> and a reusable template: <DataTemplate x:Key="DataGridTextBoxEdit"> <TextBox Name="TextBox" Text="{Binding Content, RelativeSource={RelativeSource AncestorType=ContentControl}}" Padding="2,0,0,0" /> <DataTemplate.Triggers> <Trigger SourceName="TextBox" Property="IsVisible" Value="True"> <Setter TargetName="TextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=TextBox}"/> </Trigger> </DataTemplate.Triggers> </DataTemplate> it just stopped working. The GotFocus event fires off, however I simply cannot assign anything to SelectionStart, it just doesn't save it. Tried even hardcoding: private void TextBox_GotFocus(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox == null) return; textBox.SelectionStart = 5; } but didn't work. It's also worth to note that Text is empty, only DataContext is filled at this point, however as the SelectionStart is not taking anything (saving), it's no good to me. What am I doing wrong? Kind regards, Vladan A: At the point where the TextBox gets focus it does not have any text yet, this means the handler fires before the DataGrid assigns the value. One way to get arround this is to check for the first text change and then do the selection change, e.g. private void TextBox_GotFocus(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox == null) return; var desc = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox)); EventHandler handler = null; handler = new EventHandler((s, _) => { desc.RemoveValueChanged(textBox, handler); textBox.SelectionStart = textBox.Text.Length; }); desc.AddValueChanged(textBox, handler); } (This code may not be very clean, use at own risk)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Join results from multiple MySQL tables and output with PHP Using PHP, I'm trying to populate an HTML list with data from two different tables in a MySQL database. The structure for each table is as follows: Table: "students" +------------+------------+-----------+---------------+-------+ | student_id | first_name | last_name | city | state | +------------+------------+-----------+---------------+-------+ | 1 | Tobias | Funke | Newport Beach | CA | +------------+------------+-----------+---------------+-------+ | 2 | Bob | Loblaw | Laguna Beach | CA | +------------+------------+-----------+---------------+-------+ | 3 | Ann | Veal | Bland | CA | +------------+------------+-----------+---------------+-------+ Table: "students_current" +------------+------------+---------------+ | student_id | school_id | current_class | +------------+------------+---------------+ | 1 | umass | Sr | +------------+------------+---------------+ | 2 | ucla | Jr | +------------+------------+---------------+ | 3 | ucla | Fr | +------------+------------+---------------+ I'd like to populate the list with only with records that match a specific school_id. For example, if I want the list only to contain students whose school_id is "ucla", the resulting HTML would be as follows: <li> <span class="first_name">Bob</span> <span class="last_name">Loblaw</span> <span class="city">Laguna Beach</span> <span class="state">CA</span> <span class="current_class">Jr</span> </li> <li> <span class="first_name">Ann</span> <span class="last_name">Veal</span> <span class="city">Bland</span> <span class="state">CA</span> <span class="current_class">Fr</span> </li> Each <li> item would be tied to a specific student_id value from the database. How do I write the PHP that will select/join the appropriate records from the database? A: Using a LEFT JOIN: SELECT * FROM `students` s LEFT JOIN `students_current` sc ON s.`student_id` = sc.`student_id` WHERE `school_id` = 'ucla'
{ "language": "en", "url": "https://stackoverflow.com/questions/7548884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: inet_ntop provides different returns for the same ipv6 address on different platforms On my Mac, inet_ntop produces this IPv6 address for a certain 128-bit value: 2001::53aa:64c:422:2ece:a29c:9cf6.51391 On my FC15 Linux system, I get this IPv6 address presentation: 2001:0:53aa:64c:422:2ece:a29c:9cf6.51391 My understanding is that zeros between :: can be ignored, so I think that these are the same address. Are they the same address? If so, why do the different operating systems display it differently? Thanks. A: Yes, they are the same address. The :: means 'all zeroes', the other notation shows the zero.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Virtualenvwrapper.sh functions not available in bash shell I'm doing a new install of virtualenvwrapper, and for some reason after running virtualenvwrapper.sh it's functions aren't available. $ virtualenvwrapper.sh creating..... $ workon workon: command not found I know that it's running, aside from the successful creation of all the VE files, I've wrapped some of the function definitions in echo "please get here" statements and they all get hit. So: what? A: Oh I see, the correct thing to do is: $ source virtualenvwrapper.sh it was on my PATH, and getting run in a subshell, I guess.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I toy with this .py file? I'm learning Python just so I can tinker with the files from AIMA easily. I know Java and C++, but I find the AIMA code on the repositories to be too obfuscated. The Python code looks simpler and more elegant...yet, I don't know Python. I wanna import the functions in search.py. I tried creating a search2.py file like this: import search class Problem2(Problem): pass on the folder where search.py is and got: ~/aima/aima-python$ python search2.py Traceback (most recent call last): File "search2.py", line 3, in <module> class Problem2(Problem): NameError: name 'Problem' is not defined Why is this? A: When you import search, you define the name search, as a module created from executing search.py. If in there is a class called Problem, you access it as search.Problem: import search class Problem2(search.Problem): pass An alternative is to define Problem with this statement: from search import Problem which executes search.py, then defines Problem in your file as the name Problem from the newly-created search module. Note that in this form, the name search is not defined in your file. A: You have two options here: * *Instead of import search, write from search import Problem *Instead of class Problem2(Problem), write class Problem2(search.Problem) A: If class Problem is located in the search module, you have to import it either like that from search import Problem or use it like that: import search class Problem2(search.Problem): pass
{ "language": "en", "url": "https://stackoverflow.com/questions/7548895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I check in C++ whether std::cout is redirected to a file? I need my program to behave differently, depending on whether the output is to a terminal or to a file. How can I find this out from within C++? I assume there is no solution that works for all operating systems. For my purposes, it would be good to have one strategy which works under Windows and one which works under linux/unix. Thanks in advance. A: This will help under linux: How to tell if running in a linux console versus an ssh session? Yes it is a C call, but it can definitely be called from C++. GetStdHandle gives a similar starting point under windows:
{ "language": "en", "url": "https://stackoverflow.com/questions/7548896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: hg update --mq not working? I am using: Mercurial Distributed SCM (version 1.9.1), and I've done the following: D:\code\mqtest>hg init D:\code\mqtest>hg qinit -c D:\code\mqtest>echo NonQueue > first D:\code\mqtest>hg st ? first D:\code\mqtest>hg add first D:\code\mqtest>hg commit -m nonqueue D:\code\mqtest>hg log changeset: 0:2d4bac63616a tag: tip user: Tempos date: Mon Sep 26 00:52:49 2011 +0300 summary: nonqueue D:\code\mqtest>hg log --mq D:\code\mqtest>hg qnew a D:\code\mqtest>echo Queue0 > first D:\code\mqtest>hg st M first D:\code\mqtest>hg qref D:\code\mqtest>hg qcommit -m "queue 0" D:\code\mqtest>echo Queue1 > first D:\code\mqtest>hg qref D:\code\mqtest>hg qcommit -m "queue 1" D:\code\mqtest>echo Queue2 > first D:\code\mqtest>hg qref D:\code\mqtest>hg qcommit -m "queue 2" D:\code\mqtest>hg st D:\code\mqtest>hg log --mq changeset: 2:38d08315a300 tag: tip user: Tempos date: Mon Sep 26 00:53:46 2011 +0300 summary: queue 2 changeset: 1:bb8b7da2e728 user: Tempos date: Mon Sep 26 00:53:33 2011 +0300 summary: queue 1 changeset: 0:1ac551a65492 user: Tempos date: Mon Sep 26 00:53:22 2011 +0300 summary: queue 0 And I tried to switch back to a particular revision in the mq: D:\code\mqtest>hg up -r 0 --mq 1 files updated, 0 files merged, 0 files removed, 0 files unresolved D:\code\mqtest>cat first Queue2 Why am I not seeing the Queue0 content? A: When you update the patches inside .hg\patches with hg --mq update, then you're changing the mq patches behind mq's back. In other words: the patches themselves get the new content, but they are not re-applied automatically. So the workflow you want is to do: > hg qpop -a > hg --mq update -r X > hg qpush -a where you first remove all patches, update them to look like you want, and then re-apply them. Having hg --mq update do this for you would actually be an interesting idea, and I know that you're not the first one to be surprised about the lack of integration between the two commands. A: You should be using qpush and qpop when moving through patches in your queue. From the tutorial: The patch queue aspect is actually quite nice as well. You can, for example, work on two different layers of your application (something low-level and something built on top of that) in the same queue at the same time without breaking stuff. qpush and qpop will help you move up and down while keeping your changes separate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: It's possible to upload a movie via php sdk? How can i do it? i tried something like $facebook->api('/me/movies','POST',array('source'=>..)); but it didn't worked. A: see this howto: http://developers.facebook.com/blog/post/493/ A: Accessing /me/movies is a list of the movies that the user likes. Things that the user likes are not editable via the Facebook Graph API. If you are trying to upload a movie file, you would use /me/videos. A: Here's a proper solution. You need the access token from somewhere. In my case I get it into another moment. And I upload the video when the user is offline. require 'php-sdk/src/facebook.php'; . $facebook = new Facebook(array( 'appId' => 'xxxxxxxxxxxxxxxxxxxxxx', 'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx', )); $facebook->setAccessToken("myaccesstokenhere"); $facebook->setFileUploadSupport(true); $args = array('title' => 'The title of the video','description'=>'The description of the video'); $args['videoData'] = '@' . realpath($_SERVER['DOCUMENT_ROOT']."/uploads/video.mp4"); try { $data = $facebook->api('/me/videos', 'post', $args); } catch (FacebookApiException $e) { echo "result=ERROR&message=".$e->getMessage(); die(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating .JAR's contents from code I am making a game that needs to be updated. I have two JAR files: Update.Jar and Game.Jar Basically, I want to be able to modify Game.Jar without completely overwriting it. I want to: * *Open the Jar file as a Zip file from within code *Replace/add some resources *Repackage the Jar file. Is there an easy way or classes that can do this? If not, what would be the cleanest approach to doing this? A: A Java JAR file is a normal ZIP file. You can therefore open and modify it with code dealing with ZIPs. Here's a snippet which works (courtesy of David): import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class JarUpdater { public static void main(String[] args) { File[] contents = {new File("F:\\ResourceTest.txt"), new File("F:\\ResourceTest2.bmp")}; File jarFile = new File("F:\\RepackMe.jar"); try { updateZipFile(jarFile, contents); } catch (IOException e) { e.printStackTrace(); } } public static void updateZipFile(File zipFile, File[] files) throws IOException { // get a temp file File tempFile = File.createTempFile(zipFile.getName(), null); // delete it, otherwise you cannot rename your existing zip to it. tempFile.delete(); boolean renameOk=zipFile.renameTo(tempFile); if (!renameOk) { throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath()); } byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean notInFiles = true; for (File f : files) { if (f.getName().equals(name)) { notInFiles = false; break; } } if (notInFiles) { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } } entry = zin.getNextEntry(); } // Close the streams zin.close(); // Compress the files for (int i = 0; i < files.length; i++) { InputStream in = new FileInputStream(files[i]); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(files[i].getName())); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } // Complete the ZIP file out.close(); tempFile.delete(); } } A: In Java 7, the best way is to use the built in Zip File System Provider: http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html i.e. import java.util.*; import java.net.URI; import java.nio.file.Path; import java.nio.file.*; public class ZipFSPUser { public static void main(String [] args) throws Throwable { Map<String, String> env = new HashMap<>(); env.put("create", "true"); // locate file system by using the syntax // defined in java.net.JarURLConnection URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip"); try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt"); Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt"); // copy a file into the zip file Files.copy( externalTxtFile,pathInZipfile, StandardCopyOption.REPLACE_EXISTING ); } } } ~
{ "language": "en", "url": "https://stackoverflow.com/questions/7548900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Embedded IP stack: is it okay/accepted to have asynchronous sending? I am trying to implement a very small IP stack for 8-bit AVR MCUs. I don't want it to support TCP, because it's really too big and I don't need it, but rather UDP (and, of course, ARP and ICMP). I want the stack code to fit into 16 kiB of ROM and 1 kiB of RAM, of course letting as much space as possible for the application. I am using an ENC28J60-based board for PHY/MAC management, which has an internal 8 kiB RX/TX circular buffer. As packets arrive into this chip, it writes them one after the other into the RX buffer but won't overwrite the oldest one. The oldest one is pointed to by a pointer which must be updated to point to the next packet when the user is done reading it. It also sends an interrupt on one of its pins when a new packet has arrived. For the RX part, I want to work just like lwIP does: signal that a new packet is ready when we receive an interrupt (save its address and size) but proceed it only when the user calls our IP stack function. This should work okay; if the user does not call our function often enough, the new arriving packets will be dropped and that's it. The user provides the stack with an UDP callback. Now, the problem is about TX. Let's say I want to send an UDP packet to some IP for which I don't know the link address. An ARP request has to be sent before my packet is sent. What if an UDP packet comes in before the ARP reply? It has to be processed by my UDP callback, but what if I want to send something from this callback? I'm still waiting for an ARP reply here. For sure this blocking mechanism is not right. My question is: is it okay/accepted to have asynchronous sending? Thus if I want to send something, I provide the send function with a callback and its get called when the UDP packet may be sent. This way, everything is event-driven. A: As to whether it's "acceptable" to have asynchronous sending, I can't imagine why it would be a problem, so long as you can implement that in your code size requirements. As to the best way to implement such a scheme, I don't know how big a packet size you want to support (I'm guessing a lot less than the theoretical maximum of 64K), but I would allocate a ring of send buffers, and whenever the process responsible for actually sending to the hardware ran its loop/interrupt/whatever, it would check each live buffer for its ARP status (has ARP entry, ARP request outstanding, ARP request timed out, no ARP entry or request outstanding) and take the appropriate action (respectively: push to hardware with appropriate MAC, skip this time, discard, send ARP request). You could trigger this send routine to run every time the ARP table is updated so that you could meet any necessary real-time requirements (although some people would argue that Ethernet is not and will never be a truly real-time capable system, but that's a topic for another forum that doesn't mind flamewars). A: Can you have two callbacks(basically async paths), one for receiving from IP layer and one for sending to IP? Also, if you are implementing layers, I think the IP send / route function should take care of the ARP reply at that level.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Will the timezone used in MySQL Date and Time functions cause conflicts/issues? I have a website which allows visitors to view content, and has the option for them to register and login (which gives them permission to submit content). * *Whenever content is submitted by users I do a INSERT INTO query in the content table, I use UNIX_TIMESTAMP() to store the timestamp in the column content_timestamp (which is the time of when the content is submitted). *I also allow users to optionally select a timezone (supports all timezones from http://php.net/manual/en/timezones.php) from a dropdown menu in there usercp - and a column (user_timezone) in the users table gets UPDATE'd with that, so all displayed dates are adjusted to that (if selected). *One the page which the content is displayed I display the formatted date (of when the content is submitted) - if they are not logged or have logged in and not selected a timezone (in the usercp) I format it in GMT otherwise I use there selected timezone e.g.: <?php if (!is_logged_in() || is_logged_in() && empty($row['user_timezone'])) { echo gmdate('d/m/y', $row['content_timestamp']) . ' GMT'; //in GMT } else { date_default_timezone_set($row['user_timezone']); echo date('d/m/y', $row['content_timestamp']); //use the users timezone } ?> Now everything is fine but now I'm planning on schedulling a cronjob weekly and monthly (this will be the weekly featured and monthly featured content) which will access a php file which will do a INSERT INTO query (of top rated content) and add it to the featured table - along with the UNIX_TIMESTAMP() (featured_timestamp - of when it was added). The cronjob is set to access the php file the first day of every week 12 am midnight GMT and the first day of every month 12 am midnight GMT. ...Now getting to the problem: I'm displaying the featured content by comparing timestamps using the MySQL Date and Time functions like so (below example will return the weekly featured content): SELECT * FROM featured WHERE WEEK(FROM_UNIXTIME(featured_timestamp), 1) = WEEK(UNIX_TIMESTAMP(), 1) AND FROM_UNIXTIME(featured_timestamp, '%Y %M') = FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y %M') So will this cause any timezone conflicts/issues seeing as the cronjob is accessing the file in GMT and I'm unaware of what timezone MySQL WEEK() and DATE_FORMAT() use (just curious as that would mean comparison queries like the above could produce incorrect results)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7548909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby on Rails highlight current link on navigation bar? Can anyone tell me how to highlight (with color) the current link on a navigation bar, using css? I don't want to use the controller option. Here is the code from shared/menu.html.erb: <div id = "navigation"> <ul> <li id="menu"><%=link_to "Menu", menus_path, :class => "menunav"%></li> <li id="drink"><%=link_to " Drinks", drinks_path, :class => "drinknav"%> </li> </ul> </div> A: The first approach is to handle current controller_name and action_name to detect what page you are on. It's good, but it adds a bit of server-side to client-specific template. The rails helper uses that way is link_to_unless_current. Minimum usage of JS. See an example here The second is to parse $(location) and directly add a certain class to the selected navigation item to highlight it. The third (depends on an object) is to build a JS object with current state of entity and add methods to add a class to an active nav. Then you can instantiate this JS class, passing on the object and keeping the logic encapsulated. A: Something like this would work for you. Of course you'd have to tweak it to your purposes, maybe get more sophisticated with the match (currently this would only match paths, as you have in your example). $("#navigation a[href="+window.location.pathname+"]") .closest('li') .css('background-color', '#ff0'); Better still, you'd define a "current" class somewhere, then simply add it: /* in some stylesheet */ #navigation li.current { background-color: #ff0; } /* then the js */ $("#navigation a[href="+window.location.pathname+"]") .closest('li') .addClass('current'); A: There are a few approaches to this, but if you're after a simple one, I suggest adding a class to your body. <body class="<%= params[:controller] %>_controller"> ... </body> Then in your css you can do the following. body.menus_controller #navigation a.menunav, body.drinks_controller #navigation a.drinknav { background-color : yellow color : blue } This can get complicated if you have multiple pages you want to split, but for this basic example it should be ok. A: Use a Rails Helper: link_to_unless_current * *Simple and the fastest. *I like @Anatoly's idea to use the link_to_unless_current helper so I whipped up the following solution. Copy and paste to save you some time.: What does it do? * *If the page is current then it executes the block - and you can add the CSS classes you need to highlight that link. *If the page is NOT current, then it simply returns the first link above. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Opening a epub file on a UIWebView Xcode Open File (epub) with xcode programming - NOT OPENING (O just see a little white block on upper right) I have also added epub file in project, I am using following below code to open it in viewdidload method. - (void)viewDidLoad { NSString *filepath = [[NSBundle mainBundle]pathForResource:@"MyEpub" ofType:@"epub"]; UIWebView *wv = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)]; [self.view addSubview:wv]; [wv loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filepath]]]; [super viewDidLoad]; } A: Well, you won't be able to open an ePub file in a UIWebView, because it's not a supported format. Apple provide a list of supported formats here: http://developer.apple.com/library/ios/#qa/qa1630/_index.html You'll need to use the link Jano provided above to decompress, parse, and open up the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: c++ win32 how to store persistent data I'm developing a c++ win32 application and i would like to implement persistent storage into it. I know I can use filesystem or a database or the registry, but what would be the best way for storing a: boolean unsigned int wchar_t [256] boolean [15] I need to read/write from the storage only when the application starts and shuts down. This is a user level application and the data should be stored per user. I want to store application preferences (trackbar position, some settings, number of runs,..) so there is no need to import/export settings and troubleshooting. Which storage method would be the most appropriate for this type of data? A: I think the easiest way to write settings on Windows is to put them in the registry. For user specific settings you will write in the HKEY_CURRENT_USER section. Here is the full list of registry access functions in the Win32 API. If you consider you will ever need to port your application to other platforms, then you may want to look at a more cross-platform friendly solution. What I do in my apps is to write settings the Unix way, with a settings file in the user's home directory. This has the added benefit that you can use a text based format that you (or your users) can edit if necessary, for example, you could write it in the venerable .ini format using the WritePrivateProfileString or similar API calls. Note that on Windows, applications don't write settings files directly in the home directory, there is the "AppData" user specific folder where these files typically go. You can obtain the path of this folder by calling the SHGetFolderPath function. A: The simplest solution is to store the information in a .ini file under the user's APPDATA path. A: Consider just serialization/protobuffer: http://code.google.com/p/protobuf/ where you write to some user specific path for the application
{ "language": "en", "url": "https://stackoverflow.com/questions/7548916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest way to retrieve data from a database in .NET? Using ADO.NET, what is the fastest way to retrieve data from the database and populate the data into my business objects? Which one should I use? DBDataReader , DBDataAdapter, or any other classes? Is there a way to make this process automated? Let's say based on property names and matching them with database field names? A: That sounds exactly like what an ORM or micro-ORM does. Here's the output of dapper-dot-net's performance tests (run about 1 minute ago, on a PC that is also busy doing some transcoding, so not 100% reliable - please run yourself)... This is also a very limited test - as always, tests should be representative of your specific environment - but since we can't predict your environment, we use our environment instead! I've marked the "dapper" ones as <==== dapper Running 500 iterations that load up a post entity Mapper Query (non-buffered) took 57ms <==== dapper hand coded took 57ms Dynamic Mapper Query (buffered) took 58ms <==== dapper PetaPoco (Fast) took 58ms Dynamic Mapper Query (non-buffered) took 59ms <==== dapper Mapper Query (buffered) took 60ms <==== dapper Dapper.Cotrib took 60ms <==== dapper PetaPoco (Normal) took 66ms Dynamic Massive ORM Query took 67ms BLToolkit took 88ms Simple.Data took 96ms Linq 2 SQL Compiled took 99ms NHibernate Session.Get took 127ms SubSonic Coding Horror took 128ms Entity framework CompiledQuery took 130ms NHibernate HQL took 132ms NHibernate SQL took 134ms NHibernate Criteria took 173ms Soma took 184ms Linq 2 SQL ExecuteQuery took 230ms Linq 2 SQL took 694ms NHibernate LINQ took 700ms Entity framework ESQL took 730ms Entity framework ExecuteStoreQuery took 735ms Entity framework took 991ms Entity framework No Tracking took 1011ms SubSonic ActiveRecord.SingleOrDefault took 4345ms (end of tests; press any key) A: If you want automated you are looking for an orm. You might check out some of the lighter wieght ones like massive, ormlite, dapper, and PetaPoco. A: Using ADO.NET, what is the fastest way to retrieve data from the database and populate the data into my business objects? Is there a way to make this process automated? Let's say based on property names and matching them with database field names? Dapper. Absolutely blazing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best practice for combining table data in MySQL? I have a list of people in a table that are associated with one or more projects, presumably stored in another table. My question is, what would be the best practice for setting this up? Each project needs to have a post of its own, the same goes for the people as they all have various kind of data. How do I tie multiple project posts to one people post, and vice versa? A: The is a pretty wide scope question and depends on exact requirements of the entity infrastructure to be represented in the relational database. I would suggest you to go over a basics of Data Normalization and consider yourself which normalization form is optimal for your application. * *Description of the database normalization basics *Normal forms *Introduction to Data Normalization: A Database "Best" Practice If we stick simply with Projects and Participants I would go further with sollowing desing: **PROJECTS** ID ... **PEOPLE** ID ... **PROJECT_PARTICIPANTS** PROJECT_ID (FK PROJECTS) PARTICIPANT_ID (FK PEOPLES) A: I'd expect to see a column that allowed a program to distinguish one group of people and posts from another. If they really had to be separated, and I'm not sure that I agree that they must, I'd have VIEWs for each project. I'd keep one table for person and another for post. I'd do the JOINs in the VIEW. A: generally you would have 3 tables. one for people, one for projects, and one for the relation between them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git "error: The branch 'x' is not fully merged" Here are the commands I used from the master branch git branch experiment git checkout experiment Then I made some changes to my files, committed the changes, and pushed the new branch to GitHub. git commit . -m 'changed files' git push -u origin experiment Later on I decided to merge my experiment branch into the master branch. git checkout master git merge experiment Finally I pushed the changes to GitHub. git push -u origin master All went well until I tried deleting my experiment branch using git branch -d experiment I got the error message: error: The branch 'experiment' is not fully merged. If you are sure you want to delete it, run 'git branch -D experiment'. I'm a bit new to git, and I don't know how much more I could possibly merge the two branches. What am I missing here? A: Note Wording changed in response to the commments. Thanks @slekse That is not an error, it is a warning. It means the branch you are about to delete contains commits that are not reachable from any of: its upstream branch, or HEAD (currently checked out revision). In other words, when you might lose commits¹. In practice it means that you probably amended, rebased (including squash merge) or filtered commits and they don't seem identical. Therefore you could avoid the warning by checking out a branch that does contain the commits that you're about un-reference by deleting that other branch.² You will want to verify that you in fact aren't missing any vital commits: git log --graph --left-right --cherry-pick --oneline master...experiment This will give you a list of any nonshared between the branches. In case you are curious, there might be a difference without --cherry-pick and this difference could well be the reason for the warning you get: --cherry-pick Omit any commit that introduces the same change as another commit on the "other side" when the set of commits are limited with symmetric difference. For example, if you have two branches, A and B, a usual way to list all commits on only one side of them is with --left-right, like the example above in the description of that option. It however shows the commits that were cherry-picked from the other branch (for example, "3rd on b" may be cherry-picked from branch A). With this option, such pairs of commits are excluded from the output. ¹ they're really only garbage collected after a while, by default. Also, the git-branch command does not check the revision tree of all branches. The warning is there to avoid obvious mistakes. ² (My preference here is to just force the deletion instead, but you might want to have the extra reassurance). A: You can simply figure out : git log --cherry master...experimental --cherry option is a synonym for --right-only --cherry-mark --no-merges git-log man page said it's useful to limit the output to the commits on our side and mark those that have been applied to the other side of a forked history with git log --cherry upstream...mybranch, similar to git cherry upstream mybranch. FYI. --cherry-pick omits equivalent commits but --cherry-marks doesn't. It's useful to find rebase and force updated changes between upstream and co-working public branch A: Git is warning that you might lose history by deleting this branch. Even though it would not actually delete any commits right away, some or all of the commits on the branch would become unreachable if they are not part of some other branch as well. For the branch experiment to be “fully merged” into another branch, its tip commit must be an ancestor of the other branch’s tip, making the commits in experiment a subset of the other branch. This makes it safe to delete experiment, since all its commits will remain part of the repository history via the other branch. It must be “fully” merged, because it may have been merged several times already, but now have commits added since the last merge that are not contained in the other branch. Git doesn’t check every other branch in the repository, though; just two: * *The current branch (HEAD) *The upstream branch, if there is one The “upstream branch” for experiment, as in your case, is probably origin/experiment. If experiment is fully merged in the current branch, then Git deletes it with no complaint. If it is not, but it is fully merged in its upstream branch, then Git proceeds with a warning seeming like: warning: deleting branch 'experiment' that has been merged to 'refs/remotes/origin/experiment', but not yet merged to HEAD. Deleted branch experiment (was xxxxxxxx). Where xxxxxxxx indicates a commit id. Being fully merged in its upstream indicates that the commits in experiment have been pushed to the origin repository, so that even if you lose them here, they may at least be saved elsewhere. Since Git doesn’t check other branches, it may be safe to delete a branch because you know it is fully merged into another one; you can do this with the -D option as indicated, or switch to that branch first and let Git confirm the fully merged status for you. A: I tried sehe's answer and it did not work. To find the commits that have not been merged simply use: git log feature-branch ^master --no-merges A: to see changes that are not merged, I did this: git checkout experiment git merge --no-commit master git diff --cached Note: This shows changes in master that are not in experiment. Don't forget to: git merge --abort When you're done lookin. A: I did not have the upstream branch on my local git. I had created a local branch from master, git checkout -b mybranch . I created a branch with bitbucket GUI on the upstream git and pushed my local branch (mybranch) to that upstream branch. Once I did a git fetch on my local git to retrieve the upstream branch, I could do a git branch -d mybranch. A: I had this happen to me today, as I was merging my very first feature branch back into master. As some said in a thread elsewhere on SO, the trick was switching back to master before trying to delete the branch. Once in back in master, git was happy to delete the branch without any warnings. A: Easiest Solution With Explanation (double checked solution) (faced the problem before) Problem is: 1- I can't delete a branch 2- The terminal keep display a warning message that there are some commits that are not approved yet 3- knowing that I checked the master and branch and they are identical (up to date) solution: git checkout master git merge branch_name git checkout branch_name git push git checkout master git branch -d branch_name Explanation: when your branch is connected to upstream remote branch (on Github, bitbucket or whatever), you need to merge (push) it into the master, and you need to push the new changes (commits) to the remote repo (Github, bitbucket or whatever) from the branch, what I did in my code is that I switched to master, then merge the branch into it (to make sure they're identical on your local machine), then I switched to the branch again and pushed the updates or changes into the remote online repo using "git push". after that, I switched to the master again, and tried to delete the branch, and the problem (warning message) disappeared, and the branch deleted successfully A: As Drew Taylor pointed out, branch deletion with -d only considers the current HEAD in determining if the branch is "fully merged". It will complain even if the branch is merged with some other branch. The error message could definitely be clearer in this regard... You can either checkout the merged branch before deleting, or just use git branch -D. The capital -D will override the check entirely. A: I believe the flag --force is what you are really looking for. Just use git branch -d --force <branch_name> to delete the branch forcibly. A: C:\inetpub\wwwroot\ember-roomviewer>git branch -d guided-furniture warning: not deleting branch 'guided-furniture' that is not yet merged to 'refs/remotes/origin/guided-furniture', even though it is merged to HEAD. error: The branch 'guided-furniture' is not fully merged. If you are sure you want to delete it, run 'git branch -D guided-furniture'. The solution for me was simply that the feature branch needed to be pushed up to the remote. Then when I ran: git push origin guided-furniture /* You might need to fetch here */ git branch -d guided-furniture Deleted branch guided-furniture (was 1813496). A: If you made a merge on Github and are seeing the error below. You need to pull (fetch and commit) the changes from the remote server before it will recognize the merge on your local. After doing this, Git will allow you to delete the branch without giving you the error. error: The branch 'x' is not fully merged. If you are sure you want to delete it, run 'git branch -D 'x'. A: The accepted answer is correct. In this answer, I will add three things: * *how this has happened (often to me) *show an example *how to make sure you are not missing any changes before force delete via -D I use Rebase and merge on GitHub as the default PR merging approach. That creates new commit (hashes) for the same changes. For example, when I run git log --graph --left-right --oneline add-theme-dark-2...main on one of my project, I got this: > fba6fce (HEAD -> main, tag: v2.0.9, origin/main) Refactored to semantic class names. > 4e665bc Refactored to semantic class names. (1a) .... > 8bd13a6 Added 'font-semibold' to title. (2a) < 23f7b8a (add-theme-dark-2) Refactored to semantic class names. < cf71814 Refactored to semantic class names. (1b) .... < d3a774a Added 'font-semibold' to title. (2b) (END) Note how 1a/1b and 2a/2b have different commit hashes. To make sure that you are not missing changes, run: git log --graph --left-right --cherry-pick --oneline add-theme-dark-2...main If it return a list, that each line start with "=": = fba6fce (HEAD -> main, tag: v2.0.9, origin/main) Refactored to semantic class names. = 4e665bc Refactored to semantic class names. ... = 346770b Moved text size to component. = 68cd471 Added theme-dark. = 8bd13a6 Added 'font-semibold' to title. it is safe to delete the branch with: git branch -D add-theme-dark2 A: In my case , this happened because the branch had no commits. It had only been created from another branch. The solution: Make 1 commit in the branch. Then I could switch to another branch and delete it, with no error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "387" }
Q: Rails 3.1 ActionMailer Custom Template Path? Is it possible to customize the template path for Rails 3.1 ActionMailers? By default, Rails looks in: /app/views/[mailer_class] for the mailer view templates. However, I'd much rather organize them in: /app/mailers/views/[mailer_class] or at least: /app/views/mailers/[mailer_class] I know this was possible in 2.3 via ActionMailer's template_path config parameter, but that seems to be deprecated as of Rails 3. Is this kind of customization no longer possible? A: This sort of customization is possible still. There is a couple different ways to do this depending on how your mailers are written. If you have the format blocks such as format.html you can pass render '/path/to/template'. Or if you are just calling mail() there are two options for setting the path and template name, which you should just need to pass the path option: mail(:template_path => 'mailers/[mailer_class]', :template_name => '[mailer_method]') You should check out the Rails Guides for more detailed info. http://guides.rubyonrails.org/action_mailer_basics.html#mailer-views
{ "language": "en", "url": "https://stackoverflow.com/questions/7548928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Python 3 concurrent.futures socket server works with ThreadPoolExecutor but not ProcessPoolExecutor I am trying to create a simple socket server using the new concurrent.futures classes. I can get it to work fine with ThreadPoolExecutor but it just hangs when I use ProcessPoolExecutor and I can't understand why. Given the circumstance, I thought it might have something to do with trying to pass something to the child process that wasn't pickle-able but I don't that is the case. A simplified version of my code is below. I would appreciate any advice. import concurrent.futures import socket, os HOST = '' PORT = 9001 def request_handler(conn, addr): pid = os.getpid() print('PID', pid, 'handling connection from', addr) while True: data = conn.recv(1024) if not data: print('PID', pid, 'end connection') break print('PID', pid, 'received:', bytes.decode(data)) conn.send(data) conn.close() def main(): with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind((HOST, PORT)) sock.listen(10) print("Server listening on port", PORT) while True: conn, addr = sock.accept() executor.submit(request_handler, conn, addr) conn.close() print("Server shutting down") if __name__ == '__main__': main() A: Good call Donkopotamus, you should have posted that as the answer. I wrapped the handler up in a try-block and when it attempts to call conn.recv() I got the exception: [Errno 10038] An operation was attempted on something that is not a socket. Since the worker process was dying badly, it deadlocked. With the try-block in place catching the error, I can continue to connect as much as I want without any deadlock. I do not get this error if I change the code to use a ThreadPoolExecutor. I have tried several options and it looks like there is no way to properly pass a socket to the worker process in a ProcessPoolExecutor. I have found other references to this around the internet but they say it can be done on some platforms but not others. I have tried it on Windows, Linux and MacOS X and it doesn't work on any of them. This seems like a significant limitation. A: are you sure it is not caused by 'conn.close()' after you run 'executor.submit(...)'? I just remove the line and try on mac10.12.6 and python 3.6.3 it works well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handle WIF SignInResponseMessage (Post) when user requests action method with both [HttpGet] & [HttpPost] overloads] I thought the solution to this would occur to me as I've sat on this problem for many months - but my brain has not flags the obvious best approach. I have two controller methods say "Edit" that are protected with an action filter that causes passive authentication to an STS. [HttpGet] public ActionResult Edit(Guid id) { [do stuff] } [HttpPost] public ActionResult Edit(Guid id, EditViewModel model) { [do stuff] } The problem is, mvc receives the SignInResponseMessage and then fires the HttpPost which is not what I want... Anyone out there approached this issue and feel they've got a nice solution? I guess I could uniquely name all my action methods if worst comes to worse i.e. the good old mvc1 Edit() vs Update() / New() vs Create() etc.. A: I have a solution... Instead of allowing the STS to post to any url (and hit any action in the application), I use a setting in my STS to post to one url which has an action method that looks like this: public ActionResult Index() { if (MyIdentity.IsAuthenticated) { if (ControllerContext.HttpContext.Request["wreply"] != null) { var returnUrl = ControllerContext.HttpContext.Request["wreply"]; if (returnUrl.StartsWith(Stgs.WebRt)) { return Redirect(returnUrl); } //make sure the wreply is actually for this application and not a random url } return Redirect("/"); } return View(); } Then in the STS when I'm building the SignOutResponseMessage I add the line: response.SetParameter("wreply", message.Reply); where "reponse" is a Microsoft.IdentityModel.Protocols.WSFederation.SignInReponseMessage and "message" is a is a Microsoft.IdentityModel.Protocols.WSFederation.SignInRequestMessage. This basically adds the wreply as a form input that is posted to the relying party. Hence making the controller action code above work as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can devise sign_in() test helper accept a new_record? In the following example, can I use build() instead of create()? class UsersControllerTest < ActionController::TestCase setup do @user = Factory.create(:user) end test "admin can get index" do sign_in @user get :index assert_response :success end test "user cannot get index" do sign_in @user get :index assert_response 403 end end In real-life use, the user would have already been created (saved) before signing in, so that's why my test uses create(). However, I want to use build() because I hope it will make my tests faster. The devise README does not explicitly say that it is OK to use build(). A: It looks like the user record must be persisted, according to this note by José. A mock is never going to work. When you say sign in, the user is stored in session (basically, the user class and its id). When you access the controller, another user object is retrieved based on the stored data. The best way to solve the problem is using something that persists the object, like Factory Girl. https://github.com/plataformatec/devise/issues/928
{ "language": "en", "url": "https://stackoverflow.com/questions/7548934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: problem with execjs doing michael hartl tutorial on windows... ExecJS::RuntimeError in Users#index I'm new to ruby and rails and walking (crawling?) through the tutorial. the second project uses scaffolding to create a user that consists of a name and email address. when i try to view the users screen I get the following: ExecJS::RuntimeError in Users#index Showing /home/max/rails_proj/demo_app/app/views/layouts/application.html.erb where line #6 raised: 湉異⁴牅潲㩲唠歮潮湷漠瑰潩⼢浴⽰硥捥獪〲ㄱ㤰㔲㐭㜲ⴲ㠱㝮穩ⴰ⸰獪•灳捥晩敩⹤਍ (in /home/max/rails_proj/demo_app/app/assets/javascripts/users.js.coffee) Extracted source (around line #6): 3: <head> 4: <title>DemoApp</title> 5: <%= stylesheet_link_tag "application" %> 6: <%= javascript_include_tag "application" %> 7: <%= csrf_meta_tags %> 8: </head> 9: <body> Rails.root: /home/max/rails_proj/demo_app Application Trace | Framework Trace | Full Trace app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb__1031573605_1065816420' app/controllers/users_controller.rb:7:in `index' I am using windows xp, cygwin, rails 3.1.0 (i've tried the new rc1 also), ruby 1.8.7. I found this error on google and there's supposedly a fix which i've tried to use (the execjs gem 1.2.9) but that doesn't seem to fix it for me.... i have tried all the fixes (to the best of my limited ruby etc ability at this point) but nothing seems to work although the error message is sometimes different - still errors on the same line. I've tried to uninstall and reinstall cygwin, ruby, rails etc.. to no avail so far... any feedback would be great! A: I got the same error on cygwin. I tried compiling the latest node.js (v0.6.15) but it said cygwin was not supported. Older version seem to support it so here's what I did: wget http://nodejs.org/dist/node-v0.4.12.tar.gz tar xvfz node-v0.4.12.tar.gz cd node-v0.4.12/ ./configure make make install I'm not sure if there is a newer version than 0.4.12 that will work under cygwin, but this seems to fix my problem for now. Also I seemed to have the proper prereq's but if you have trouble during configure or make then just do a search on "step by step install nodejs cygwin". A: I am not sure if this will work in your case, but on Ubuntu you can add gem 'therubyracer' to your Gemfile and it will work just fine. Another tip would be to comment out the following lines in the Gemfile: group :assets do # gem 'sass-rails', " ~> 3.1.0" # gem 'coffee-rails', "~> 3.1.0" # gem 'uglifier' end since those are the ones that require execjs A: I also had this problem, and it was solved installing a javascript runtime: sudo apt-get install nodejs I follow this post: http://www.adanacs.com/node/3 Good luck! A: As someone who tried to do that book on windows, I have 2 pieces of advice: * *Install Ubuntu to run ruby on rails. It is a little bit of work, but if you are going to invest time and effort it is worth it 100 times over. You can set up dual install with existing windows. Or, just find an old computer and install it on there. It uses much less power than windows xp and only about 300 Mb of memory. *Start with Agile Web Development with Rails. http://www.amazon.com/Agile-Development-Rails-Pragmatic-Programmers/dp/1934356549 . It is a much better first tutorial. A: I had a similar problem. Helped me to update Ruby 1.9.3 on Ruby 2.0.0. A: Run bundle install in cmd and it will install some new gems. Go back to cygwin and launch your server rails s and all will be well. I had the same problem. Cygwin seems to be the issue here. A: On windows, I had the same problem. It seems there is no javascript interpreter installed to compile the coffeescript that is used in scaffolds. Install node.js from http://nodejs.org/ and restart the command prompt you were using to run rails, in order to update the path. I don't have cygwin installed, so I couldn't compile node.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Force php to display number as 0.000001 instead of f 1.0E-6 I want to force php to output the number as a decimal number, not 1E-6. Is this possible? A: Use printf: printf("%0.6f", $var); Alternatively, sprintf returns a string rather than printing directly to the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ImageMagick compare not returning anything to php shell_exec() I want to compare two images using Image Magick. For this I am using following command in windows command prompt compare -verbose -metric mae image1.jpg image2.jpg difference.png This command compares image1 and image2 and prints the resultant output to command prompt window and generates a difference.jpg file that shows difference between two images. But when I run same command using php shell_exec() no output is returned. I know that the command is being executed by php as difference.jpg is being generated but no output is returned by the function. Similarly when i try passthrough() or system() to get output, again the command is being executed but no output is returned.But when I use builtin system commands like dir I can easily get output. Any help will be appreciated as I am stuck on this for hours but still no success Thanks A: I solved the problem. Its strange that imagemagick compare with verbose arguement does not send anything to normal command promt output. It sends output to stderr. Stderr normally receives error output. But here this command is writing normal output to stderr. As output is going to stderr so shell_exec() is unable to get it. In order to capture it in shell_exec() we will have to append 2>&1 to command. This will redirect stderr to normal command prompt output. A: The ImageMagick compare command normally doesn't produce any output. You give it two input files and the name of the output file, and it quietly creates the output file. If there's an error, it will write an error message to stderr and set a non-zero exit status. (There should be a way to get the exit status, but I don't know PHP.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to show a status dialog while parent form is closing I have a WPF app that takes a while to close so I want to add a 'please wait' dialog to show up while the main form is closing. However, when I added 'formmessage.show' to my main form's closing event handler, the form displays but instead of the 'please wait' text, all i get is a white rectangle. This only seems to happen when calling this code from the closing handler. It works fine from other handlers (form click or maximize). Can anyone help? Here is my simplified code: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Form1 f = new Form1(); f.Show(); System.Threading.Thread.Sleep(3000); } } Form1 has a label on it which says 'please wait'. A: Try out: Application.Current.Dispatcher.Invoke( DispatcherPriority.Normal, new Action(() => { Form1 f = new Form1(); f.Show(); System.Threading.Thread.Sleep(3000); })); BTW, you can remove Thread.Sleep() because default value of the Application Shutdown mode is OnLastWindowClose so Application will be active until an user explicitly close active window, this behaviour could be changed by switching Application.ShutdownMode to OnMainWindowClose in the App.xaml file) A: That would be because of the fact your creating the form in the same thread your telling to sleep, during which it's not going to respond to draw requests, try launching the form in another thread, and closing it in MainWindow's destructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Wrong Date from string returns from formatter! Why? I have problem with NSDateFormatter I converting date from picker in one view `NSDateFormatter *output = [[NSDateFormatter alloc] init]; [output setDateStyle:NSDateFormatterMediumStyle]; [output setDateStyle:NSDateFormatterShortStyle]; [output setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; NSString *StringToSend = [output stringFromDate:datePicker.date]; ` then send string to other nib where converting it back with that code `NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; [inputFormatter setDateStyle:NSDateFormatterMediumStyle]; [inputFormatter setDateStyle:NSDateFormatterShortStyle]; [inputFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; NSDate *formatterDate = [inputFormatter dateFromString:StringFromOtherView]; NSLog(@"%@", formatterDate);` and it's return wrong date sending 2011-09-26 01:02:49 geting 2011-09-25 22:02:49 +0000 what is wrong? A: Because: * *When you NSLog() an NSDate, it always logs it in GMT *You live in a timezone that's three hours ahead of of GMT. Thus, 1:02 am for you is 22:02 pm (of the previous day) in GMT. A: Include the timezone on your date format string. A: + (NSDate*) dateFromString:(NSString*)aStr { if (aStr.length == 10) { aStr = [aStr stringByAppendingFormat:@" 00:00:00"]; } NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"]; dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; NSLog(@"strdate %@", aStr); NSDate *aDate = [dateFormatter dateFromString:aStr]; NSLog(@"date = %@",aDate); [dateFormatter release]; return aDate; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Enable new permission dialog How to enable the new oauth permission/install dialog? Any actual url will be helpful. A: Apps Dashboard > Edit your App > Settings > Advanced > Migrations section > Enable "Enhanced Auth Dialog" A: It may be because you're testing with a Facebook account that isn't logged as a developer or test user of the app. If you're using a Facebook user not associated with your app the old dialogs will still display to you. Go to the roles section of your app, create a test user, switch to that user and start testing again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails dynamic content in jQuery qTip2 I got my jQuery qTip2 working but I have one last thing to solve: getting dynamic content to display as a link in the tooltip. (I'm new to all this so please bear with me.) Here's what I have now to get the qTip to show: $(document).ready(function() { $('span[title]').qtip({ position: { my: 'bottom center', at: 'top center' }, hide: { fixed: true }, style: { classes:'ui-tooltip-shadow ui-tooltip-rounded' } }); }); Here's my erb file: <li class="article"><span title="<%= author.name %>"> <%= article.body %>,&nbsp; </span></li> The HTML rendered: <li class="article"><span title="My Name"> Testing,&nbsp; </span></li> What I want to do though is display a link as the qTip that shows the author's name and links to their profile. I know I can add a link in my application.js file like so: **content: { text: '<a href="link">My name</a>'},** However, how can I make it so the content adds dynamically from my database? Ideally I'd want something like: **content: { text: '<a href="`<%= article.author.profile %>`">`<%= author.name %>`</a>'},** I know from a previous answer that there is an issue with producing valid HTML. However I'm hoping someone can help me out here. A: One way you can accomplish this is to do an ajax call to the server to get the dynamic HTML you want to display in the tooltip depending on the content. You can use the api method of onRender to accomplish this: $(document).ready(function() { $('span[title]').qtip({ position: { my: 'bottom center', at: 'top center' }, hide: { fixed: true }, style: { classes:'ui-tooltip-shadow ui-tooltip-rounded' }, api: { onRender: function() { $.post(urlToContent, function (content) { // Update the tooltip with the dynamic content api.updateContent(content); }); } } }); }); EDIT: You can do the same thing in qtip2 by using the ajax method: $(document).ready(function() { $('span[title]').qtip({ position: { my: 'bottom center', at: 'top center' }, hide: { fixed: true }, style: { classes:'ui-tooltip-shadow ui-tooltip-rounded' }, content: { text: 'Loading...', // The text to use whilst the AJAX request is loading ajax: { url: '/path/to/file', // URL to the local file type: 'GET', // POST or GET data: {} // Data to pass along with your request } }); }); Take a look at the ajax link to see the other ways to get data from the sever, but the example above will work if you are getting back basic HTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ to java conversion, a few questions I am converting a some C++ to java and have a small bit that I am unsure about first question is what is tested for in the line if (ampconst[i][0] || ampconst[i][1]) this in an example to the data in the array. static short ampconst[NUT_SERIES][2] = { {0,0}, {0,0}, {46,-24} }; and my second question is that the ampsecul array is far shorter than NUT_SERIES so I am getting array out of bounds exceptions, the array terminates like so static long ampsecul[][5] = { {0 ,-171996 ,-1742 ,92025 ,89}, {1 ,2062 ,2 ,-895 ,5}, {8 ,-13187 ,-16 ,5736 ,-31}, {9 ,1426 ,-34 ,54 ,-1}, {10 ,-517 ,12 ,224 ,-6}, {11 ,217 ,-5 ,-95 ,3}, {12 ,129 ,1 ,-70 ,0}, {15 ,17 ,-1 ,0 ,0}, {17 ,-16 ,1 ,7 ,0}, {30 ,-2274 ,-2 ,977 ,-5}, {31 ,712 ,1 ,-7 ,0}, {32 ,-386 ,-4 ,200 ,0}, {33 ,-301 ,0 ,129 ,-1}, {37 ,63 ,1 ,-33 ,0}, {38 ,-58 ,-1 ,32 ,0}, /* termination */ { -1, } }; so how could this be handled in java and what would the values be at these lines when the array is out of bounds or how would C++ handle this. ampsin = ampsecul[isecul][1] + ampsecul[isecul][2] * T10; ampcos = ampsecul[isecul][3] + ampsecul[isecul][4] * T10; thanks in advance for any advice. This is the whole for loop too see the code in context. for (i = isecul = 0; i < NUT_SERIES ; ++i) { double arg = 0., ampsin, ampcos; short j; if (ampconst[i][0] || ampconst[i][1]) { /* take non-secular terms from simple array */ ampsin = ampconst[i][0]; ampcos = ampconst[i][1]; } else { /* secular terms from different array */ ampsin = ampsecul[isecul][1] + ampsecul[isecul][2] * T10; ampcos = ampsecul[isecul][3] + ampsecul[isecul][4] * T10; ++isecul; } for (j = 0; j < 5; ++j) arg += delcache[j][NUT_MAXMUL + multarg[i][j]]; if (fabs(ampsin) >= prec) lastdpsi += ampsin * sin(arg); if (fabs(ampcos) >= prec) lastdeps += ampcos * cos(arg); } A: That first if statement is testing the array entries for zero/non-zero. In C/C++ a boolean is simply an int that is used in a special way such that zero is false and non-zero is true. As for your second array question I haven't grocked it yet. But understand that C/C++ does no array bounds checking (other than what may accidentally occur if you touch an undefined storage page), so unless there's an egregious error in the C++ code there must be something that limits references to the valid bounds of the array. A: if (ampconst[i][0] || ampconst[i][1]) tests whether the first/second column in ampconst[i] contain non-zero (it is an early-out optimization: if both the constants are 0 then the calculation can be skipped) Edit I just found (google!) that this is a nutation calculation that has been adopted in quite a few places, but seems to be originally from a libastro. hg clone https://bitbucket.org/brandon/pyephem As far as the isecul index is concerned: apparently isecul should never grow to >= 15 (note that i is the loop variable, not isecul, isecul is incremented conditionally). However, seeing the 'terminator' (-1) value, I'd really expect a check some like if (ampsecul[isecul][0] == -1) isecul = 0; // ? just guessing :) or if (ampsecul[isecul][0] == -1) break; Also, I get the impression that the first column of ampsecul is a range-based division, so somehow, there would be a binarysearch for the matching slot into ampsecul, not direct indexing (i.e. isecul=4 would select index 2 (2..8) not 4) Are you sure you are getting the source code correctly? I looks very much like there are some custom indexers (operators[](...)) that you misssed out on? This would probably be about the same class/function that contains the terminator check like shown above. Edit from the linked source I get the impression that the code is very much intended as is, and hence isecul should simply not be growing >= 15
{ "language": "en", "url": "https://stackoverflow.com/questions/7548961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL find and replace text I'm working on updating an existing wordpress database and everything is going smoothly. However, the links are still directing to the old site. Is there any way to use a loop or something to run through every record and update http://OLD_URL.com to say http://NEW_URL.com? I might just be too lazy to manually do it but I will if it comes down to it. Thank you. A: I usually run a couple of quick commands in phpmyadmin and I'm done. Here's a blog post that discusses this exact issue: http://www.barrywise.com/2009/02/global-find-and-replace-in-wordpress-using-mysql/ I would read this first: http://codex.wordpress.org/Changing_The_Site_URL to make sure all your bases are covered first. A: If you want to update links in a particular table you can use the query like below: UPDATE TableName SET URL = CASE WHEN URL = 'http://OLD_URL.com' THEN 'http://NEW_URL.com ELSE URL END FROM TableName
{ "language": "en", "url": "https://stackoverflow.com/questions/7548964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display only triangle boundaries on textured surface in vtk? I want to display a surface which is textured. I want the triangles boundaries to be visible over the surface in a different color (lets say red). I have found the following code from the vtk code samples but it does not display the triangle boundaries but the filled triangles. import vtk # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create points points = vtk.vtkPoints() points.InsertNextPoint(1.0,0.0,0.0) points.InsertNextPoint(0.0,0.0,0.0) points.InsertNextPoint(0.0,1.0,0.0) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0,0) triangle.GetPointIds().SetId(1,1) triangle.GetPointIds().SetId(2,2) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints( points ) trianglePolyData.SetPolys( triangles ) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(trianglePolyData) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) # assign actor to the renderer ren.AddActor(actor) # enable user interface interactor iren.Initialize() renWin.Render() iren.Start() Can anybody please let me know that how to display triangle only with the boundaries with a specific color. I ideally i want to display triangles on a textured surface. My data consist of triangles. It might also be possible that the vertices of the triangles which are given to vtk can be made visible. I am coding in python. Thanks a lot A: You need to extract the edges from your vtkPolyData object: edges = vtk.vtkExtractEdges() edges.SetInput(trianglePolyData) edge_mapper = vtk.vtkPolyDataMapper() edge_mapper.SetInput(edges.GetOutput()) edge_actor = vtk.vtkActor() edge_actor.SetMapper(edge_mapper) edge_actor.GetProperty().SetColor(1,0,0) ren.AddActor(edge_actor) vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset() First you must extract the edges via a vtkExtractEdges filter. You map the results of that filter to a vtkPolyData object and construct an actor for that data. We then set the color of the mesh to red by modifying the actor directly. The call to vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset() prevents the edges from fighting with the surfaces (the two geometric objects are coincident and tear through each other due to z-buffer precision issues). For completeness sake, here's the whole code: import vtk # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create points points = vtk.vtkPoints() points.InsertNextPoint(1.0,0.0,0.0) points.InsertNextPoint(0.0,0.0,0.0) points.InsertNextPoint(0.0,1.0,0.0) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0,0) triangle.GetPointIds().SetId(1,1) triangle.GetPointIds().SetId(2,2) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints( points ) trianglePolyData.SetPolys( triangles ) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(trianglePolyData) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) # assign actor to the renderer ren.AddActor(actor) #++++++++++++++++++++++++++++++++++++++++++++++++ # Get the edges from the mesh edges = vtk.vtkExtractEdges() edges.SetInput(trianglePolyData) edge_mapper = vtk.vtkPolyDataMapper() edge_mapper.SetInput(edges.GetOutput()) # Make an actor for those edges edge_actor = vtk.vtkActor() edge_actor.SetMapper(edge_mapper) # Make the actor red (there are other ways of doing this also) edge_actor.GetProperty().SetColor(1,0,0) ren.AddActor(edge_actor) # Avoid z-buffer fighting vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset() #------------------------------------------------ # enable user interface interactor iren.Initialize() renWin.Render() iren.Start()
{ "language": "en", "url": "https://stackoverflow.com/questions/7548966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Format output to 40 characters long per line I'm fairly new to Ruby and I've been searching Google for a few hours now. Does anyone know how to format the output of a print to be no more than 40 characters long? For example: What I want to print: This is a simple sentence. This simple sentence appears on four lines. But I want it formatted as: This is a simple sentence. This simple sentence appears on four lines. I have each line of the original put into an array. so x = ["This is a simple sentence.", "This simple", "sentence appears", "on three lines."] I tried x.each { |n| print n[0..40], " " } but it didn't seem to do anything. Any help would be fantastic! A: The method word_wrap expects a Strind and makes a kind of pretty print. Your array is converted to a string with join("\n") The code: def word_wrap(text, line_width = 40 ) return text if line_width <= 0 text.gsub(/\n/, ' ').gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip end x = ["This is a simple sentence.", "This simple", "sentence appears", "on three lines."] puts word_wrap(x.join("\n")) x << 'a' * 50 #To show what happens with long words x << 'end' puts word_wrap(x.join("\n")) Code explanation: x.join("\n")) build a string, then build one long line with text.gsub(/\n/, ' '). In this special case this two steps could be merged: x.join(" ")) And now the magic happens with gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n") * *(.{1,#{line_width}})): Take any character up to line_width characters. *(\s+|$): The next character must be a space or line end (in other words: the previous match may be shorter the line_width if the last character is no space. *"\\1\n": Take the up to 40 character long string and finish it with a newline. *gsub repeat the wrapping until it is finished. And in the end, I delete leading and trailing spaces with strip I added also a long word (50 a's). What happens? The gsub does not match, the word keeps as it is. A: puts x.join(" ").scan(/(.{1,40})(?:\s|$)/m) This is a simple sentence. This simple sentence appears on three lines. A: Ruby 1.9 (and not overly efficient): >> x.join(" ").each_char.each_slice(40).to_a.map(&:join) => ["This is a simple sentence. This simple s", "entence appears on three lines."] The reason your solution doesn't work is that all the individual strings are shorter than 40 characters, so n[0..40] always is the entire string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ROR deprecation warning desert-0.5.4 So I am getting this error: DEPRECATION WARNING: ActiveSupport::Dependencies.load_paths is deprecated, please use autoload_paths instead. (called from load_paths at /opt/local/lib/ruby/gems/1.8/gems/desert-0.5.4/lib/desert/manager.rb:36) times like a million after call ruby script/server before this warning => Booting WEBrick => Rails 2.3.12 application starting on http://0.0.0.0:3000 and then after the activesupport error I get a bunch of NOTE: Gem.source_index is deprecated, use Specification. It will be removed on or after 2011-11-01. Gem.source_index called from /opt/local/lib/ruby/gems/1.8/gems/rails-2.3.12/lib/rails/gem_dependency.rb:78. and then after all these warnings and notes I get /Users/anthonysierra/.gem/ruby/1.8/gems/bcrypt-ruby-2.1.4/lib/bcrypt_ext.bundle: [BUG] Segmentation fault ruby 1.8.7 (2010-12-23 patchlevel 330) [x86_64-darwin10] Abort trap My questions is how I might add gems or install things in order to get things running? In case you are wondering this is a project I pulled from svn. A: The deprecation warnings have been added to ActiveSupport in version 2.3.9 (source here). They're just that, warnings. For the Gem.source_index note, see this question. The bcrypt error should be solved by reinstalling bcrypt (see related bug here). A: So it looks like what I had to do was add gem 'bcyrpt-ruby', :require => "crypt" to the gemfile and then call sudo gem install bcrypt-ruby :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mock/Stub constructor I have the following code: class Clients constructor : -> @clients = [] createClient : (name)-> client = new Client name @clients.push client I am testing it with Jasmine BDD like this: describe 'Test Constructor', -> it 'should create a client with the name foo', -> clients = new clients clients.createClient 'Foo' Client.should_have_been_called_with 'Foo' it 'should add Foo to clients', -> clients = new clients clients.createClient 'Foo' expect(clients.clients[0]).toEqual SomeStub In my first test I want to check if the constructor is being called with the correct name. In my second I just want to confirm that whatever came out of new Client was added to the array. I am using Jasmine BDD and it has a way to create spies/mocks/stubs but it seems it's not possible to test constructor. So I am looking into a way to test the constructor it would be nice if there is a way that I don't need an extra library but I am open to anything. A: It is possible to stub out constructors in Jasmine, the syntax is just a bit unexpected: spy = spyOn(window, 'Clients'); In other words, you don't stub out the new method, you stub out the class name itself in the context where it lives, in this case window. You can then chain on a andReturn() to return a fake object of your choosing, or a andCallThrough() to call the real constructor. See also: Spying on a constructor using Jasmine A: I think the best plan here is to pull out the creation of the new Client object to a separate method. This will allow you to test the Clients class in isolation and use mock Client objects. I've whipped up some example code, but I haven't tested it with Jasmine. Hopefully you can get the gist of how it works: class Clients constructor: (@clientFactory) -> @clients = [] createClient : (name)-> @clients.push @clientFactory.create name clientFactory = (name) -> new Client name describe 'Test Constructor', -> it 'should create a client with the name foo', -> mockClientFactory = (name) -> clients = new Clients mockClientFactory clients.createClient 'Foo' mockClientFactory.should_have_been_called_with 'Foo' it 'should add Foo to clients', -> someStub = {} mockClientFactory = (name) -> someStub clients = new Clients mockClientFactory clients.createClient 'Foo' expect(clients.clients[0]).toEqual someStub The basic plan is to now use a separate function (clientFactory) to create new Client objects. This factory is then mocked in the tests allowing you to control exactly what is returned, and inspect that it has been called correctly. A: My solution ended up similar to @zpatokal I ended up using a module accross my app (not really big app), and mocking from there. One catch is that and.callThrough won't work, as the constructor is going to be called from the Jasmine method, so I had to do some trickery with and.callFake. On unit.coffee class PS.Unit On units.coffee class PS.Units constructor: -> new PS.Unit And on the spec files: Unit = PS.Unit describe 'Units', -> it 'should create a Unit', -> spyOn(PS, 'Unit').and.callFake -> new Unit arguments... # and.callThrough() expect(PS.Unit).toHaveBeenCalled() A: Clearer solution with recent jasmine version: window.Client = jasmine.createSpy 'Client' clients.createClient 'Foo' expect(window.Client).toHaveBeenCalledWith 'Foo'
{ "language": "en", "url": "https://stackoverflow.com/questions/7548974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: C++ handling specific impl - #ifdef vs private inheritance vs tag dispatch I have some classes implementing some computations which I have to optimize for different SIMD implementations e.g. Altivec and SSE. I don't want to polute the code with #ifdef ... #endif blocks for each method I have to optimize so I tried a couple of other approaches, but unfotunately I'm not very satisfied of how it turned out for reasons I'll try to clarify. So I'm looking for some advice on how I could improve what I have already done. 1.Different implementation files with crude includes I have the same header file describing the class interface with different "pseudo" implementation files for plain C++, Altivec and SSE only for the relevant methods: // Algo.h #ifndef ALGO_H_INCLUDED_ #define ALGO_H_INCLUDED_ class Algo { public: Algo(); ~Algo(); void process(); protected: void computeSome(); void computeMore(); }; #endif // Algo.cpp #include "Algo.h" Algo::Algo() { } Algo::~Algo() { } void Algo::process() { computeSome(); computeMore(); } #if defined(ALTIVEC) #include "Algo_Altivec.cpp" #elif defined(SSE) #include "Algo_SSE.cpp" #else #include "Algo_Scalar.cpp" #endif // Algo_Altivec.cpp void Algo::computeSome() { } void Algo::computeMore() { } ... same for the other implementation files Pros: * *the split is quite straightforward and easy to do *there is no "overhead"(don't know how to say it better) to objects of my class by which I mean no extra inheritance, no addition of member variables etc. *much cleaner than #ifdef-ing all over the place Cons: * *I have three additional files for maintenance; I could put the Scalar implementation in the Algo.cpp file though and end up with just two but the inclusion part will look and fell a bit dirtier *they are not compilable units per-se and have to be excluded from the project structure *if I do not have the specific optimized implementation yet for let's say SSE I would have to duplicate some code from the plain(Scalar) C++ implementation file *I cannot fallback to the plain C++ implementation if nedded; ? is it even possible to do that in the described scenario ? *I do not feel any structural cohesion in the approach 2.Different implementation files with private inheritance // Algo.h class Algo : private AlgoImpl { ... as before } // AlgoImpl.h #ifndef ALGOIMPL_H_INCLUDED_ #define ALGOIMPL_H_INCLUDED_ class AlgoImpl { protected: AlgoImpl(); ~AlgoImpl(); void computeSomeImpl(); void computeMoreImpl(); }; #endif // Algo.cpp ... void Algo::computeSome() { computeSomeImpl(); } void Algo::computeMore() { computeMoreImpl(); } // Algo_SSE.cpp AlgoImpl::AlgoImpl() { } AlgoImpl::~AlgoImpl() { } void AlgoImpl::computeSomeImpl() { } void AlgoImpl::computeMoreImpl() { } Pros: * *the split is quite straightforward and easy to do *much cleaner than #ifdef-ing all over the place *still there is no "overhead" to my class - EBCO should kick in *the semantic of the class is much more cleaner at least comparing to the above that is private inheritance == is implemented in terms of *the different files are compilable, can be included in the project and selected via the build system Cons: * *I have three additional files for maintenance *if I do not have the specific optimized implementation yet for let's say SSE I would have to duplicate some code from the plain(Scalar) C++ implementation file *I cannot fallback to the plain C++ implementation if nedded 3.Is basically method 2 but with virtual functions in the AlgoImpl class. That would allow me to overcome the duplicate implementation of plain C++ code if needed by providing an empty implementation in the base class and override in the derived although I will have to disable that behavior when I actually implement the optimized version. Also the virtual functions will bring some "overhead" to objects of my class. 4.A form of tag dispatching via enable_if<> Pros: * *the split is quite straightforward and easy to do *much cleaner than #ifdef ing all over the place *still there is no "overhead" to my class *will eliminate the need for different files for different implementations Cons: * *templates will be a bit more "cryptic" and seem to bring an unnecessary overhead(at least for some people in some contexts) *if I do not have the specific optimized implementation yet for let's say SSE I would have to duplicate some code from the plain(Scalar) C++ implementation *I cannot fallback to the plain C++ implementation if needed What I couldn't figure out yet for any of the variants is how to properly and cleanly fallback to the plain C++ implementation. Also I don't want to over-engineer things and in that respect the first variant seems the most "KISS" like even considering the disadvantages. A: You could use a policy based approach with templates kind of like the way the standard library does for allocators, comparators and the like. Each implementation has a policy class which defines computeSome() and computeMore(). Your Algo class takes a policy as a parameter and defers to its implementation. template <class policy_t> class algo_with_policy_t { policy_t policy_; public: algo_with_policy_t() { } ~algo_with_policy_t() { } void process() { policy_.computeSome(); policy_.computeMore(); } }; struct altivec_policy_t { void computeSome(); void computeMore(); }; struct sse_policy_t { void computeSome(); void computeMore(); }; struct scalar_policy_t { void computeSome(); void computeMore(); }; // let user select exact implementation typedef algo_with_policy_t<altivec_policy_t> algo_altivec_t; typedef algo_with_policy_t<sse_policy_t> algo_sse_t; typedef algo_with_policy_t<scalar_policy_t> algo_scalar_t; // let user have default implementation typedef #if defined(ALTIVEC) algo_altivec_t #elif defined(SSE) algo_sse_t #else algo_scalar_t #endif algo_default_t; This lets you have all the different implementations defined within the same file (like solution 1) and compiled into the same program (unlike solution 1). It has no performance overheads (unlike virtual functions). You can either select the implementation at run time or get a default implementation chosen by the compile time configuration. template <class algo_t> void use_algo(algo_t algo) { algo.process(); } void select_algo(bool use_scalar) { if (!use_scalar) { use_algo(algo_default_t()); } else { use_algo(algo_scalar_t()); } } A: If the virtual function overhead is acceptable, option 3 plus a few ifdefs seems a good compromise IMO. There are two variations that you could consider: one with abstract base class, and the other with the plain C implementation as the base class. Having the C implementation as the base class lets you gradually add the vector optimized versions, falling back on the non-vectorized versions as you please, using an abstract interface would be a little cleaner to read. Also, having separate C++ and vectorized versions of your class let you easily write unit tests that * *Ensure that the vectorized code is giving the right result (easy to mess this up, and vector floating registers can have different precision than FPU, causing different results) *Compare the performance of the C++ vs the vectorized. It's often good to make sure the vectorized code is actually doing you any good. Compilers can generate very tight C++ code that sometimes does as well or better than vectorized code. Here's one with the plain-c++ implementations as the base class. Adding an abstract interface would just add a common base class to all three of these: // Algo.h: class Algo_Impl // Default Plain C++ implementation { public: virtual ComputeSome(); virtual ComputeSomeMore(); ... }; // Algo_SSE.h: class Algo_Impl_SSE : public Algo_Impl // SSE { public: virtual ComputeSome(); virtual ComputeSomeMore(); ... }; // Algo_Altivec.h: class Algo_Impl_Altivec : public Algo_Impl // Altivec implementation { public: virtual ComputeSome(); virtual ComputeSomeMore(); ... }; // Client.cpp: Algo_Impl *myAlgo = 0; #ifdef SSE myAlgo = new Algo_Impl_SSE; #elseif defined(ALTIVEC) myAlgo = new Algo_Impl_Altivec; #else myAlgo = new Algo_Impl_Default; #endif ... A: As requested in the comments, here's a summary of what I did: Set up policy_list helper template utility This maintains a list of policies, and gives them a "runtime check" call before calling the first suitable implementaiton #include <cassert> template <typename P, typename N=void> struct policy_list { static void apply() { if (P::runtime_check()) { P::impl(); } else { N::apply(); } } }; template <typename P> struct policy_list<P,void> { static void apply() { assert(P::runtime_check()); P::impl(); } }; Set up specific policies These policies implement a both a runtime test and an actual implementation of the algorithm in question. For my actual problem impl took another template parameter that specified what exactly it was they were implementing, here though the example assumes there is only one thing to be implemented. The runtime tests are cached in a static bool for some (e.g. the Altivec one I used) the test was really slow. For others (e.g. the OpenCL one) the test is actually "is this function pointer NULL?" after one attempt at setting it with dlsym(). #include <iostream> // runtime SSE detection (That's another question!) extern bool have_sse(); struct sse_policy { static void impl() { std::cout << "SSE" << std::endl; } static bool runtime_check() { static bool result = have_sse(); // have_sse lives in another TU and does some cpuid asm stuff return result; } }; // Runtime OpenCL detection extern bool have_opencl(); struct opencl_policy { static void impl() { std::cout << "OpenCL" << std::endl; } static bool runtime_check() { static bool result = have_opencl(); // have_opencl lives in another TU and does some LoadLibrary or dlopen() return result; } }; struct basic_policy { static void impl() { std::cout << "Standard C++ policy" << std::endl; } static bool runtime_check() { return true; } // All implementations do this }; Set per architecture policy_list Trivial example sets one of two possible lists based on ARCH_HAS_SSE preprocessor macro. You might generate this from your build script, or use a series of typedefs, or hack support for "holes" in the policy_list that might be void on some architectures skipping straight to the next one, without trying to check for support. GCC sets some preprocessor macors for you that might help, e.g. __SSE2__. #ifdef ARCH_HAS_SSE typedef policy_list<opencl_policy, policy_list<sse_policy, policy_list<basic_policy > > > active_policy; #else typedef policy_list<opencl_policy, policy_list<basic_policy > > active_policy; #endif You can use this to compile multiple variants on the same platform too, e.g. and SSE and no-SSE binary on x86. Use the policy list Fairly straightforward, call the apply() static method on the policy_list. Trust that it will call the impl() method on the first policy that passes the runtime test. int main() { active_policy::apply(); } If you take the "per operation template" approach I mentioned earlier it might be something more like: int main() { Matrix m1, m2; Vector v1; active_policy::apply<matrix_mult_t>(m1, m2); active_policy::apply<vector_mult_t>(m1, v1); } In that case you end up making your Matrix and Vector types aware of the policy_list in order that they can decide how/where to store the data. You can also use heuristics for this too, e.g. "small vector/matrix lives in main memory no matter what" and make the runtime_check() or another function test the appropriateness of a particular approach to a given implementation for a specific instance. I also had a custom allocator for containers, which produced suitably aligned memory always on any SSE/Altivec enabled build, regardless of if the specific machine had support for Altivec. It was just easier that way, although it could be a typedef in a given policy and you always assume that the highest priority policy has the strictest allocator needs. Example have_altivec(): I've included a sample have_altivec() implementation for completeness, simply because it's the shortest and therefore most appropriate for posting here. The x86/x86_64 CPUID one is messy because you have to support the compiler specific ways of writing inline ASM. The OpenCL one is messy because we check some of the implementation limits and extensions too. #if HAVE_SETJMP && !(defined(__APPLE__) && defined(__MACH__)) jmp_buf jmpbuf; void illegal_instruction(int sig) { // Bad in general - https://www.securecoding.cert.org/confluence/display/seccode/SIG32-C.+Do+not+call+longjmp%28%29+from+inside+a+signal+handler // But actually Ok on this platform in this scenario longjmp(jmpbuf, 1); } #endif bool have_altivec() { volatile sig_atomic_t altivec = 0; #ifdef __APPLE__ int selectors[2] = { CTL_HW, HW_VECTORUNIT }; int hasVectorUnit = 0; size_t length = sizeof(hasVectorUnit); int error = sysctl(selectors, 2, &hasVectorUnit, &length, NULL, 0); if (0 == error) altivec = (hasVectorUnit != 0); #elif HAVE_SETJMP_H void (*handler) (int sig); handler = signal(SIGILL, illegal_instruction); if (setjmp(jmpbuf) == 0) { asm volatile ("mtspr 256, %0\n\t" "vand %%v0, %%v0, %%v0"::"r" (-1)); altivec = 1; } signal(SIGILL, handler); #endif return altivec; } Conclusion Basically you pay no penalty for platforms that can never support an implementation (the compiler generates no code for them) and only a small penalty (potentially just a very predictable by the CPU test/jmp pair if your compiler is half-decent at optimising) for platforms that could support something but don't. You pay no extra cost for platforms that the first choice implementation runs on. The details of the runtime tests vary between the technology in question. A: You may consider to employ adapter patterns. There are a few types of adapters and it's quite an extensible concept. Here is an interesting article Structural Patterns: Adapter and Façade that discusses very similar matter to the one in your question - the Accelerate framework as an example of the Adapter patter. I think it is a good idea to discuss a solution on the level of design patterns without focusing on implementation detail like C++ language. Once you decide that the adapter states the right solutiojn for you, you can look for variants specific to your implemementation. For example, in C++ world there is known adapter variant called generic adapter pattern. A: This isn't really a whole answer: just a variant on one of your existing options. In option 1 you've assumed that you include algo_altivec.cpp &c. into algo.cpp, but you don't have to do this. You could omit algo.cpp entirely, and have your build system decide which of algo_altivec.cpp, algo_sse.cpp, &c. to build. You'd have to do something like this anyway whichever option you use, since each platform can't compile every implementation; my suggestion is only that whichever option you choose, instead of having #if ALTIVEC_ENABLED everywhere in the source, where ALTIVEC_ENABLED is set from the build system, you just have the build system decide directly whether to compile algo_altivec.cpp . This is a bit trickier to achieve in MSVC than make, scons, &c., but still possible. It's commonplace to switch in a whole directory rather than individual source files; that is, instead of algo_altivec.cpp and friends, you'd have platform/altivec/algo.cpp, platform/sse/algo.cpp, and so one. This way, when you have a second algorithm you need platform-specific implementations for, you can just add the extra source file to each directory. Although my suggestion's mainly intended to be a variant of option 1, you can combine this with any of your options, to let you decide in the build system and at runtime which options to offer. In that case, though, you'll probably need implementation-specific header files too. A: In order to hide the implementation details you may just use an abstract interface with static creator and provide three 3 implementation classes: // --------------------- Algo.h --------------------- #pragma once typedef boost::shared_ptr<class Algo> AlgoPtr; class Algo { public: static AlgoPtr Create(std::string type); ~Algo(); void process(); protected: virtual void computeSome() = 0; virtual void computeMore() = 0; }; // --------------------- Algo.cpp --------------------- class PlainAlgo: public Algo { ... }; class AltivecAlgo: public Algo { ... }; class SSEAlgo: public Algo { ... }; static AlgoPtr Algo::Create(std::string type) { /* Factory implementation */ } Please note, that since PlainAlgo, AlivecAlgo and SSEAlgo classes are defined in Algo.cpp, they are only seen from this compilation unit and therefore the implementation details hidden from the outside world. Here is how one can use your class then: AlgoPtr algo = Algo::Create("SSE"); algo->Process(); A: It seems to me that your first strategy, with separate C++ files and #including the specific implementation, is the simplest and cleanest. I would only add some comments to your Algo.cpp indicating which methods are in the #included files. e.g. // Algo.cpp #include "Algo.h" Algo::Algo() { } Algo::~Algo() { } void Algo::process() { computeSome(); computeMore(); } // The following methods are implemented in separate, // platform-specific files. // void Algo::computeSome() // void Algo::computeMore() #if defined(ALTIVEC) #include "Algo_Altivec.cpp" #elif defined(SSE) #include "Algo_SSE.cpp" #else #include "Algo_Scalar.cpp" #endif A: Policy-like templates (mixins) are fine until the requirement to fall back to default implementation. It's runtime opeation and should be handled by runtime polymorphism. Strategy pattern can handle this fine. There's one drawback of this approach: Strategy-like algorithm implemented cannot be inlined. Such inlining can provide reasonable performance improvement in rare cases. If this is an issue you'll need to cover higher-level logic by Strategy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Image align with text -CSS/HTML I need your help - I have this CSS and HTML; I need the text to align to the right of the image. But for some reason, they keep pushing to the bottom of the image. What I'm looking for infact is to have the details next to the image in a grid from left to right. Here's my code <html> <head> <style type="text/css"> #container { font-size: 12px; font-family: 'Lucida Grande',Verdana,sans-serif; text-align: center; } #container a.name_link{ text-decoration: none; color: #8E190B; font-weight: bold; padding-bottom: 8px; } #image { width:100px; height:104px; border: 2px solid #e9e3dd; float:left;} #text { padding-top: 5px; padding-bottom:5px; } .horizontal_banner {float:left; margin: 2px; padding: 4px 2px 10px 10px; } </style> </head> <body> <div class="horizontal_banner"> <div id="container"> <a href="details.php?id=42"> <img src="uploads/Lisa.jpg" id="image" title="Lisa"/></a> </div> <div id="name_container"> <a class="name_link" href="details.php?id=42">Lisa</a> </div> <div id="text">Not available</div> <div id="text">Not Specified</div> <div id="text">Female</div> </div> <div class="horizontal_banner"> <div id="container"> <a href="details.php?id=23"> <img src="uploads/Lucky.jpg" id="image" title="Lucky" /></a> </div> <div id="name_container"> <a class="name_link" href="details.php?id=23">Lucky</a> </div> <div id="text">Employed</div> <div id="text">25 Years</div> <div id="text">Male</div> </div> </body> </html> Any help will be greatly appreciated. A: To do so, you need to specify a fixed width to .horizontal_banner . 200x worked for me when I tried your example. A: Something like this? http://jsfiddle.net/CvZWG/ I added new rules to .horizontal_banner to make them float left. Also, you're using the text id on divs multiple times in your HTML. IDs are supposed to be unique, if you want to use it multiple times you should use class instead of id. A: You have a number of options depending on how long the text is. However, looking at your code I would suggest... you kill all those id's and make them classes, the interpreter balks at multiple id's with the same name, that's issue number 1. Issue 2, float: the to the left, since it's a block element, and give it a height and width. It's good practice to give anything that is floating an height and a width so the browser knows what it's working with. Don't forget clearance for margin and padding, you might want to consider some reset.css rules if you haven't set that up yet. http://sixrevisions.com/css/css-tips/css-tip-1-resetting-your-styles-with-css-reset/ Issue 3, you might have to go as far as floating those "text" divs right, although you might want to consider a or for this situation since all that data looks the same and will be a child of the same class. http://www.codingforums.com/showthread.php?t=186697 Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with XSLT and apply templates I'm going to be brief. I'm doing XSLT on the client. The output is a report/html with data. The report consists of several blocks, ie one block is one child element of root-node in the xml file. There are n reports residing in n different xslt-files in my project and the reports can have the same block. That means if there is a problem with one block for one report and it is in n reports i have to update every n report (xslt file). So i want to put all my blocks in templates (kind-of-a businesslayer) that i can reuse for my reports by xsl:include on the templates for those reports. So the pseudo is something like this: <?xml version="1.0".....?> <xsl:stylesheet version="1.0"....> <xsl:include href="../../Blocks/MyBlock.xslt"/> <xsl:template match='/'> <xsl:apply-templates /> </xsl:template> </xsl:stylesheet> MyBlock.xslt: <?xml version="1.0"....?> <xsl:stylesheet version="1.0".....> <xsl:template match='/root/rating'> HTML OUTPUT </xsl:template> </xsl:stylesheet> I hope someone out there understands my question. I need pointers on how to go about this, if this is one way to do it. But it doesn't seem to work. A: Below is my experience that how am dealing this. This is example which I modified your code. <?xml version="1.0"?> <xsl:stylesheet version="1.0"> <xsl:include href="../../Blocks/MyBlock.xslt"/> <xsl:template match="/"> <xsl:apply-templates select="node()" mode="callingNode1"/> </xsl:template> </xsl:stylesheet> MyBlock.xslt: <?xml version="1.0"?> <xsl:stylesheet version="1.0"> <xsl:template mode="callingNode1" match="*"> HTML OUTPUT </xsl:template> <xsl:template mode="callingNode2" match="/root/rating"> HTML OUTPUT </xsl:template> </xsl:stylesheet> Here am calling the nodes based on the mode & match.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ignoring mass from welded joints in box2d What I have is a circle that rolls over other objects and 'picks' them up. My current setup uses WeldJoint to join and place the picked up object at the circle's edge. I then edit these object's fixtures to become a sensor to avoid collision response. The circle is pushed around using applyForceToCenter() and a slight impulse to get it going. This all works. The problem is that the the accumulating mass from the new bodies is limiting the main circle's movement. Too realistic for my game. The bodies keep tugging the circle around. I want to zero out any physics-based attributes affecting the circle. I've tried a variety of methods using resetMassData(), MassData.mass = 0, setAwake(false), setActive(false) ... Any help is appreciated, thanks. Edit: I've thought about using a math function to spiral the object's around the circle, e.g. Make a sprite go in a circle. I'm not so sure if that's the route to go with box2d in hand. A: When you are using weld joints, you aren't deleting any of the bodies (which have their own mass) as you attach them to your circle. Since you are content to simply assume that once something becomes stuck to the circle that it no longer needs to collide with anything, a good solution would be to add them as sensors to your circle body. This will require you to delete the body and add the fixture to your circle. I think it would be cool to have more objects result in more mass for your circle. Why not make a routine that determines the total additional mass currently stuck on your ball, and scale your ball's push force accordingly? You'll end up with the same acceleration but you will get a realistic increase in collision forces generated for free. Not only that, but your welded sensors will also effectively modify the inertia so your ball's center-of-gravity will now reflect how things are stuck on it! It's free realism, so I'd try to take advantage of it. Plus it will be easier than writing code to correctly move the fixtures. You could also in addition reduce the density of a newly "stuck-on" object by some factor to reduce the effect as necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Node.js tcp socket server on multiple machines I have a node.js tcp server that is used as a backend to an iPhone chat client. Since my implementation includes private group chats I store a list of users and what chat room they belong to in memory in order to route messages appropriately. This all works for fine assuming my chat server will always be on one machine, but when/if I need to scale horizontally I need a good way of broadcasting messages to clients that connect to different servers. I don't want to start doing inter-process communication between node servers and would prefer sharing state with redis. I have a few ideas but I'm wondering if anyone has a good solution for this? To be clear here is an example: User 1 connects to server 1 on room X, user 2 connects to server 2 on room X. User 1 sends a message, I need this to be passed to user 2, but since I am using an in memory data structure the servers don't share state. I want my node servers to remain as dumb as possible so I can just add/remove to the needs of my system. Thanks :) A: You could use a messaging layer (using something like pub/sub) that spans the processes: Message Queue ------------------------------------------------------------------------------- | | ServerA ServerB ------- ------- Room 1: User1, User2 Room 1: User3, User5 Room 2: User4, User7, User11 Room 2: User6, User8 Room 3: User9, User13 Room 3: User10, User12, User14 Let's say User1 sends a chat message. ServerA sends a message on the message queue that says "User1 in Room 1 said something" (along with whatever they said). Each of your other server processes listens for such events, so, in this example, ServerB will see that it needs to distribute the message from User1 to all users in its own Room 1. You can scale to many processes in this way--each new process just needs to make sure they listen to appropriate messages on the queue. Redis has pub/sub functionality that you may be able to use for this if you're already using Redis. Additionaly, there are other third-party tools for this kind of thing, like ZeroMQ; see also this question. A: Redis is supposed to have built in cluster support in the near future, in the mean time you can use a consistent hashing algorithm to distribute your keys evenly across multiple servers. Someone out there has a hashing module for node.js, which was written specifically to implement consistent hashing for a redis cluster module for node.js. You might want to key off the 'room' name to ensure that all data points for a room wind up on the same host. With this type of setup all the logic for which server to use remains on the client, so your redis cluster can basically remain the same and you can easily add or remove hosts. Update I found the consistent hashing implementation for redis I was talking about, it gives the code of course, and also explains sharding in an easy to digest way. http://ngchi.wordpress.com/2010/08/23/towards-auto-sharding-in-your-node-js-app/
{ "language": "en", "url": "https://stackoverflow.com/questions/7548989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: The object assignment doesn't make sense in PHP OOP I was tested and I got this wrong but this doesn't make sense: class myClass { public $x; function myMethod() { echo $this->x; } } $a = new myClass(); $a->x = 10; $b = $a; $b->x = 20; $c = clone $b; $c->x = 30; $a->myMethod(); $b->myMethod(); $c->myMethod(); My intuition would be 102030 but the result is actually 202030!!! What happened to 10?!?! Shouldn't the variable of $a be left alone? I thought all objects are independent and would not be updated unless it has direct reference set by the ampersand (=&)? A: In $b = $a;, only the object reference is being copied, not the object. When you use clone, however, the object is indeed being copied, so $c = clone $b, creates both a new object (referenced by $c) and a new reference ($c). In $b =& $a;, both symbols $a and $b would point to the same reference, that is, not even the reference would be copied (and therefore an assignment to $b of, say, an integer, would also affect the value of $a). To sum up, there are two indirections here: from the symbol to the "zval" (in the case an object reference) and from the object reference to the object itself (i.e., to a portion of memory where the actual object state is stored). A: From the PHP manual: When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it. A: PHP uses references for objects. So when you create a new one $a = new myClass(); PHP doesn't actually store it in $a, it just puts the reference there. Now you copy the reference: $b = $a; When you modify the object pointed by $a, you also modify the one pointed by $b because they point to the same thing. A: As $a represents a reference to an object and not the object itself, you are assigning the reference to $b. Now, $a and $b reference the same object, when you manipulate the object referenced by $b, the changes get reflected accessing it via $a as well. A: Objects are handled by reference, and references are aliases on assignment. So after you say $b = $a, both variables refer to the same object. The value/reference distinction is fundamental in many "modern" OO languages: values are copied, references are aliased. It is perhaps unfortunate that the syntax of the language does not always make it obvious which semantics the variable obeys at any given point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .htpasswd without .htaccess I would like to protect a web folder via .htpasswd. However, as the .htaccess file is under version control, I would prefer to not mess with it. Instead, I would like to have the configuration in /etc/apache2/sites-enabled/mysite /etc/apache2/.htpasswd Any idea what I need to put in the "mysite" apache configuration file? So far it is sth like this, <VirtualHost (ip address):80> ServerName my.domain DocumentRoot /var/sites/sitename ServerAdmin ... </VirtualHost> A: Heureka, I figured it out myself.. or what I think to be the solution. <VirtualHost (ip address):80> ServerName my.domain DocumentRoot /var/sites/sitename/ ServerAdmin ... <Directory /var/sites/sitename/> AuthUserFile /etc/apache2/.htpasswd AuthGroupFile /dev/null AuthName "What is the pw" AuthType Basic require user (username) </Directory> </VirtualHost> The .htpasswd can be created in the usual way via commandline, # htpasswd /etc/apache2/.htpasswd (username) EDIT: anthony in the comment below strongly recommends you use https/SSL, to prevent the password from being sent unencrypted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the "Ruby way" to align variable assignments? (code style question) Say i have this untainted code: some_var = Hash.new some_var[:name] = "blah" some_var[:address] = "101 blahblah lane" another = "Olly olly oxen free!" What is the ruby way of making it pretty? option 1: Leave it as is option 2: Align related things some_var = Hash.new some_var[:name] = "blah" some_var[:address] = "101 blahblah lane" another = "Olly olly oxen free!" option 3: Align all the things some_var = Hash.new some_var[:name] = "blah" some_var[:address] = "101 blahblah lane" another = "Olly olly oxen free!" option 4: ????? Thanks!! A: Using Hashes as in your example I would do another version: some_var = { :name => "blah", :address => "101 blahblah lane", } another = "Olly olly oxen free!" or with Ruby 1.9 some_var = { name: "blah", address: "101 blahblah lane", } another = "Olly olly oxen free!" A: I really don't like #2 or #3. When you align stuff like that, you are grouping things together. Even if they are "symmetrical", that is totally not what you want in variable assignment. like a = 1 foobar = 2 baz = 3 visually, you are grouping a, foobar, and baz, and grouping 1, 2, and 3. Even if 1, 2, and 3 are related, they should still be grouped with their labels, showing they are related can be accomplished by effective whitespace around the assignments. Now, datastructures are an example of something you DO want to group some_method([[1, "foo"], [2, "bar"], [3, "baz"]]) is (imo) way harder to read then some_method([[1, "foo"], [2, "bar"], [3, "baz"]]) This is sort of situational, but I have a #4 for you. some_var = Hash.new.tap do |h| h[:name] = "blah" h[:address] = "101 blahblah lane" end another = "Olly olly oxen free!" Object#tap will yield the thing you tap into the block, and evaluate the block to be the thing that you tapped. So in that example, Hash.new gets yielded in, modified by the block, and then returned to be assigned to some_var. Some people I work with absolutely hates it, but I find it does a fantastic job of saying "Everything in here is directly related to initializing this expression" A: IMHO 1 would be the most common one, but I've definitely seen 2. Plus the latter one is also mentioned in at least one style guide: When multiple symmetrical assignments are on lines one after another, align their assignment operators. On the other hand, do not align assignment operators of unrelated assignments which look similar just by coincidence. Rationale: Alignment helps reader recognize that the assignments are related or symmetrical. http://en.opensuse.org/openSUSE:Ruby_coding_conventions#Assignment
{ "language": "en", "url": "https://stackoverflow.com/questions/7548997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NC flag in htaccess causing Internal Server Error Whenever I add the [NC] flag in .htaccess, it causes an Internal Server Error. This works: Redirect 301 /gabf http://www.mydomain.com/category/gabf but this doesn't: Redirect 301 /gabf http://www.mydomain.com/category/gabf [NC] How can I allow things like /gabf, /GABF, /Gabf, etc? A: Use this code: RewriteEngine ON RewriteRule ^gabf/?$ http://www.domain.com/category/gabf [R=301,NC,L] before: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> Wordpress overwrite all RewriteRule to index.php. If you put that first, this "gabf" rule will be executed first and since it's the last rule it will stop. R=301 = Redirect Permanent and NC = No Case (case insensitive)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make whole table cell clickable but vertical align text inside it - CSS How to make whole table cell clickable but vertical align text inside it. Alright it is achievable by making link display:block and setting line height. But the problem is text may get 2 lines some times. So this way is not solution. Are there any other solution ? thank you. A: You could do this by adding a class to the cell you want to click and hooking this up using jquery such as <td class="clickable">...</td> your jquery... $('.clickable').click(function() { alert('Table cell has been clicked'); }); A: Yes you could do that but I usually need each cell to do something different or to send a different piece of data for each cell. So I use something like this. <td onclick="update_calendar(1337317200);">19</td>
{ "language": "en", "url": "https://stackoverflow.com/questions/7549004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Redmine internal error I get an internal error trying to access "My account" in Redmine. But after reloading the page there is no internal error and I can access the page. Here is the information from Redmine log: Processing MyController#account (for 91.90.15.48 at 2011-09-26 01:10:20) [GET] Parameters: {"action"=>"account", "controller"=>"my"} Rendering template within layouts/base Rendering my/account ActionView::TemplateError (uninitialized constant ActiveSupport::TimeZone::TZInfo) on line #3 of app/views/users/_preferences.html.erb: 1: <% fields_for :pref, @user.pref, :builder => TabularFormBuilder, :lang => current_language do |pref_fields| %> 2: <%= pref_fields.check_box :hide_mail %> 3: <%= pref_fields.select :time_zone, ActiveSupport::TimeZone.all.collect {|z| [ z.to_s, z.name ]}, :include_blank => true %> 4: <%= pref_fields.select :comments_sorting, [[l(:label_chronological_order), 'asc'], [l(:label_reverse_chronological_order), 'desc']] %> 5: <%= pref_fields.check_box :warn_on_leaving_unsaved %> 6: <% end %> app/views/users/_preferences.html.erb:3 app/views/users/_preferences.html.erb:1 app/views/my/account.rhtml:40:in _run_rhtml_app47views47my47account46rhtml' app/views/my/account.rhtml:8:in _run_rhtml_app47views47my47account46rhtml' passenger (2.2.15) lib/phusion_passenger/rack/request_handler.rb:92:in process_request' passenger (2.2.15) lib/phusion_passenger/abstract_request_handler.rb:207:inmain_loop' passenger (2.2.15) lib/phusion_passenger/railz/application_spawner.rb:441:in start_request_handler' passenger (2.2.15) lib/phusion_passenger/railz/application_spawner.rb:381:in handle_spawn_application' passenger (2.2.15) lib/phusion_passenger/utils.rb:252:in safe_fork' passenger (2.2.15) lib/phusion_passenger/railz/application_spawner.rb:377:in handle_spawn_application' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:352:in __send__' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:352:in main_loop' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:196:in start_synchronously' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:163:in start' passenger (2.2.15) lib/phusion_passenger/railz/application_spawner.rb:222:in start' passenger (2.2.15) lib/phusion_passenger/railz/framework_spawner.rb:291:in handle_spawn_application' passenger (2.2.15) lib/phusion_passenger/abstract_server_collection.rb:126:in lookup_or_add' passenger (2.2.15) lib/phusion_passenger/railz/framework_spawner.rb:286:in handle_spawn_application' passenger (2.2.15) lib/phusion_passenger/abstract_server_collection.rb:80:in synchronize' passenger (2.2.15) lib/phusion_passenger/abstract_server_collection.rb:79:in synchronize' passenger (2.2.15) lib/phusion_passenger/railz/framework_spawner.rb:284:in handle_spawn_application' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:352:in send' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:352:in main_loop' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:196:in start_synchronously' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:163:in start' passenger (2.2.15) lib/phusion_passenger/railz/framework_spawner.rb:101:instart' passenger (2.2.15) lib/phusion_passenger/spawn_manager.rb:253:in spawn_rails_application' passenger (2.2.15) lib/phusion_passenger/abstract_server_collection.rb:126:in lookup_or_add' passenger (2.2.15) lib/phusion_passenger/spawn_manager.rb:247:in spawn_rails_application' passenger (2.2.15) lib/phusion_passenger/abstract_server_collection.rb:80:in synchronize' passenger (2.2.15) lib/phusion_passenger/abstract_server_collection.rb:79:in synchronize' passenger (2.2.15) lib/phusion_passenger/spawn_manager.rb:246:in spawn_rails_application' passenger (2.2.15) lib/phusion_passenger/spawn_manager.rb:145:in spawn_application' passenger (2.2.15) lib/phusion_passenger/spawn_manager.rb:278:in handle_spawn_application' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:352:in __send__' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:352:in main_loop' passenger (2.2.15) lib/phusion_passenger/abstract_server.rb:196:in `start_synchronously' Rendering /home/eosweb/rails_apps/Redmine/public/500.html (500 Internal Server Error) Processing TimeTrackersController#render_menu (for 95.81.29.50 at 2011-09-26 01:10:26) [POST] Parameters: {"action"=>"render_menu", "authenticity_token"=>"Shjxnqzbk2l3hFzHQIAoibBQLfgKwmOnC5p0XMh4P/g=", "controller"=>"time_trackers"} Completed in 14ms (View: 10, DB: 1) | 200 OK [http://redmine.eos-soft.com/time_trackers/render_menu] Processing MyController#account (for 91.90.15.48 at 2011-09-26 01:10:32) [GET] Parameters: {"action"=>"account", "controller"=>"my"} Rendering template within layouts/base Rendering my/account Completed in 49ms (View: 46, DB: 0) | 200 OK [http://redmine.eos-soft.com/my/account] What can be wrong? A: Since Redmine does not use Bundler, it's easy for new or updated gems that get installed on the system to cause errors like this. I got the same error and solved it by putting Redmine on Bundler. Bundler keeps gems that are installed but not in the Gemfile from inadvertently being included in the Rails app. Assuming the new gems that were installed were put there intentionally, you'll want to use bundler to keep Redmine from loading them. If that's not the case, maybe you should just see if the tzinfo gem got installed and uninstall it. To use bundler, first install the bundler gem gem install bundler Then follow the instructions at http://gembundler.com/rails23.html You can look at https://github.com/SciMed/redmine/commit/e94b607b3d9843085c178057702199a819d3725a as an example of the changes you'll to the Redmine app for bundler. Be sure to include rails and whatever database adapter you're using in your gemfile (in my case, pg for postgresql). Restart your app, and this issue should go away.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scala-redis requires sbt 0.10.1 (other versions don't work) - is that normal? While trying out the Scala bindings for Redis, I followed the instructions in the README file (clone the repo, cd into it, type sbt) and I got this: $ sbt Getting org.scala-tools.sbt sbt_2.9.1 0.10.1 ... :: problems summary :: :::: WARNINGS module not found: org.scala-tools.sbt#sbt_2.9.1;0.10.1 ==== local: tried /Users/noah/.ivy2/local/org.scala-tools.sbt/sbt_2.9.1/0.10.1/ivys/ivy.xml -- artifact org.scala-tools.sbt#sbt_2.9.1;0.10.1!sbt_2.9.1.jar: /Users/noah/.ivy2/local/org.scala-tools.sbt/sbt_2.9.1/0.10.1/jars/sbt_2.9.1.jar ==== Maven2 Local: tried file:///Users/noah/.m2/repository/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.pom -- artifact org.scala-tools.sbt#sbt_2.9.1;0.10.1!sbt_2.9.1.jar: file:///Users/noah/.m2/repository/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.jar ==== typesafe-ivy-releases: tried http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt_2.9.1/0.10.1/ivys/ivy.xml -- artifact org.scala-tools.sbt#sbt_2.9.1;0.10.1!sbt_2.9.1.jar: http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt_2.9.1/0.10.1/jars/sbt_2.9.1.jar ==== Maven Central: tried http://repo1.maven.org/maven2/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.pom -- artifact org.scala-tools.sbt#sbt_2.9.1;0.10.1!sbt_2.9.1.jar: http://repo1.maven.org/maven2/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.jar ==== Scala-Tools Maven2 Repository: tried http://scala-tools.org/repo-releases/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.pom -- artifact org.scala-tools.sbt#sbt_2.9.1;0.10.1!sbt_2.9.1.jar: http://scala-tools.org/repo-releases/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.jar ==== Scala-Tools Maven2 Snapshots Repository: tried http://scala-tools.org/repo-snapshots/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.pom -- artifact org.scala-tools.sbt#sbt_2.9.1;0.10.1!sbt_2.9.1.jar: http://scala-tools.org/repo-snapshots/org/scala-tools/sbt/sbt_2.9.1/0.10.1/sbt_2.9.1-0.10.1.jar :::::::::::::::::::::::::::::::::::::::::::::: :: UNRESOLVED DEPENDENCIES :: :::::::::::::::::::::::::::::::::::::::::::::: :: org.scala-tools.sbt#sbt_2.9.1;0.10.1: not found :::::::::::::::::::::::::::::::::::::::::::::: :: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS unresolved dependency: org.scala-tools.sbt#sbt_2.9.1;0.10.1: not found Error during sbt execution: Error retrieving required libraries (see /Users/noah/.sbt/boot/update.log for complete log) Error: Could not retrieve sbt 0.10.1 This was using sbt 0.7.4. I tried downloading the latest version of sbt (0.11.0) and I got the same problem. Then I manually downloaded sbt-launcher.jar from the 0.10.1 release of sbt, and that worked. My question is: is sbt supposed to automatically download the required version of itself, or am I going to have to manually download & run different versions of sbt for packages which require different versions? A: The error message seems unrelated to Redis. Yes, SBT is supposed to download the appropriate version of itself. You can find out what versions of SBT are available by pointing your browser to: http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/ You will see that Scala 2.8.1 is tied to SBT versions <= 0.10.1, whereas Scala 2.9.1 is (currently) compatible with SBT 0.11.0 only. You're getting this error message because somehow you're trying to get SBT 0.10.1 for Scala 2.9.1, which is an invalid combination. Not sure how you did this.. maybe you edited some internal SBT config files in the directory ~/.sbt/? If you want to get a "virgin" SBT, you can delete ~/.sbt/ and download the latest sbt-launch.jar. If you want to use a previous version of SBT, you can edit the project/build.properties file, as described on the Wiki.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: interprocedural analysis Does gcc (C, C++ and Fortran compilers in particular) support interprocedural analysis to improve performance? If yes, which are the relevant flags? http://gcc.gnu.org/wiki/InterProcedural says the gcc is going to implement IPA, but that page is quite outdated. A: Yes, it supports. Take a look at options started with -fipa here. Recent gfortran version (4.5+) supports even more sophisticated type of optimization - link-time optimization (LTO) which is interprocedural optimizations across files. The corresponding compiler flag is -flto. P.S. I wrote a small series of posts about LTO at my blog. You're welcome! :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7549019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Form validation: un-hide submit button when a radio value is selected and text message is entered I just want my "submit" button to un-hide (so user can push it) when a radio button is selected and a message is entered in the text box. I'm using ruby on rails, but I think this may be a javascript/css question. please let me know. (Also i'm using formalize for the form styling) A: You should add an onchange (or onclick) event listener to the radio button and a keyup event listener to the text box, then check the values. http://jsfiddle.net/vHdBb/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7549023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stacking up methods in Javascript I have an object I created with this snip-it that looks like this: ... var steps = new Array(); this.createStep = function(){steps.push(new step()); return steps[steps.length-1];}; this.getSteps = function(){return steps;}; //returns Array this.removeStep = function(pos){steps.splice(parseInt(pos), 1);}; // integer possition zero base this.insertStep = function(pos){steps.splice(parseInt(pos),0, new step());}; And this works fine: ... var newStep = wfObj.createStep(); newStep.setTitle('Step-'+i); newStep.setStatus('New'); but this does not var newStep = wfObj.createStep().setTitle('Step-'+i).setStatus('New'); Could someone please tell me how to fix this or even what to call it when you chain methods like this? A: This is called a fluent interface. The way to make it work is to have every function return this. A: As Ned said, this is sometimes called fluent interface. It's also sometimes called method chaining, as you have heard. You probably have some code somewhere that looks like this: this.setTitle = function(newTitle) { title = newTitle; }; Change that to this: this.setTitle = function(newTitle) { title = newTitle; return this; }; Do the same for setStatus.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jquery ajaxSubmit replaceTarget javascript I have a div in this pattern: <div id="register_container"> ... <script type="text/javascript"> $(document).ready(function() alert('hi'); $("#customer").css("backgroundColor", "red"); $('#add_item_form').ajaxSubmit({target: "#register_container", replaceTarget: true}); </script> </div> The first run around I get a background color of red on the #customer select box and an alert. The 2nd...n times around I get an alert but the #customer background doesn't change. It seems to be operating on the "Old" stuff. How can I fix this? A: try $("#customer").css("background-color", "red");
{ "language": "en", "url": "https://stackoverflow.com/questions/7549025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Curl doesn't work when tried to get contents of a specific domain PHP Curl doesn't work when tried to get contents of a specific domain. The specific domain is 'www.net4winners.com.br', it works with every domain but not with this domain, it always returns: 'object not found' in curl output. PHP Code of this test: <?php function run_curl($url,$p=null) { $ch = curl_init(); $options = array( CURLOPT_URL => $url, CURLOPT_HEADER => 0, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)", CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => 1 ); if($p != null) { $options[CURLOPT_CUSTOMREQUEST] = "POST"; $options[CURLOPT_POST] = 1; $options[CURLOPT_POSTFIELDS] = $p; } curl_setopt_array($ch,$options); $resultado = curl_exec($ch); if($resultado) { return $resultado; } else { return curl_error($ch); } curl_close($ch); } $out = run_curl('http://www.net4winners.com.br/'); echo $out; ?> could someone help me please? Thanks. A: It's not working because the server is checking for the existence of certain headers which are not sent by cURL. Based on my testing, the one that's missing in your case is Accept-Language. Try adding the following to your $options array: CURLOPT_HTTPHEADER => array('Accept-Language: en-us') Example: <?php $ch = curl_init('http://www.net4winners.com.br/'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/534.51.22 (KHTML, like Gecko) Version/5.1.1 Safari/534.51.22'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept-Language: en-us' )); curl_exec($ch);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with model binder property type int In my View Model I have a property: [Required] [MaxLength(4)] [DisplayName("CVC")] public int BillingCvc { get; set; } In my view I use it like so: @Html.TextBoxFor(x => x.BillingCvc, new { size = "4", maxlength = "4" }) When I post the form I get this error message: Unable to cast object of type 'System.Int32' to type 'System.Array'. However, if I change the property to string instead of int, I don't get the error. Declaring it as int allows the client validator to check if the field contains non numbers. A: The issue is your use of MaxLength with a type of int. see: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.maxlengthattribute(v=vs.103).aspx edit: you;re probably looking for Range(int,int)
{ "language": "en", "url": "https://stackoverflow.com/questions/7549028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Trying to get jenkins and gitolite to work successfully - Permission denied (publickey,password) I have been trying for days to get my gitolite work with jenkins so I can have repos hosted from server and working with Jenkins (they are on the same sever). I have gitolite working but I guess I have problems with ssh. I got some help on a chat and added private key to jenkins/.ssh. I have a user "git" that hosts the gitolite, and I got a user "gitolite" and a "jenkins" user. I can clone a repo by using git clone git@e-ject.se:Matrix But I can't use it in jenkins. I get this when I try to build. Checkout:workspace / /var/lib/jenkins/jobs/Matrix/workspace - hudson.remoting.LocalChannel@dbb335 Using strategy: Default Checkout:workspace / /var/lib/jenkins/jobs/Matrix/workspace - hudson.remoting.LocalChannel@dbb335 Cloning the remote Git repository Cloning repository origin ERROR: Error cloning remote repo 'origin' : Could not clone git@e-ject.se:Matrix ERROR: Cause: Error performing command: git clone --progress -o origin git@e-ject.se:Matrix /var/lib/jenkins/jobs/Matrix/workspace Command "git clone --progress -o origin git@e-ject.se:Matrix /var/lib/jenkins/jobs/Matrix/workspace" returned status code 128: Cloning into /var/lib/jenkins/jobs/Matrix/workspace... Permission denied, please try again. Permission denied, please try again. Permission denied (publickey,password). fatal: The remote end hung up unexpectedly Trying next repository ERROR: Could not clone repository FATAL: Could not clone hudson.plugins.git.GitException: Could not clone at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1042) at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:968) at hudson.FilePath.act(FilePath.java:758) at hudson.FilePath.act(FilePath.java:740) at hudson.plugins.git.GitSCM.checkout(GitSCM.java:968) at hudson.model.AbstractProject.checkout(AbstractProject.java:1193) at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:566) at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:454) at hudson.model.Run.run(Run.java:1376) at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46) at hudson.model.ResourceController.execute(ResourceController.java:88) at hudson.model.Executor.run(Executor.java:230) I login to my server and su - jenkins, then type "ssh -v git@server" I get this. git@Server:~$ sudo su - jenkins jenkins@Server:~$ ssh -v git@server OpenSSH_5.8p1 Debian-1ubuntu3, OpenSSL 0.9.8o 01 Jun 2010 debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for * debug1: Connecting to server [127.0.1.1] port 22. debug1: Connection established. debug1: identity file /var/lib/jenkins/.ssh/id_rsa type -1 debug1: identity file /var/lib/jenkins/.ssh/id_rsa-cert type -1 debug1: identity file /var/lib/jenkins/.ssh/id_dsa type -1 debug1: identity file /var/lib/jenkins/.ssh/id_dsa-cert type -1 debug1: identity file /var/lib/jenkins/.ssh/id_ecdsa type -1 debug1: identity file /var/lib/jenkins/.ssh/id_ecdsa-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.8p1 Debian-1ubuntu3 debug1: match: OpenSSH_5.8p1 Debian-1ubuntu3 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.8p1 Debian-1ubuntu3 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: sending SSH2_MSG_KEX_ECDH_INIT debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ECDSA f3:ab:a6:55:83:98:c5:4f:85:c6:70:be:2f:40:1f:65 debug1: Host 'server' is known and matches the ECDSA host key. debug1: Found key in /var/lib/jenkins/.ssh/known_hosts:3 debug1: ssh_ecdsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,password debug1: Next authentication method: publickey debug1: Trying private key: /var/lib/jenkins/.ssh/id_rsa debug1: read PEM private key done: type RSA debug1: Authentications that can continue: publickey,password debug1: Trying private key: /var/lib/jenkins/.ssh/id_dsa debug1: Trying private key: /var/lib/jenkins/.ssh/id_ecdsa debug1: Next authentication method: password git@server's password: It still asks for password... Anyone who have done this? Getting gitolite working with jenkins? I'm very grateful for any help and can gladly donate 10 bucks (visa card) for helping me set this up! A: SSH into the Jenkins box and create an SSH key pair for the Jenkins user (assuming jenkins here): local$ ssh jenkins-box you@jenkins-box$ sudo su jenkins jenkins@jenkins-box$ ssh-keygen jenkins@jenkins-box$ cat $HOME/.ssh/id_rsa.pub Copy the SSH public key you see on the screen and paste it into the new file keydir/jenkins.pub inside your local gitolite admin repository. Add the following lines to conf/gitolite.conf to give Jenkins permissions to clone and pull all repositories: repo @all R = jenkins Commit and push the gitolite admin repository. Jenkins should now work correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MySQL function declaration. Not works from PHP. Run's ok from phpmyadmin. Not creates function I have function to cal miles distance: DELIMITER // DROP FUNCTION IF EXISTS distance_miles// CREATE FUNCTION distance_miles(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT(120) BEGIN DECLARE pi, q1, q2, q3 FLOAT; DECLARE rads FLOAT DEFAULT 0; SET pi = PI(); SET lat1 = lat1 * pi / 180; SET lon1 = lon1 * pi / 180; SET lat2 = lat2 * pi / 180; SET lon2 = lon2 * pi / 180; SET q1 = COS(lon1-lon2); SET q2 = COS(lat1-lat2); SET q3 = COS(lat1+lat2); SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ); RETURN 6378.388 * rads * 0.621371192; END// DELIMITER ; I run this as 1 query from phpmyadmin. It run's Ok. But i dont see this in routines table in information_schema. Also, when am trying run this from php i got an error $mdb->query($mdb->mes(" DELIMITER // DROP FUNCTION IF EXISTS distance_miles// CREATE FUNCTION distance_miles(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT(120) BEGIN DECLARE pi, q1, q2, q3 FLOAT; DECLARE rads FLOAT DEFAULT 0; SET pi = PI(); SET lat1 = lat1 * pi / 180; SET lon1 = lon1 * pi / 180; SET lat2 = lat2 * pi / 180; SET lon2 = lon2 * pi / 180; SET q1 = COS(lon1-lon2); SET q2 = COS(lat1-lat2); SET q3 = COS(lat1+lat2); SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ); RETURN 6378.388 * rads * 0.621371192; END// DELIMITER ; ")); this one: error:1064 CALLED:[Resource id #8]***You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\r\nDELIMITER ~~ ' at line 1 in db query: [\r\nDELIMITER ~~ Pls help me, what happens? Completely dont understood this. * *How to look if function exists? *It will appear in information_shema table ROUTINES? *why is problem with php running this query? ==== SELECT ROUTINE_TYPE, ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES Also - dont show this function ... strange this all... Also this: SHOW CREATE FUNCTION distance_miles Answers: MySQL said: Documentation 1305 - FUNCTION distance_miles does not exist ... A: mysql_query doesn't support multiqueries. See manual. You just need to remove the DELIMITER lines, split the queries by yourself, and the CREATE FUNCTION should work. $mdb->query($mdb->mes("DROP FUNCTION IF EXISTS distance_miles")); $mdb->query($mdb->mes("CREATE FUNCTION distance_miles(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT(120) BEGIN DECLARE pi, q1, q2, q3 FLOAT; DECLARE rads FLOAT DEFAULT 0; SET pi = PI(); SET lat1 = lat1 * pi / 180; SET lon1 = lon1 * pi / 180; SET lat2 = lat2 * pi / 180; SET lon2 = lon2 * pi / 180; SET q1 = COS(lon1-lon2); SET q2 = COS(lat1-lat2); SET q3 = COS(lat1+lat2); SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ); RETURN 6378.388 * rads * 0.621371192; END ")); A: $mdb->query($mdb->mes("DROP FUNCTION IF EXISTS distance_miles")); $mdb->query($mdb->mes("delimiter $ CREATE FUNCTION distance_miles(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT(120) DETERMINISTIC BEGIN DECLARE pi, q1, q2, q3 FLOAT; DECLARE rads FLOAT DEFAULT 0; SET pi = PI(); SET lat1 = lat1 * pi / 180; SET lon1 = lon1 * pi / 180; SET lat2 = lat2 * pi / 180; SET lon2 = lon2 * pi / 180; SET q1 = COS(lon1-lon2); SET q2 = COS(lat1-lat2); SET q3 = COS(lat1+lat2); SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ); RETURN 6378.388 * rads * 0.621371192; END $ "));
{ "language": "en", "url": "https://stackoverflow.com/questions/7549037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: loading a JavaScript file with vars not set at load time the post title may not explain fully, but here is what I am hoping to do: I have my JavaScript code in a separate file, and I have it arranged like so var PK = { "vars" : { "uris" : { "app1": "http://this/server/", "app2": "http://that/server/" }, "something": { "objects": [], "obj1": { "url": PK.vars.uris.app1 }, "obj2": { "url": PK.vars.uris.app2 } } }, "methods" : { "doThis" : function(a) { $.ajax({ url: PK.vars.uris.app1, data: data, type: "GET", success: function(data) { .. do something .. } }); }, "doThat" : function(a) { $.ajax({ url: PK.vars.uris.app2, data: data, type: "GET", success: function(data) { .. do something else .. } }); }, "init" : function(position) { if (position) { PK.methods.doThis(); } else { PK.methods.doThat(); } } } }; and then, in my html, I have the following $(document).ready(function() { PK.vars.uris.app1 = "[% app1 %]"; PK.vars.uris.app2 = "[% app2 %]"; PK.methods.init(); }); where the values of app1 and app2 are sent from the server based on a config file. Except, it doesn't work as expected, because, when the separate JavaScript loads, PK.vars.uris is not defined at that time. Of course, everything works beautifully if I have PK.vars.uris{} hardcoded. How can I delay the evaluation of var PK until after the document has loaded and PK.vars.uris is available to be used in the JavaScript code? A: Is the problem that you need to pass values into an initialiser? How's this approach: In your external file: function PK_Constructor(app1Uri, app2Uri) { this.vars = { "uris" : { "app1" : app1Uri, "app2" : app2Uri }, "something": { "objects": [], "obj1": { "url": app1Uri }, "obj2": { "url": app1Uri } }, }; this.doThis = function(a) { $.ajax({ url: this.vars.uris.app1, data: data, type: "GET", success: function(data) { .. do something .. } }); // etc } And in you HTML: // Ensuring PK has global scope var PK = undefined; $(document).ready(function() { PK = new PK_Constructor("[% app1 %]", "[% app2 %]"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7549039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Netbeans Auto-Indentation and Curly Braces }{ Is it possible to set up the NetBeans editor to automatically unindent closing curly braces? I want this: if (something){ do thing one; do thing two; } Netbeans gives me this: if (something){ do thing one; do thing two; } and then I have to delete the four preceding spaces which is annoying. It would be nice if it would automatically unindent after typing the closing brace. Any ideas? Is it possible to do this with a macro? A: I ended up asking this on the netbeans forums and it turns out that it's a bug. If you have 'auto-insert braces' turned off, the braces won't align automatically, but everything works fine with 'auto-insert braces' turned on. A: NetBeans, as any other IDE, formats automatically the code (by default). So, when you insert the closing } it will remove the unnecessary spaces automatically. Anyway, you can select Source → Format or press Alt+Shift+F to re-format the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: A Python screen capture script that can be called programmatically? I want to open a page and grab the screen and obtain its mean color with PIL. I want to open about 100 pages so I thought a screen capture script with Python would be useful. I found several of them and I decided to use this simple one: """ A simple screen grabbing utility @author Fabio Varesano - @date 2009-03-17 """ from PIL import ImageGrab import time time.sleep(5) ImageGrab.grab().save("screen_capture.jpg", "JPEG") But I need to run this from Command Prompt which then shows on the screen. How do I make this into a script so that I can call it programmatically? Or, what do you think is the best way to achieve this? Thanks! A: You can use Selenium and any browser: Take a screenshot with Selenium WebDriver This is cross-platform, works on every browser. Selenium is designed for functional web browser testing, but is suitable also for use cases like yours. More info about Python + Selenium: http://pypi.python.org/pypi/selenium The benefit of Selenium is that you have fine-tuned control of the browser - you can click buttons, execute Javascript, whatever you wish and the browser is no longer a black box. A: This solution seems to do exactly what you want by bringing the browser to the foreground before performing the screen grab. Just replace 'firefox' with 'chrome'
{ "language": "en", "url": "https://stackoverflow.com/questions/7549044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can get an image from a 301 redirect download link in PHP? I'm trying to download this image with PHP to edit it with GD. I found many solutions for image links, but this one is a download link. Edit: $curl = curl_init("http://minecraft.net/skin/Notch.png"); $bin = curl_exec($curl); curl_close($curl); $img = @imagecreatefromstring($bin); This is my current code. It displays "301 Moved Permanently". Are there CURLOPTs I have to set? A: $curl = curl_init("http://minecraft.net/skin/Notch.png"); // Moved? Fear not, we'll chase it! curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // Because you want the result as a string curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $bin = curl_exec($curl); curl_close($curl); $img = @imagecreatefromstring($bin); A: Here is an option to directly save the image to a file (instead of using imagecreatefromstring): <?php $fileName = '/some/local/path/image.jpg'; $fileUrl = 'http://remote.server/download/link'; $ch = curl_init($fileUrl); // set the url to open and download $fp = fopen($fileName, 'wb'); // open the local file pointer to save downloaded image curl_setopt($ch, CURLOPT_FILE, $fp); // tell curl to save to the file pointer curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // tell curl to follow 30x redirects curl_exec($ch); // fetch the image and save it with curl curl_close($ch); // close curl fclose($fp); // close the local file pointer A: fopen - depends on your php settings if url fopen is allowed. or curl see the fine php manual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SqlDataAdapter.Fill() - Conversion overflow All, I am encountering "Conversion overflow" exceptions on one of the SqlDataAdapter.Fill() usages for a decimal field. The error occurs for value beginning 10 billion, but not till 1 billion. Here is the code: DataSet ds = new DataSet(); SqlDataAdapter sd = new SqlDataAdapter(); adapter.SelectCommand = <my SQL Command instance> adapter.Fill(ds); I have read using SqlDataReader as an alternate but we need to set the datatype and precision explicitly. There are at least 70 columns that I am fetching and I don't want to set all of them only for one decimal field in error. Can anyone suggest alternate approaches? Thank you. A: Although dataset is allowed for "filling" a data adapter, I've typically done with a DataTable instead as when querying, I'm only expecting one result set. Having said that, I would pre-query the table, just to get its structure... something like select whatever from yourTable(s) where 1=2 This will get the expected result columns when you do a DataTable myTable = new DataTable(); YourAdapter.Fill( myTable ); Now that you have a local table that will not fail for content size because no records will have been returned, you can now explicitly go to that one column in question and set its data type / size information as you need... myTable.Columns["NameOfProblemColumn"].WhateverDataType/Precision = Whatever you need... NOW, your local schema is legit and the problem column will have been identified with its precision. Now, put in your proper query with proper where clause and not the 1=2 to actually return data... Since no actual rows in the first pass, you don't even need to do a myTable.Clear() to clear the rows... Just re-run the query and dataAdapter.Fill(). I haven't actually tried as I don't have your data issues to simulate same problem, but the theoretical process should get you by without having to explicitly go through all columns... just the few that may pose the problem. A: I had the same problem and the reason is because in my stored procedure I returned a decimal(38,20) field. I changed it into decimal(20,10) and all works fine. It seems to be a limitation of Ado.Net. CREATE PROCEDURE FOOPROCEDURE AS BEGIN DECLARE @A DECIMAL(38,20) = 999999999999999999.99999999999999999999; SELECT @A; END GO string connectionString =""; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand("EXEC FOOPROCEDURE", conn); SqlDataAdapter adt = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adt.Fill(ds); //exception thrown here
{ "language": "en", "url": "https://stackoverflow.com/questions/7549058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can we call methods with parameters in Struts2 fieldexpression? I've configured my sturts2 application to use the validation xml for my actions. I also have fieldexpression working. Would it be possible to call a method from my action in the expression. eg: <field name="myField"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[ @com.test.MyClass@isCaptchaOk(keyString, userResponce) ]]></param> <message>My credit limit should be MORE than my girlfriend's</message> </field-validator> </field> Here is my actual test code, the simple fieldexpression works, but function call one does not (see the tbox1). I'm not sure if the @class@method path is ok or not, but is not working coz, I've added log in the functions but nothing comes up, so i presume the validator can't reach the functions. Also, Is this possible, ie is it allowed or am i being too ambitious. Thanks PS I've corrected the message, I'm not trading my girlfriend ;-) **** validation.xml <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators> <field name="tbox1"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[@uk.co.nhbc.userRegistration.action.Test2Action@getString()]]></param> <message>function call message here</message> </field-validator> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[@uk.co.nhbc.userRegistration.action.Test2Action@isCaptchaOk(tbox1, user.username)]]></param> <message>function call message here</message> </field-validator> </field> <field name="tbox2"> <field-validator type="stringlength"> <param name="maxLength">5</param> <message>length messssage here</message> </field-validator> </field> <field name="user.username"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[(!(tbox2 == "aa" && user.username.equals("")))]]></param> <message>tbox2 eq aa and username is empty messssage2 here</message> </field-validator> </field> </validators> ******* java class package uk.co.nhbc.userRegistration.action; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import uk.co.nhbc.common.action.BaseAction; import uk.co.nhbc.userRegistration.model.Users; public class Test2Action extends BaseAction { private String tbox1; private String tbox2; private Users user; private static final Log log = LogFactory.getLog(Test2Action.class); public String execute() { return SUCCESS; } public String getTbox2() { return tbox2; } public void setTbox2(String tbox2) { this.tbox2 = tbox2; } public String getTbox1() { return tbox1; } public void setTbox1(String tbox1) { this.tbox1 = tbox1; } public Users getUser() { log.debug("get user called"); return user; } public void setUser(Users user) { log.debug("set user called"); this.user = user; } public boolean isCaptchaOk(String challenge, String response) { //dummy test function log.debug("captcha function called"); if (response.equals("true")) return true; return false; } public String getString (){ log.debug("getString function called"); return "hello"; } } *********and jsp page <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sj" uri="/struts-jquery-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <s:form name="formtest" action="Test2Action"> <s:actionerror/> <s:fielderror></s:fielderror> <s:textfield name="tbox1" label="box1"></s:textfield> <s:textfield name="tbox2" label="box1"></s:textfield> <s:textfield name="user.username" label="boxuser"></s:textfield> <s:submit></s:submit> </s:form> </body> </html> A: In order to calling a static method in expression, which must be OGNL, you should enable struts.ognl.allowStaticMethodAccess by adding below constant to struts.xml file: < constant name="struts.ognl.allowStaticMethodAccess" value="true"/> A: See my updated working validator file. for field tbox1 in the fieldexpression I'm referring to the method directly as it is my action, which would be on the VS. tbox1 and user.username are items on the jsp page (and also exist in the action) I tried to experiment with a static method, but that didn't work, (no time to investigate now). Hope this helps and thanks dave for the input. ***updated validation xml <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators> <field name="tbox1"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[isCaptchaOk(tbox1, user.username)]]></param> <message>function call message here</message> </field-validator> </field> <field name="tbox2"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[(@uk.co.nhbc.userRegistration.action.Test2Action@isFuncOk(tbox2))]]></param> <message>func okk function call message here</message> </field-validator> </field> <field name="user.username"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[(!(tbox2 == "aa" && user.username.equals("")))]]></param> <message>tbox2 eq aa and username is empty messssage2 here</message> </field-validator> </field> </validators> ***updated java class package uk.co.nhbc.userRegistration.action; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import uk.co.nhbc.common.action.BaseAction; import uk.co.nhbc.userRegistration.model.Users; public class Test2Action extends BaseAction { private String tbox1; private String tbox2; private Users user; private static final Log log = LogFactory.getLog(Test2Action.class); public String execute() { return SUCCESS; } public String getTbox2() { return tbox2; } public void setTbox2(String tbox2) { this.tbox2 = tbox2; } public String getTbox1() { return tbox1; } public void setTbox1(String tbox1) { this.tbox1 = tbox1; } public Users getUser() { log.debug("get user called"); return user; } public void setUser(Users user) { log.debug("set user called"); this.user = user; } public boolean isCaptchaOk(String challenge, String response) { //dummy test function log.debug("captcha function called"); log.debug("captcha function called"+challenge+response); if (response.equals("true")) return true; return false; } public String getString (){ log.debug("getString function called"); return "hello"; } public static boolean isFuncOk (String response){ log.debug("isFuncOk function called"+response); if (response.equals("true")) return true; return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: flash as3 rounding numbers automatically I wrote out a long post trying to explain the exact details of the problem im having, but instead i think ill keep it simple, and ask an example question here: var n1:Number = 9.99999999999999; n1 += 0.000000000000009; var n2:Number = n1 + 10; var n3:Number = n1 - 10; Long story short, n1 = 9.99....7, n2 = 20, n3 = 10. If i try to make a comparison between n1 and n3, they should be the same but they arn't. I dont care if flash rounds it or not, i just need them to be the same (and they arn't, cause flash rounds in one case, and not the other). Is there some standard solution for a problem like this? P.S. I dont need this precision on my numbers, but i also would not like to micromanage the rounding of the numbers EVERY time i do a manipulation (that seems like it could add a LOT of code to the mix). If this is the only solution however, i guess ill just have to do a lot of rounding throughout the code, ha. A: The Number in flash is a double precision floating point number. Read more here about them. These "problems" are not unique to flash, but just have to do with how these numbers are stored. There are a couple of options. Here is a quick little library for fuzzy comparing numbers, within a certain margin of error. Another option would be implement a fixed point math library. A: Is it a problem to just wrap in int() if you're trying to compare? trace(int(n1) == int(n3));
{ "language": "en", "url": "https://stackoverflow.com/questions/7549064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extensible Orchard I am new to Orchard, I am wondering how Can I run my module once project start instead of Orchard Startup module? Also how can I override the Routing to route to my new module?where it is being written? Thanks A: Implement IHomePageProvider. If I understood the question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide one view and unhide another upon touching a button I have been creating "if/then" apps for android and now my boss want me to do the same for his iPad. I just need to figure out how to code so that when the buttons are clicked, it hides the current view (text and button) and reveals the next set of text and buttons. A: Make sure your two sets of text/buttons are in two UIViews (I will refer to these as 'viewOne' and 'viewTwo'), when you want to swap your views, use this code: [viewOne setHidden:[viewTwo isHidden]]; [viewTwo setHidden:![viewTwo isHidden]]; It's not the most understandable way to do this, but it's one of the shortest. For something easier to read: if ([viewOne isHidden]) { [viewOne setHidden:NO]; [viewTwo setHidden:YES]; } else { [viewOne setHidden:NO]; [viewTwo setHidden:YES]; } Either will work, it just depends on how you like to write your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: When including external xml file, LayoutInflater throws RuntimeException: "You must supply a layout_width attribute." I'm trying to include a ScrollView (upgrade_content.xml) containing a ListView in my Activity's XML layout file (upgrades.xml). When I include the external file using <include layout="@layout/upgrades_content"/>, I get a RuntimeException with the message "You must supply a layout_width attribute." If I copy the code from upgrade_content.xml and paste it directly into upgrades.xml, it works fine. upgrades.xml (This throws the exception): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/upgrades_layout" android:layout_width="fill_parent" android:layout_height="match_parent" android:gravity="center_vertical" android:background="@drawable/menu_screen_bg" android:orientation="vertical"> <include layout="@layout/upgrades_content"/> </LinearLayout> upgrades_content.xml: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:fillViewport="true" android:layout_weight="1"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center_horizontal"> <!-- Activity Title --> <RelativeLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="10dp"> <TextView android:id="@+id/upgrades_title_text" android:text="@string/upgrade_store_string" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:textSize="@dimen/TitleTextSize" style="@style/ActivityTitleTextStyle" /> </RelativeLayout> <!-- Upgrades List --> <LinearLayout android:background="@drawable/old_paper_bg" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:layout_gravity="center_horizontal" android:layout_marginLeft="@dimen/OldPaperScrollViewMargin" android:layout_marginRight="@dimen/OldPaperScrollViewMargin" android:layout_marginBottom="@dimen/OldPaperScrollViewMargin" android:padding="@dimen/OldPaperScrollViewPadding"> <ListView android:id="@android:id/list" android:layout_width="wrap_content" android:layout_height="fill_parent"> </ListView> </LinearLayout> </LinearLayout> </ScrollView> UpgradeActivity.java: public class UpgradeActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.upgrades); setListAdapter(ArrayAdapter.createFromResource(this, R.array.upgrade_string_array, R.layout.upgrade_layout_list_item)); } } upgrade_layout_list_item.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="@dimen/LabelTextSize" /> EDIT: The RuntimeException thrown by this code doesn't cause a Force Close, so I might have just been a little too liberal in which exceptions I set Eclipse to catch. A: try to specify the layout height and width in upgrade.xml under your <include> tag like this: <include layout="@layout/upgrades_content" android:layout_width="fill_parent" android:layout_height="wrap_content" /> Put the width and height values to whatever fill your need: fill_parent or wrap_content
{ "language": "en", "url": "https://stackoverflow.com/questions/7549078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: e.preventDefault() is not behaving correctly I have a drop down menu that is still triggering an href change even though I'm calling e.preventDefault(). This is how I have my jquery address change configured: $(document).ready(function() { // Setup jQuery address on some elements $('a').address(); // Run some code on initial load $.address.init(function(e) { // Address details can be found in the event object }); // Handle handle change events $.address.change(function(e) { var urlAux = e.value.split('='); var page = urlAux[0]; var arg = urlAux[1]; .... }); }); My drop down id looks like this: <li id="search"><a href="#" class="drop" >Search</a> my event handler for the drop down is below: $('#search').click(function(e) { e.preventDefault(); $(this).children(menuItemChildren).slideDown(0); $(this).hover(function() { }, function(){ $(this).children(menuItemChildren).slideUp(0); }); }); Even though I'm calling e.preventDefault() on my #search element it still triggers an address change. Any idea whats wrong? A: This should work <li id="search"><a href="javascript:void(0)" class="drop" >Search</a> A: You should add a click handler on the a element, with a call to e.preventDefault() $('#search a.drop').click(function(e) { e.preventDefault(); }); A: Events bubble upwards, from child to parent. You're trying to prevent the default action on the <a> by calling e.preventDefault(); on the parent <li>. The problem is that all actions connected with the <a> will fire before those connected to the <li> because of the event bubbling order I described in the first sentence. In other words, e.preventDefault(); doesn't get called until after the event has already been triggered on the child. You should bind a click event to the <a> element, and call e.preventDefault(); from there. A: The problem is most likely that MouseEvent e does not reference the a tag because you're binding the click event to the list element. You can check that using console.log(e.target). You may see that e.target is a list element. You can fix that by binding another event to $('#search a').click(function (e) { e.preventDefault(); }); But why use e.preventDefault() when you can just remove the href attribute? Do this and there will be no action taken upon click.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any JSF Select Time Zone component out there? I have been looking for this for a while and haven't found it. It is surprisingly complicated as shown in this old IceFaces tutorial. What is needed is a UIInput component that will set a java.util.TimeZone property, allowing the user to select it from a map or a list on the screen. Before I dive in to write one for myself -- does anyone know of an available component that does this? A: Use <h:selectOneMenu> to represent a dropdown list. Use <f:selectItems> to feed it with a E[], List<E>, SelectItem[] or List<SelectItem> as value. Here's how it can look like at its simplest: @ManagedBean @ViewScoped public class Bean implements Serializable { private String timeZoneID; // +getter +setter private String[] timeZoneIDs; // +getter only @PostConstruct public void init() { timeZoneIDs = TimeZone.getAvailableIDs(); // You may want to store it in an application scoped bean instead. } public void submit() { System.out.println("Selected time zone: " + TimeZone.getTimeZone(timeZoneID)); } // ... } with this view: <h:form> <h:selectOneMenu value="#{bean.timeZoneID}" required="true"> <f:selectItem itemValue="#{null}" itemLabel="Select timezone..." /> <f:selectItems value="#{bean.timeZoneIDs}" /> </h:selectOneMenu> <h:commandButton value="submit" action="#{bean.submit}" /> <h:messages/> </h:form> If you want to make it a fullworthy TimeZone property, you'd need to bring in a @FacesConverter(forClass=TimeZone.class) which should be pretty straightforward enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Membership Provider or Profile Provider in mvc asp.net I'm venturing into the world of asp.net mvc. I have not yet understood whether it makes sense to use a custom Membership Provider or use the Profile provider for the user management? A: Membership provider - manages user names, email addresses, and passwords. Profile provider - manages all other custom user settings, such as name and preferences. So, to answer your question, you should use both, because they serve different purposes. A: One, Membership providers and Profile providers serve two different purposes. The Membership provider provides a user list and authentication functionality. The Profile provider provides a way to store application-specific data associated with each user. Whether you need a custom provider depends on what type of datastore you want to use. The two built-in Membership providers allow for using an Active Directory domain (generally only appropriate if you're developing an application for a corporate intranet) or an MS SQL Server Database. The one built-in Profile provider uses MS SQL. If you want to use a different type of datastore, for example a PostgreSQL database, then you'll need a custom provider for that particular datastore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: .Net - using method extensions? Is it possible to use the method extensions to add methods that accept parameters ? for example: myString.NumberOfCharacters("a"); A: yes. like this   public static class StringExtensions { public static void NumberOfCharacters(this string someString, string param) { ... } } Check out the MDSN page of extension methods and the examples there. A: Sure: public static int NumberOfCharacters(this string str, string extraParam) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: One account, multiple ways to login? I want to build an application that allow users to log in via the following: * *my own authentication/authorization solution *3rd party providers, such as "log in with your Gmail account" or "log in with your Facebook account" My concern is that an individual could create an account using my application's solution AND have a Gmail account AND have a FB account, etc. Though there may be various ways for a person to log in, they still all refer to the same individual. Despite multiple ways to log in, I want to be able to figure out if they refer to the same individual. Questions: * *Is what I am thinking even possible? (Meaning, is there some way I'll be able to figure out that a Gmail account is referring to the same person with a particular FB account?) *Any suggestions on general strategies on how to implement this? A: Get the user to identify their accounts explicitly. Only let them link two accounts once they authenticate against both of them. See how stackoverflow does it (click "my logins" on your profile page). You might also want to consider the issue of merging accounts. A user might create two accounts and then realise they only meant to have one. The way you resolve this will be specific to your problem domain and schema.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nil and List as case expressions in Scala This code compiles: def wtf(arg: Any) = { arg match { case Nil => "Nil was passed to arg" case List() => "List() was passed to arg" case _ =>"otherwise" } } But this one does not: def wtf(arg: Any) = { arg match { case List() => "List() was passed to arg" case Nil => "Nil was passed to arg" case _ =>"otherwise" } } The line case Nil => ... is marked as unreachable code. Why, in the first case, the line case List() => ... is not marked with the same error? A: The actual answer requires understanding an unfortunate implementation detail which cost me a lot of time to discover. 1) case List() invokes an extractor, for which no exhaustivity/unreachability checking is possible in the general case because extractors invoke arbitrary functions. So far so good, we can't be expected to overturn the halting problem. 2) Way back in the more "wild west" days of the compiler, it was determined that pattern matching could be sped up rather a lot (and not lose exhaustivity checking) if "case List()" were just translated to "case Nil" during an early compiler phase so it would avoid the extractor. This is still the case and although it could be undone, apparently lots of people have been told that "case List() => " is perfectly fine and we don't want to pessimize all their code all of a sudden. So I just have to figure out a road out. You can see empirically that List is privileged by trying it with some other class. No unreachability errors. import scala.collection.immutable.IndexedSeq val Empty: IndexedSeq[Nothing] = IndexedSeq() def wtf1(arg: Any) = { arg match { case Empty => "Nil was passed to arg" case IndexedSeq() => "IndexedSeq() was passed to arg" case _ =>"otherwise" } } def wtf2(arg: Any) = { arg match { case IndexedSeq() => "IndexedSeq() was passed to arg" case Empty => "Nil was passed to arg" case _ =>"otherwise" } } A: The discrepancy is particularly weird since the code for the Nil case in the second version is definitely not unreachable, as we can see if we hide things from the compiler a bit: def wtf(arg: Any) = { arg match { case List() => "List() was passed to arg" case x => x match { case Nil => "Nil was passed to arg" case _ =>"otherwise" } } } Now wtf(Vector()) will return "Nil was passed to arg". This may also seem counterintuitive, but it's because literal patterns match values that are equal in terms of ==, and Vector() == Nil, but Vector() doesn't match the extractor pattern List(). More concisely: scala> (Vector(): Seq[_]) match { case List() => true; case Nil => false } <console>:8: error: unreachable code scala> (Vector(): Seq[_]) match { case List() => true; case x => x match { case Nil => false } } res0: Boolean = false So the compiler's response is completely reversed: in the "good" version the second case is unreachable, and in the "bad" version the second case is perfectly fine. I've reported this as a bug (SI-5029). A: Nil is an object extending List[Nothing]. Being more specific than List(), it isn't reached if it appears after List() in the case expression. While I think the above is more or less true, it's likely not the whole story. There are hints in the article Matching Objects with Patterns, though I don't see a definitive answer there. I suspect that detection of unreachability is simply more completely implemented for named constants and literals than for constructor patterns, and that List() is being interpreted as a constructor pattern (even though it's a trivial one), while Nil is a named constant. A: I cannot find anything in the language specification with respect to unreachable match clauses. Somebody correct me if I'm wrong. So I assume that unreachable compilation errors are on a best effort basis, which may explain why the first case does not complain. scala -Xprint:typer suggests that Nil is a literal pattern using immutable.this.Nil.== to check for a match, while List() is an extractor pattern. Looking at the implementation of the extractor in it seems to be doing something like this: def unapplySeq[A](x: CC[A]): Some[CC[A]] = Some(x) So I got curious and rolled out an alternate implementation: object ListAlt { def unapplySeq[A](l: List[A]): Some[List[A]] = Some(l) } It matches like List(): scala> Nil match { case ListAlt() => 1 } res0: Int = 1 But if I implement your function with it, it compiles fine (except for unchecked warning): def f(a: Any) = a match { case ListAlt() => 1 case Nil => 2 case _ => 0 } scala> f(List()) res2: Int = 1 scala> f(Nil) res3: Int = 1 scala> f(4) res4: Int = 0 So I am wondering if the pattern matcher implementation has some special casing for Nil and List(). May be it treats List() as a literal...
{ "language": "en", "url": "https://stackoverflow.com/questions/7549111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: good example applications combining rails 3 and sproutcore I am trying to write a sproutcore frontend for a rails 3.1 application I am making. I have had a look at the sproutcore guides, but I am interested in seeing real examples how to use sproutcore together with rails 3(.1). I have found two examples, but each is totally different: * *A todo-app created using bulk_api: an interesting approach using a specific REST-style to minimise the traffic. But it proposes to place the sproutcore app in app/sproutcore, and is still a bit unclear to me how that actually hooks in completely. *Travis-ci which seems to be a very clean example, rails 3.1, to use sproutcore. It is not yet completely clear to me, but all sproutcore js is cleanly stored inside app/assets/javascript/apps and as far as i can tell, the application.html just loads the js and provides the frame where everything is loaded into. Do you know any other examples? How do you use sproutcore in your rails app? A: The method you describe is the same way that you integrate backbone.js into a rails app, and it seems to work very well https://github.com/codebrew/backbone-rails This stores backbone in app/assets/javascripts/backbone/ app/assets/javascripts/backbone/app/models app/assets/javascripts/backbone/app/controllers And then there is a script tag in the view that just initializes backbone <script type="text/javascript"> $(function() { // Blog is the app name window.router = new Blog.Routers.PostsRouter({posts: <%= @posts.to_json.html_safe -%>}); Backbone.history.start(); }); </script> I imagine a similar process for sproutcore would make sense A: I did find a demo-project: sproutcore-on-rails that did manage to make things clearer for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Exception handling in Python Tornado I am trying to handle exception occurred in AsyncClient.fetch in this way: from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest from tornado.stack_context import ExceptionStackContext from tornado import ioloop def handle_exc(*args): print('Exception occured') return True def handle_request(response): print('Handle request') http_client = AsyncHTTPClient() with ExceptionStackContext(handle_exc): http_client.fetch('http://some123site.com', handle_request) ioloop.IOLoop.instance().start() and see next output: WARNING:root:uncaught exception Traceback (most recent call last): File "/home/crchemist/python-3.2/lib/python3.2/site-packages/tornado-2.0-py3.2.egg/tornado/simple_httpclient.py", line 259, in cleanup yield File "/home/crchemist/python-3.2/lib/python3.2/site-packages/tornado-2.0-py3.2.egg/tornado/simple_httpclient.py", line 162, in __init__ 0, 0) socket.gaierror: [Errno -5] No address associated with hostname Handle request What am I doing wrong? A: According to the Tornado documentation: If an error occurs during the fetch, the HTTPResponse given to the callback has a non-None error attribute that contains the exception encountered during the request. You can call response.rethrow() to throw the exception (if any) in the callback. from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest from tornado.stack_context import ExceptionStackContext from tornado import ioloop import traceback def handle_exc(*args): print('Exception occured') return True def handle_request(response): if response.error is not None: with ExceptionStackContext(handle_exc): response.rethrow() else: print('Handle request') http_client = AsyncHTTPClient() http_client.fetch('http://some123site.com', handle_request) http_client.fetch('http://google.com', handle_request) ioloop.IOLoop.instance().start() The message you're seeing on the console is only a warning (sent through logging.warning). It's harmless, but if it really bothers you, see the logging module for how to filter it. A: I don't know Tornado at all, but I gave a look and you simply can't catch exceptions that way. The exception is generated in the constructor of _HTTPConnection(), and most of the code in that constructor is already wrapped by a different stack context: with stack_context.StackContext(self.cleanup): parsed = urlparse.urlsplit(_unicode(self.request.url)) [...] So basically whenever an exception is generated there (gaierror in your example), it is caught already and handled through self.cleanup, that in turns generate a 599 response AFAICT: @contextlib.contextmanager def cleanup(self): try: yield except Exception, e: logging.warning("uncaught exception", exc_info=True) self._run_callback(HTTPResponse(self.request, 599, error=e, request_time=time.time() - self.start_time, )) Not sure if this answers your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Overlaying an animation on top of UIView What is the best way to overlay an animated gif on top of a UIView? I have an animation of snowfall that I would like to lay on top of a view, yet still retain interaction with the view below. Can this be accomplished with UIView animation, or would CoreAnimation be better (for compositing the layers). Thanks again for the help A: One of probably many options would be to set the UIView.backgroundColor = [UIColor clearColor], then place animation objects behind the view, or use a UIButton with a clear bg, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: blackberry os 7 sencha touch tap text field I just got a BlackBerry Torch 9810 running OS 7. I noticed my sencha touch app won't let me tap to enter a text input field. I have to click the trackpad. I know it works normally on non-sencha fields, like the ones here. I tried the example for forms from sencha and I'm having the same issue. I tried attaching a tap listener to the textfield but it's not being triggered. Any ideas? A: Sencha Touch 1 has many problems with Blackberry OS 7, I'd recommend upgrading to Sencha Touch 2 which has less issues. Yes, 'less'... there are still some. In any case, I was able to fix this particular bug: https://gist.github.com/2645017 It's quite untested, so use at your own risk, but here's hoping it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flashbuilder 4.5. Parse results of HTTP Service Call I'm making an HTTP Service Call using Flash Builder 4.5. My web service returns a string. I'm having trouble understanding how to read in the returned string. LoginResult.token = login.Login(Username.text, Password.text); Here is what I have so far. What do I need to do next to get the returned string? A: Figured it out. In case this will help anyone else, the following gets you the String returned by the HTTP Service Call. LoginResult.token = login.Login(Username.text, Password.text); LoginResult.lastResult //String returned by web service
{ "language": "en", "url": "https://stackoverflow.com/questions/7549130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Domain is not allowed, og:url/type/title not set... (using comments plugin) We're testing the FB comments plugin on our articles, only I continue to get 'url not reachable' warnings. So I have no idea what I'm doing wrong here - it's telling me og:url, og:type, and og:title aren't set, but not only does it show them as set below, it's also recognizing the url as being of type 'article' when telling me it can't access the domain - and the domain is very clearly set in the app properties. As long as I'm here asking, is it possible to okay an application for more than one domain? We have a staging site with a different domain and it would be convenient to be able to do things solely on it. I've searched and not found this precise problem, but please excuse me if I'm doing something completely stupid and obvious here. A: you must write www.sitename.com in the fb application
{ "language": "en", "url": "https://stackoverflow.com/questions/7549131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customize destination of Redis' RDB file I want to customize the destination of Redis' RDB file to be something other than a file on a mounted file system. For example: * *Send the file to a remote host via scp *Upload the file to Hadoop HDFS (I'm running Redis on a Hadoop cluster, in which we use HDFS for backup all the time) *gzip the file and then move it to some archive location The reason for this is I want to archive the RDB files (my data gets flushed out every day). I'm not sure what I'm going to do with these archived RDB files yet, but I think I'll be able to derive some value from them later. Is there a way to trigger an external process from Redis when a new dump is made so that I can ship the RDB file to its destination? The most sophisticated thing I can come up with right now is a cron job that checks to see if the file needs to be shipped ever minute or so, but I'd rather have it triggered instead of constantly polling. I'm pretty new to Redis, so feel free to correct me if you think I'm approaching this problem improperly and suggest a new solution. A: Maybe I'm missing something, if you're doing this to preserve data that is going to be wiped out, why not just schedule it to scp it and gzip it right before the days data is flushed? What is the reason for wanting it not to live on a normal file system? To my knowledge there is no way to trigger an external process from within redis when it writes the RDB file. It's going to potentially happen quite frequently depending on your save settings in the config file. Take a look at this doc to get more information http://redis.io/topics/persistence. A: May be I am missing too, but: You can change where the file is made in redis.conf You can set up crontab that move/copy the file. For highest security, do two crontabs - one that move the file (mv data.rdb data1.rdb) and second that upload data1.rdb 5-10 min later. Reason is that it may be possible the crontab to start at the same time as Redis save process. Because topic is interesting, I may do simple script that do this, check http://redis4you.com/articles.php tomorrow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When my method is a Helper, Utility or should be turned into a Extension? For example this encryption function could be called a Utility ? public static string HashText(string text) { byte[] encodedBytes; using (var md5 = new MD5CryptoServiceProvider()) { var originalBytes = Encoding.UTF8.GetBytes(text); encodedBytes = md5.ComputeHash(originalBytes); } return Encode(encodedBytes); } While this other function would be a Helper ? public static string Encode(byte[] byteArray) { if (byteArray == null || byteArray.Length == 0) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteArray.Length; i++) { sb.Append(byteArray[i].ToString("x2")); } return sb.ToString(); } How about a Extension could you provide any simple examples of when I should turn something into a extension of a method ? A: When to make a method a static helper method or an extension method is a subjective decision. If you need help deciding whether or not to make a method an extension method, then ask yourself whether it makes sense to include that method in the other class as a normal instance method. For example, you might have a method like this: public class Customers { public static Customer GetCustomer(string name) { // implementation return customer; } } Does this make sense as an instance method of the String class? public class String { public Customer GetCustomer() { // implementation return customer; } // other methods } Design-wise this polutes the String class with a completely unrelated class. It makes the String class a "kitchen sink" that collects anything and everything remotely related to strings. On the other hand, suppose you have method like this: public class StringHelper { public static string[] Split(string s, string separator) { // implementation return array; } } Does this make sense as an instance method of the String class? public class String { public string[] Split(string separator) { // implementation return array; } // other methods } Absolutely! This an natural extension to the existing Split functionality. It could have been included in the original implementation of String. Everything in between can be judged on a case-by-case basis. A: I'm not sure if it's entirely correct but I've often heard the terms helper and utility used interchangeably. They both strike me as fairly informal terms since they refer to an organizational approach rather than anything specific about how the language handles them. Still, there are some connotations that may clear up some confusion for you. A utility method will typically be one that is used often but is not specific to your application. Cosine and Sine methods are good examples of this. A helper class or helper method is typically used often but is specific to your application. Encrypt is a good example because encryption methods employed vary from application to application. With your regard to when you should write a utility method the answer is it's not really a "should" or "should not" kind of situation. There is negligible (if any) difference when it comes to performance and whether you use an extension method or pass in a parameter to a helper/utility method is purely a matter of preference. While an extension method may have a cleaner feel to it there are many languages that do not support extension methods so neither approach is wrong and will have a negligible impact on readability of your source code. A: Regarding the extension methods, they shouldn't be overused. Extension methods are best when they seem to extend the existing functionality of an object. For example, you might extend StringBuilder with a method AppendHex. However, if the functionality seems unrelated to the object or to its existing functionality, using a "utility" class is a better practice. It will be easier to read, write, and understand these methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CodeIgniter's dbutils not recognizing new database connection Does the Utility Class reconnect to the database defined in your database configuration file when it's initialized? The following code is returning databases from the dev database and not prod: $this->load->database('prod'); $this->load->dbutil(); print_r($this->dbutil->list_databases()); My database configuration file contains: $db['dev']['hostname'] = 'localhost'; $db['dev']['username'] = 'root'; $db['dev']['password'] = ''; $db['dev']['database'] = 'mydb'; ... $db['prod']['hostname'] = 'prodhost'; $db['prod']['username'] = 'username'; $db['prod']['password'] = 'password'; $db['prod']['database'] = 'myproddb'; ... edit 1: indeed, dbutil appears to be influenced by $active_group variable in the database configuration file. How do I override this for a single function? I thought that was the purpose of $this->load->database('environment'); ... no? A: The Utility class uses the database assigned to $this->db to carry out its functions. The solution was to assign the result of $this->load->database('environment') to $this->db: $this->db = $this->load->database('environment', TRUE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LINQ: The specified type member is not supported in LINQ I am trying to run the linq statement below. I am getting the following error message: The specified type member 'CustomerID' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. I stepped through the code and it happens when I take query and attempt to convert using "ToList()". Any ideas? How would I rewrite this query so that LINQ to Entities stops complaining. Steve var query = from l in db.QBPOLines join t in db.tblJobTasks on l.POID equals t.PurchaseOrderID join j in db.tblJobTasks on t.JobID equals j.JobID join c in ( from c in db.tblCustomers select new { c.CustomerID, PricingID = c.PricingID == null || c.PricingID == 0 ? 1 : c.PricingID } ) on j.CustomerID equals c.CustomerID join m in db.QBItemsPriceMaps on l.Item equals m.ItemName join s in db.tblCustomerPricingSchemes on c.CustomerID equals s.CustomerID into g1 from s in g1.DefaultIfEmpty() join p in db.tblPricingSchemes on l.LangPairs equals p.PSLangPairID into g2 from p in g2.DefaultIfEmpty() where t.JobID == jobID && s.PSLangPairID == l.LangPairs && p.PSDescID == c.PricingID select new { j.JobID, l.Item, l.LangPairs, l.Qty, Rate = s.PSLangPairID != null ? (m.CustomerPriceField == "PS_FZ50" ? s.PS_FZ50 : m.CustomerPriceField == "PS_FZ75" ? s.PS_FZ75 : m.CustomerPriceField == "PS_FZ85" ? s.PS_FZ85 : m.CustomerPriceField == "PS_FZ95" ? s.PS_FZ95 : null) : (m.CustomerPriceField == "PS_FZ50" ? p.PS_FZ50 : m.CustomerPriceField == "PS_FZ75" ? p.PS_FZ75 : m.CustomerPriceField == "PS_FZ85" ? p.PS_FZ85 : m.CustomerPriceField == "PS_FZ95" ? p.PS_FZ95 : null) }; List<tblJobManagementLineItem> list = query.ToList().ConvertAll(i => new tblJobManagementLineItem { JobID = i.JobID, LineItemDescr = i.Item, LanguagePairID = i.LangPairs, SourceWordCount = (int)i.Qty, QtyToInvoice = (int)i.Qty, //item.JobInvoiceID <--- Implement later Rate = i.Rate }); A: I believe the problem is that you can't join on a collection of anonymous types. Move the PricingId property to a later let clause and join directly to Customers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How should I pass collections from one view's ViewModel to another View? can anyone please advise a solution in following scenario : I have an MVVM application in which I need to show modal window from Main window to add some value to the Collection that is in viewModel class. What will be the best approach to do this. I mean. I need to change some collection in viewModel , My MainWindow have reference to viewMode. viewModel = new ExamViewModel(); this.DataContext = viewModel; Is it good enough to expose viewmodel also to child window ? Or there is "right" way to do this. A: Normally, the modal window will only know about the object in question, allowing the user to fill in a new object (and possibly also edit an existing object). It will then pass the filled-in object back to the parent, which is responsible for updating the collection. A: As @Marcelo suggested, your code that opens the new child window should be passed on with some delegate from your ViewModel. This delegate will create a child ViewModel (say ChildVM) and populate one of its properties (say ChildCollection) with its own collection (ParentVM.ParentCollection). var childVM = new ChildVM(); childVM.ChildCollection = parentVM.ParentCollection.ToList(); return childVM; Then your child window will be bound to that newly populated collection (ChildVM.ChildCollection) property and after it performs "OK" / "SAVE" kind of affirmation actions, the closed child window should notify / delegate back to the parent viewmodel to "incorporate" changes back to its old collection... like so... parentVM.ParentCollection.Clear(); parentVM.ParentCollection.AddRange(ChildVM.ChildCollection); This way * *Changes are done on seperate lists. Data integrity is maintained. *ONLY a legitimate action (OK / SAVE) merges the changes. *Child viewmodel is easily plugged off the UI and and disposed off the memory due to disconnected data and the unloaded child view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot determine the field name in a magento filter query I'm having trouble with using an OR filter in a Magento query. This is what i used: $collection = Mage::getModel('sales/order')->getCollection() ->addAttributeToSelect('*') ->addAttributeToFilter( array( array('attribute'=>'status','eq'=>'pending'), array('attribute'=>'created_at', 'from'=>$startDate, 'to'=>$finishDate) ) ); I want the following WHERE statement: WHERE 'status' = 'pending' OR (created_at < $startDate AND created_at > $finishDate) but i get the following error message Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Cannot determine the field name.' in /home/content/r/o/n/ronakkaria/html/magento/app/Mage.php:563 Stack trace: #0 /home/content/r/o/n/ronakkaria/html/magento/app/code/core/Mage/Sales/Model/Resource/Collection/Abstract.php(52): Mage::throwException('Cannot determin...') #1 /home/content/r/o/n/ronakkaria/html/magento/app/code/core/Mage/Sales/Model/Resource/Collection/Abstract.php(80): Mage_Sales_Model_Resource_Collection_Abstract->_attributeToField(Array) #2 /home/content/r/o/n/ronakkaria/html/new/admin/magentoInvoice/getInvocieList.php(43): Mage_Sales_Model_Resource_Collection_Abstract->addAttributeToFilter(Array) #3 {main} thrown in /home/content/r/o/n/ronakkaria/html/magento/app/Mage.php on line 563 I am currently using version 1.6-2rc. A: Afaik you cannot use addAttributeToFilter() to OR two attributes for the sales/order model. Use addAttributeToSearchFilter() instead: $startDate = '2011-01-01'; $finishDate = '2011-01-31'; var_dump( Mage::getModel('sales/order')->getCollection() ->addAttributeToSelect('*') ->addAttributeToSearchFilter( array( array( 'attribute' => 'status', 'eq' => 'pending' ), array( 'attribute' => 'created_at', 'from' => $startDate, 'to' => $finishDate ) ) ) ->getSelectSql(true) ); This will create a WHERE clause of: WHERE (status = 'pending') OR (created_at >= '2011-01-01' AND created_at <= '2011-01-31')
{ "language": "en", "url": "https://stackoverflow.com/questions/7549148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: use of inner.html Apologies for the strange format of this question. I've asked a couple of similar questions recently and am still at a loss. I REALLY don't know how most of this works, and I've been trying to follow various tutorials etc. on places like W3Schools.com, and with the help of people here, and although I don't fully understand, I think I'm almost there. What I'm trying to do is ONLY play a piece of video if it's the first time a visitor has arrived at the site (but it's a bit special - it's transparent, and needs to float on the page). The code below correctly sets a cookie if one doesn't exist, and checks for it on the user visiting the site. The bit I have a problem with is the syntax of the line that starts: document.getElementById('video').innerHTML = If I comment that line out, all the other cookie stuff works fine, so I'm hoping that someone can help. the errors that the firefox error console gives are: unexpected end of xml source and checkCookie is not defined I also tried throwing quotes around the whole lot, but it made no real difference. Here is the code, and thank you all in advance. Rob. <div id="video" style="position:absolute;top:125px;left:-67px;z-index:10000000"> </div> <script src="AC_RunActiveContent.js" type="text/javascript"> </script> <script type="text/javascript"> function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x = x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,7); document.getElementById('video').innerHTML = <script type="text/javascript"> AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=true&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer')</script>; } } } </script> <body onload="checkCookie()"> </body> A: Aren't you missing a few quotation marks there? document.getElementById('video').innerHTML = <script type="text/javascript"> AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=true&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer')</script>; vs document.getElementById('video').innerHTML = "<script type='text/javascript'> AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=true&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer')</script>"; A: A couple of things that may or may not lead you the answer: Check that the returned value from getElementById is not null before trying to use it, e.g.: var el = document.getElementById('video') if (el) { el.innerHTML = ... } Setting a script element as the innerHTML of an element will not execute the script. The best way to do that is to put the script into a separate file and load it using the src property of the script element, e.g. var script = document.createElement('script'); script.src = 'videoScript.js'; // or whatever you call the script file el.appendChild(script); Alternatively, you can set the script as the script element's .text property, but that will not work in some browsers: script.text = '...'; el.appendChild(script);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a more economical way of tiling a texture? I am developing a tile based 2d game. I have split things up into components such as skybackground, landbackground, town, UI and so on, with each component handling its drawing. before invoking any of the draw calls, I spritebatch.Begin() with default values so that I draw everything in 1 batch. For drawing the land mass, I repeatedly draw a square land texture across the area until i fill it up. However there is a spriteBatch mode called linear wrap that does just that. the downside would be that I will have to change my design by splitting up my one global spritebatch.begin() many times down to each component. So my question is what is better/more economical, tiling a texture manually or splitting up the begin() and end() among subcomponents? There are also other issues that may require me to split a single spriteBatch.Begin(), so how significant is 1 extra spriteBatch.Begin()? or 10 more? or 100 more? I would like to know at what scale should I start to worry about adding more begins(). A: The best solution is to have as much work happening on the GPU instead of the CPU (e.g. by taking advantage of tiling and the like) and to have as few SpriteBatch.Begin() calls as possible thus... It's sounds like the optimal solution here is not to go with either extreme. Why not just have two SpriteBatches and use on for your land and the other for everything else? e.g. Re-architect your solution so that: * *both SpriteBatches are passed into every component and let the component decide which one to use? ...or... *each component has a property that indicate which SpriteBatch it requires and pass in the appropriate one upon drawing? As for the impact of each SpriteBatch.Begin(), it really depends on your particular game (and the amount of work that needs to happen to complete the previous spriteBatch and begin the next one) so I would suggest continually testing and monitoring performance is your best way to determining when you should care.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: south (django app) doesn't alter table even though migration is saved in db Ok so basically when I deploy using Fabric, the south migrate command is being run on the remote machine and fabric outputs that each migration (i.e. 10 of them) were completed. However checking (via explain) the table that the 10th migration should alter reveals that the table was not altered (yes, the 10th migration file exists). So basically the 9th migration was applied fine, but the 10th was not, even though there is a migration entry for migration #10 in the south migration history table. Even more strangely, when I do the migration manually on the remote server, it runs fine (assuming there is no entry for migration 10 in the south migration history table) and the table is altered appropriately when checked w/ explain. Any ideas on what the problem is? Thanks guys! A: Have you upped the verbosity on the south migrations? Also you can use --show=debug to get more info out of the fab runs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I handle binding to an entity that doesn't exist? I'm trying to understand how binding works between the view model and page controls when on a 'New Item' page. For example: TransactionView.xaml.cs public TransactionsView() { InitializeComponent(); this.DataContext = App.ViewModel; } If I have a list of Transactions, I would do something like this, where AllTransactions is of type ObservableCollection. <ListBox Margin="12,15,12,0" Height="Auto" x:Name="lb_Transactions" HorizontalAlignment="Stretch" Grid.Row="2" Grid.ColumnSpan="2" ItemsSource="{Binding AllTransactions}" ItemTemplate="{StaticResource TransListDataTemplate}"> </ListBox> What happens when I have a 'New Transaction' page, which contains a simple form that contains input controls for the user to input text. When the user clicks save, I would create a new Transaction object, populate it using the data from the form, and add it using App.ViewModel.SaveTransaction(). What do I bind the controls in the UI on the New form to? A: I would probably create a new Transaction first then open the dialog which only manipulates said transaction (pass in constructor and save reference in a property for binding). If the dialog is confirmed the object can be added to the collection, if it is cancelled the object can just be ignored (and go out of scope if created as local variable).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }