text
stringlengths
8
267k
meta
dict
Q: Open a Read Only file as non read only and save/overwrite I have a number of word documents I am converting. Everything is going great until I get a file that is read only. In this case I get a Save As prompt. Is there any way to open the file in read/write format? I should have admin privileges so access isn't an issue. I'm using VB.net to open the files. More specifically doc = word.Documents.Open(path, Type.Missing, False, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing) A: To open a read-only file you need to set that attribute to false: string path = "C:\\test.txt"; FileInfo info = new FileInfo(path); info.IsReadOnly = false; StreamWriter writer = new StreamWriter(path); writer.WriteLine("This is an example."); writer.Close(); info.IsReadOnly=true; This was an example but I'm sure it will work with word files. EDIT: VB.NET equivalent: Dim path As String = "C:\test.txt" Dim info As FileInfo = New FileInfo(path) info.IsReadOnly = False Dim writer As StreamWriter = New StreamWriter(path) writer.WriteLine("This is an example.") writer.Close() info.IsReadOnly = True A: Before you open the file, check its Attributes with a FileInfo class. If the Attributes property contains FileAttributes.ReadOnly, change it and the file will no longer be read-only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Background-position +/- X pixels How do I offset the background-position, let's say 20px, from its original position? Like: $(".selector").animate("slow").css("backgroundPosition", "center -=20px"); (That obviously doesn't work... But how do I do this??) A: jQuery by default does not animate backgrounds. There is this short code that can enable that. After you add it your code should work but first fix it like this: $(".selector").animate({ "backgroundPosition": "center -=20px" },"slow"); Taken from: http://snook.ca/archives/javascript/jquery-bg-image-animations Demo: http://snook.ca/technical/jquery-bg/ A: Animating CSS background-position works with standard jQuery .animate(), as in this example. HTML <p>Lorem ipsum</p> CSS p { height:50px; width:200px; background-image:url(http://lorempixum.com/200/50); } JavaScript $('p').animate({'backgroundPosition':'-20px'}, 'slow'); A: You want to animate it or just change it? You can change it by doing something like: var newPos = parseFloat(($('.selector').css('backgroundPosition').replace('px', ''))+20) + "px"; $('.selector').css('backgroundPosition', newPos);
{ "language": "en", "url": "https://stackoverflow.com/questions/7505497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling PHP methods with varying arguments I'm writing an API class, and my general goal is for it to be easy to make any class's methods accessible via the API, without having to make any serious changes to the class itself. Essentially, I should be able to instantiate an API class instance on any class that I want to use (within my little framework), and have it just work. For example, In my API class, I have a method call, that I want to use $_GET to call the correct function from the class that I want to make accessible (let's call it Beep). So I specify an action parameter in my API, so that the action is the method of Beep to call, with the remaining arguments in $_GET being, presumably, the arguments for the method. In API->call, I can do $BeepInstance->$_GET['action'](), but I have no way of determining which arguments from $_GET to send, and in what order to send them. func_get_args will only return the list of given arguments for the function in which it is called, and I don't necessarily know the correct order in which to pass them with call_user_func_array. Has anyone tried to do something similar to this? A: Here's a solution + example that uses reflection to map your input arguments to method parameters. I also added a way to control which methods are exposed to make it more secure. class Dispatch { private $apis; public function registerAPI($api, $name, $exposedActions) { $this->apis[$name] = array( 'api' => $api, 'exposedActions' => $exposedActions ); } public function handleRequest($apiName, $action, $arguments) { if (isset($this->apis[$apiName])) { $api = $this->apis[$apiName]['api']; // check that the action is exposed if (in_array($action, $this->apis[$apiName]['exposedActions'])) { // execute action // get method reflection & parameters $reflection = new ReflectionClass($api); $method = $reflection->getMethod($action); // map $arguments to $orderedArguments for the function $orderedArguments = array(); foreach ($method->getParameters() as $parameter) { if (array_key_exists($parameter->name, $arguments)) { $orderedArguments[] = $arguments[$parameter->name]; } else if ($parameter->isOptional()) { $orderedArguments[] = $parameter->getDefaultValue(); } else { throw new InvalidArgumentException("Parameter {$parameter->name} is required"); } } // call method with ordered arguments return call_user_func_array(array($api, $action), $orderedArguments); } else { throw new InvalidArgumentException("Action {$action} is not exposed"); } } else { throw new InvalidArgumentException("API {$apiName} is not registered"); } } } class Beep { public function doBeep($tone = 15000) { echo 'beep at ' . $tone; } public function notExposedInAPI() { // do secret stuff } } Example: // dispatch.php?api=beep&action=doBeep&tone=20000 $beep = new Beep(); $dispatch = new Dispatch(); $dispatch->registerAPI($beep, 'beep', array('doBeep')); $dispatch->handleRequest($_GET['api'], $_GET['action'], $_GET); A: We did something similar in our API. We used a proxy method _methodName($p) and passed in the $_GET or $_REQUEST array. The proxy method knows the order of the parameters required for the real method, so it invokes the real method correctly. Using call_user_func_array() worked pretty well with that. Not sure if that's the best way to go about it, but it works well for us. The controller looks something like this: if (method_exists($server, "_$method")) $resp = call_user_func_array("{$server}::_$method", array($_REQUEST)); And then the model is setup like: public function test($arg1, $arg2) { ... } public function _test($p) { return $this->test($p['arg1'], $p['arg2']); } A: I'd propose to pass an associative array the the respective method. Since the assoc. array provides a name to value mapping. Moreover, never do something like this: $BeepInstance->$_GET['action']() This is highly insecure. Probably define another associate array, which maps actions passed as GET 'action' parameters to actual method names.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you center a div with Internet Explorer? i have trouble with internet explorer and centering , my question is how can i centering a div without the CENTER tag and it got to work in all the browsers , because i was using margin:auto; it works in all borwsers but it does not work in internet explorer i'm looking for something that will work in all the browsers someone told me to put text-align: center; to the body but than all the text has go to the middle so how can i do that? A: You're close. Use the CSS below: margin:0 auto; Here's a working jsFiddle. Note that I gave the div a fixed width. A: IE has spotty support for auto margins (i.e., different behavior in quirks mode). This should work in pretty much all cases though: CSS: .container { /* for IE */ text-align: center; } #the-div { /* reset text-align */ text-align: left; /* for "good" browsers */ margin: 0 auto; } HTML: <div class="container"> <div id="the-div">centered content</div> </div> A: You need to specify a width as well as margin: div.center { width:980px; margin:0px auto; } Example HTML: <html> <head></head> <body> <div class="center">CONTENT</div> </body> </html> A: Yes this works perfectly in IE. .container { /* for IE */ text-align: center; } #the-div { /* reset text-align */ text-align: left; /* for "good" browsers */ margin: 0 auto; } A: Your CSS is close, the your issue isn't the browser. The simple fix is to change the inner div class. You have your position absolute with Left 25%... Use Left 50% and it will autocorrect. Remove the left: 50% entirely and add margin: 0 auto; as previously noted on another answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: snprintf and sprintf explanation Can someone explain the output of this simple program? #include <stdio.h> int main(int argc, char *argv[]) { char charArray[1024] = ""; char charArrayAgain[1024] = ""; int number; number = 2; sprintf(charArray, "%d", number); printf("charArray : %s\n", charArray); snprintf(charArrayAgain, 1, "%d", number); printf("charArrayAgain : %s\n", charArrayAgain); return 0; } The output is: ./a.out charArray : 2 charArrayAgain : // Why isn't there a 2 here? A: snprintf(charArrayAgain, 1, "%d", number); // ^ You're specifying your maximum buffer size to be one byte. However, to store a single digit in a string, you must have two bytes (one for the digit, and one for the null terminator.) A: You've told snprintf to only print a single character into the array, which is not enough to hold the string-converted number (that's one character) and the string terminator \0, which is a second character, so snprintf is not able to store the string into the buffer you've given it. A: The second argument to snprintf is the maximum number of bytes to be written to the array (charArrayAgain). It includes the terminating '\0', so with size of 1 it's not going to write an empty string. A: Because snprintf needs space for the \0 terminator of the string. So if you tell it the buffer is 1 byte long, then there's no space for the '2'. Try with snprintf(charArrayAgain, 2, "%d", number); A: Check the return value from the snprintf() it will probably be 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Cakephp update or add new record I have an image upload that adds the filename to a table called attachments. If the id already exists then I want it to update and if not then create a new record. At the moment it creates a new record so I have multiple records forthe one id. The id's are from a table called Addon's. I am not sure how to do this in cakephp. if (!empty($this->data)) { $this->layout = null; //if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);} // restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT $tmp_file = $this->data['Attachment'][0]['file']; $tmp_file['extension'] = array_reverse(explode('.', $tmp_file['name'])); $tmp_file['extension'] = $tmp_file['extension'][0]; $tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension'])))); $this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title'])); $previous = $this->AddOn->Attachment->find('first', array('conditions'=> array('model'=>'AddOn', 'foreign_key'=>$id))); if( !empty( $previous ) ) { $this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ]; } if ($this->AddOn->save($this->data, array('validate' => 'first'))) { $id = $this->AddOn->Attachment->getLastInsertID(); $att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id); $this->set('attachment',$att[0]['attachments']); } else { $tmp_file['name'] = 'INVALID FILE TYPE'; } //debug($this->data); $this->set('file', $tmp_file); $this->RequestHandler->renderAs($this, 'ajax'); $this->render('../elements/ajax'); } A: save() and saveAll() automatically update an existing row if the id has been set. You can do something like: $previous = $this->AddOn->Attachment->find( /* whatever conditions you need */ ); if( !empty( $previous ) ) { $this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ]; } Now the old record will be updated if it exists. As a side note, the code after a successful saveAll() doesn't make much sense: first you're saving data to the database, then immediately retrieving it again. You can just keep using $this->data that already has the same content. And another side note: you should use query() only as a last resort when you can't use Cake's other methods. query("SELECT * from attachments WHERE id = ".$id) is a trivial case that can be rewritten as $this->Model->id = $id; $this->Model->read(); or using a simple $this->Model->find() query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to add tabs inside another tabs in android? I have an application which have 3 tabs on the top, I want inside the second tab to add another 5 tabs on the bottom. is that possible? if yes can you show how?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why can't I spawn a simple command with node.js? pipe(): Too many open files node.js:134 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: Error spawning That's my error. My code is: grep = spawn 'ls' UPDATE for tweet in indexedTweetsResults exec 'ls', (error, stdout, stderr) -> console.log stdout This is my code and it errors with the pipe error. Any ideas? A: YOu need to do exec = require("child_process").exec and then somewhere do exec("ls", function(error, stdout, stderr) { // handle error, stdout, stderr }); you have to write javascript....
{ "language": "en", "url": "https://stackoverflow.com/questions/7505511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to parse any date format I'm trying to make something clever in order to parse date in any international format. On my frontend I use jquery ui as a date picker and each languages has its specific date format. Fr: d/m/Y En: m/d/Y ... OK but now on the php part I have to store those date using the same format (Mysql Y-m-d). I would like to avoid using switch case and stuff like that so I started to look for another alternative. The best thing I've found is http://www.php.net/manual/en/datetime.createfromformat.php That function will enable me to parse the dates if I know the format. For example $format = 'Y-m-d'; $date = DateTime::createFromFormat($format, '2009-02-15'); Ok so that's a good start but now I'd like to find the standard date format for the current locale. So I found this : http://www.php.net/manual/en/intldateformatter.getpattern.php But I dont really know how to get it to work because I get inconstitent results: php > $i = new IntlDateFormatter("fr_FR.utf8",IntlDateFormatter::SHORT,IntlDateFormatter::NONE); php > echo $i->getPattern(); dd/MM/yy /* correct ! */ but php > $i = new IntlDateFormatter("en_US.utf8",IntlDateFormatter::SHORT,IntlDateFormatter::NONE); php > echo $i->getPattern(); M/d/yy /* wtf */ Am I missing something ? Thanks A: There is no "universal date format symbol standard". The symbol "y" could be a 2-digit year, a 4-digit year, or even a 3-letter abbreviated month (highly unlikely), depending on the source. The formatting symbols for IntlDateFormatter are documented here. As you can see from the documentation, for this implementation, "d" is the date without leading zeros, while "dd" contains the leading zeros. Both "M" and "MM" represent the month with leading zeros. The "yy" is the 2-digit year. There is enough difference between this and jQuery UI's date format symbols that you'll need a data map to map the IntlDateFormatter format symbols to jQuery UI datepicker format symbols, and vice versa. Something like this should be sufficient (untested): // PHP => jQuery $formatMap = array( 'dd' => 'dd', 'd' => 'd', 'MM' => 'mm', 'M' => 'mm', 'yy' => 'y' // and so on... ); Once you have your map set up, you can create your IntlDateFormatter based on locale, convert that format's symbols into jQuery UI date format symbols, and then send the format to the front-end. When the user posts back the chosen date, you can do the same in reverse to get back to IntlDateFormatter symbols. At that point, you can use a combination of IntlDateFormatter::setPattern() to set the format to MySQL-style, and datefmt_format() (or equivalent) to actually format the posted date. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Any workaround to get text in an iFrame on another domain in a WebBrowser? You will probably first think is not possible because of XSS restrictions. But I'm trying to access this content from an application that hosts a WebBrowser, not from javascript code in a site. I understand is not possible and should not be possible via non hacky means to access this content from javascript because this would be a big security issue. But it makes no sense to have this restriction from an application that hosts a WebBrowser. If I'd like to steel my application user's Facebook information, I could just do a Navigate("facebook.com") and do whatever I want in it. This is an application that hosts a WebBrowser, not a webpage. Also, if you go with Google Chrome to any webpage that contains an iFrame whose source is in another domain and right click its content and click Inspect Element, it will show you the content. Even simpler, if you navigate to any webpage that contains an iFrame in another domain, you will see its content. If you can see it on the WebBrowser, then you should be able to access it programmatically, because it have to be somewhere in the memory. Is there any way, not from the DOM objects because they seem to be based on the same engine as javascript and therefore restricted by XSS restrictions, but from some more low level objects such as MSHTML or SHDocVw, to access this text? A: Can this be useful for you? foreach (HtmlElement elm in webBrowser1.Document.GetElementsByTagName("iframe")) { string src = elm.GetAttribute("src"); if (src != null && src != "") { string content = new System.Net.WebClient().DownloadString(src); //or using HttpWebRequest MessageBox.Show(content); } } A: Do you just need a way to request content from code? HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webRequest.URL); request.UserAgent = webRequest.UserAgent; request.ContentType = webRequest.ContentType; request.Method = webRequest.Method; if (webRequest.BytesToWrite != null && webRequest.BytesToWrite.Length > 0) { Stream oStream = request.GetRequestStream(); oStream.Write(webRequest.BytesToWrite, 0, webRequest.BytesToWrite.Length); oStream.Close(); } // Send the request and get a response HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); // Read the response StreamReader sr = new StreamReader(resp.GetResponseStream()); // return the response to the screen string returnedValue = sr.ReadToEnd(); sr.Close(); resp.Close(); return returnedValue;
{ "language": "en", "url": "https://stackoverflow.com/questions/7505515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Does Z3_ast reference counting count references outside Z3? In Z3 there are 2 modes: automatic reference counting and manual. I understand how manual ref counting works. Thanks to example. But how does Z3 know when to delete AST node in automatic ref-counting case? Since Z3_ast is a struct from C language => it is impossible to track all assignments and usages of Z3_ast outside Z3 after it was created. Or Z3 track references inside Z3 only? That is no updates to ref counters are made if you do for example: ast1 = ast2. A: The automatic mode uses a very simple policy. Whenever an AST is returned to the user, Z3 stores it on a stack S and increments its reference counter. When the Z3_push function is executed, Z3 saves the size of the stack S. When the matching Z3_pop is executed, the size of the stack S is restored, and the reference counter of the ASTs popped from the stack is decremented. This mode is very easy to use, but it has a main problem: memory consumption. For example, if Z3_push and Z3_pop are not used, then all ASTs created by the user will never be deleted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: about broadcast receiver Hi all I want to create an application in which there is an activity say My activity. Now I want to start it with incoming call, if it is not answered within 20 seconds.Please Help me. A: You would first need to register your receiver such as.. <receiver android:name=".CustomBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> Here you register to listen for the phones state to change. Next you would want to extend the phonestateListener for your specifications. public class CustomPhoneStateListener extends PhoneStateListener { private static final String TAG = "CustomPhoneStateListener"; public void onCallStateChange(int state, String incomingNumber){ //Here you recieve the phone state being changed and are able to get the number and state. switch(state){ case TelephonyManager.CALL_STATE_RINGING: Log.d(TAG, "RINGING"); //Here you could count with for() for 20 seconds and then create a method to do what you want. break; Here you create your BroadCastReceiver... public class CustomBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "CustomBroadcastReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.v(TAG, "inside"); TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener(); telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); Bundle bundle = intent.getExtras(); String phoneNr= bundle.getString("incoming_number"); Log.v(TAG, "phoneNr: "+phoneNr); } EDIT: To count you could create a method such as public void increment() { if (count < maxCount) count++; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to convert the members of a collection used as an ItemsSource? In WPF you can use an IValueConverter or IMultiValueConverter to convert a data-bound value from say an int to a Color. I have a collection of Model objects which I would like to convert to their ViewModel representations but in this scenario, <ListBox ItemsSource="{Binding ModelItems, Converter={StaticResource ModelToViewModelConverter}" /> the converter would be written to convert the whole collection ModelItems at once. I wish to convert the items of the collection individually, is there a way to do that? I might want to use a CollectionViewSource and have some filtering logic so I don't want to have to iterate over the whole collection every time something changes. A: You cannot set the converter on the collection itself, because it would get the collection as input. You have two choices: * *Make sure your converter can also deal with collections (IEnumerable). *Use the converter within the item template. If you want to use the second approach, then use something like this: <ListBox ItemsSource="{Binding ModelItems}"> <ListBox.ItemTemplate> <DataTemplate> <ContentPresenter Content="{Binding Converter={StaticResource ModelToViewModelConverter}}" ContentTemplate="{StaticResource MyOptionalDataTemplate}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> If you don't need a custom datatemplate, then you can skip the ContentTemplate attribute. A: Yes you can. It is acting the same as with the IValueConverter. You simply treat the value parameter for the Convert method as a collection. Here is an example of Converter for a collection: public class DataConvert : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ObservableCollection<int> convertible = null; var result = value as ObservableCollection<string>; if (result != null) { convertible = new ObservableCollection<int>(); foreach (var item in result) { if (item == "first") { convertible.Add(1); } else if (item == "second") { convertible.Add(2); } else if (item == "third") { convertible.Add(3); } } } return convertible; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } In this case is just a proof of concept, but I think it should show the idea very well. The Converter converts from a simple collection of strings like this: ModelItems = new ObservableCollection<string>(); ModelItems.Add("third"); ModelItems.Add("first"); ModelItems.Add("second"); into a collection of integers corresponding to the string meaning. And here is the corresponding XAML (loc is the reference of the current assembly where is the converter): <Window.Resources> <loc:DataConvert x:Key="DataConverter"/> </Window.Resources> <Grid x:Name="MainGrid"> <ListBox ItemsSource="{Binding ModelItems, Converter={StaticResource DataConverter}}"/> </Grid> If you want to make a two way binding, you have to implement also the convert back. From the experience of working with MVVM, i suggest to use something like the Factory Pattern to transform from Model in ViewModel and backwards. A: Here is another example. I'm using MVVM Caliburn Micro. MyObjects is a list of enums in my case. <ListBox x:Name="MyObjects"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding ., Converter={StaticResource MyConverter}}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
{ "language": "en", "url": "https://stackoverflow.com/questions/7505524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: how do i pass form data from one jsp page to another? i need to transfer data from 1.jsp to 2.jsp there will be checkboxes and radio buttons and drop downs which i need to pass from 1.jsp to 2.jsp, then ill use that data in 2.jsp to generate the proper page is there a way of doing so without passing that info through the url? heres my fiddle for the form: http://jsfiddle.net/S2SxN/10/ so if i have a form with a radio button id="extra" i can get the value of it when i submit it in 1.jsp to 2.jsp right?!? 1.jsp: <form name="form1" id="form" action="/2.jsp"> <table> <tr> <td>I am interested in:</td> <td><input type="radio" name="choice" value="consume" id="con"/> Cosuming and/or distributing OTC Markets data </td> </tr> <tr> <td></td> <td><input type="radio" name="choice" value="extranet" id="extra"/> Providing connectivity to OTC Markets(Extranet)</td> </tr> <tr> <td> <input type="reset" id="re"> <input type="submit" id="sub" value="Submit"> </td> </tr> </table> </form> 2.jsp: <% if(request.getParameter("extra") != null) { %> <h2>you selected <%= request.getParameter("extra") %></h2> <% } else { %> <h2>you selected <%= request.getParameter("con") %></h2> <% } %> some reason im getting the "con" result and not the "extra", when i do get the "con" result is it null... what am i doing wrong??? A: Submit the form to 2.jsp as a post and get the values back out of the post data. Or is that not what you mean?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set the Subversion revision number in Visual Studio build I'd like to use the current Subversion revision number in my AssemblyFileVersion attribute to have this in the final complied dll. I've used the MsBuild Community Task library from my deploy script to read the revision number and update the AssemblyInfo - this somewhat works, but ... When I have an updated project and a current revsion number, say for example 100. I run the script and that will update the AssemblyInfo and a final dll with 100 as an attribute. When I then check these new AssemblyInfo files in I'll get a new revsion number (101). The problem then is that if I see a dll with a specific revsion number and like to rebuild that dll the actual revsion I need is actually the one after the revsion numnber I see ... How can this process be improved? A: Is it possible to use RCS Keywords? One of the keywords is $Revision$. This expands automatically to $Revision:xxx$ where xxx is the Subversion revision number every time you do a svn checkout or svn update. You'll have to set the property svn:keywords on your Assembly file in order for this to work: $ svn propset svn:keywords Revision Assembly.cs I do this all the time, but for the build server that runs our continuous build software. That's takes a bit of setting up, but it will automatically build the software, set the correct version number, and even deploy the software every time someone does a commit. By the way, I take it you're using AnkhSVN as your Subversion integration for VisualStudio.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the best practice for layer architecture? Right now I’m working on a very big banking solution developed in VB6. The application is massively form-based and lacks a layered architecture (all the code for data access, business logic and form manipulation is in the single form class). My job is now to refactor this code. I'm writing a proper business logic layer and data access layer in C# and the form will remain in VB. Here are code snippets: public class DistrictDAO { public string Id{get;set;} public string DistrictName { get; set; } public string CountryId { get; set; } public DateTime SetDate { get; set; } public string UserName { get; set; } public char StatusFlag { get; set; } } District Entity class, why its extension is DAO, Im not clear. public class DistrictGateway { #region private variable private DatabaseManager _databaseManager; #endregion #region Constructor public DistrictGateway(DatabaseManager databaseManager) { _databaseManager = databaseManager; } #endregion #region private methods private void SetDistrictToList(List<DistrictDAO> dataTable, int index, DistrictDAO district){ // here is some code for inserting } #endregion #region public methods try { /* query and rest of the codes */ } catch (SqlException sqlException) { Console.WriteLine(sqlException.Message); throw; } catch (FormatException formateException) { Console.WriteLine(formateException.Message); throw; } finally { _databaseManager.ConnectToDatabase(); } public void InsertDistrict() { // all query to insert object } public void UpdateDistrict() { } #endregion } DistrictGateway class responsible for database query handling Now the business layer. public class District { public string Id { get; set; } public string DistrictName { get; set; } public string CountryId { get; set; } } public class DistrictManager { #region private variable private DatabaseManager _databaseManager; private DistrictGateway _districtGateway; #endregion #region Constructor public DistrictManager() { // Instantiate the private variable using utitlity classes } #endregion #region private method private District TransformDistrictBLLToDL(DistrictDAO districtDAO) { // return converted district with lots of coding here } private DistrictDAO TransformDistrictDLToBLL(District district) { // return converted DistrictDAO with lots of coding here } private List<District> TransformDistrictBLLToDL(List<DistrictDAO> districtDAOList) { // return converted district with lots of coding here } private List<DistrictDAO> TransformDistrictDLToBLL(List<District> district) { // return converted DistrictDAO with lots of coding here } #endregion #region public methods public List<District> GetDistrict() { try { _databaseManager.ConnectToDatabase(); return TransformDistrictBLLToDL( _districtGateway.GetDistrict()); } catch (SqlException sqlException) { Console.WriteLine(sqlException.Message); throw; } catch (FormatException formateException) { Console.WriteLine(formateException.Message); throw; } finally { _databaseManager.ConnectToDatabase(); } } #endregion This is the code for the business layer. My questions are: * *Is it a perfect design? *If not, what are flaws here? *I think, this code with duplicated try catch block *What can be good design for this implementation A: Perfect? No such thing. If you have to ask here, it's probably wrong. And even if it's "perfect" right now, it won't be once time and entropy get ahold of it. The measure of how well you did will come when it's time to extend it. If your changes slide right in, you did well. If you feel like you're fighting legacy code to add changes, figure out what you did wrong and refactor it. Flaws? It's hard to tell. I don't have the energy, time, or motivation to dig very deeply right now. Can't figure out what you mean by #3. The typical layering would look like this, with the arrows showing dependencies: view <- controller -> service +-> model <- persistence (service knows about persistence) There are cross-cutting concerns for each layer: * *view knows about presentation, styling, and localization. It does whatever validation is possible to improve user experience, but doesn't include business rules. *controller is intimately tied to view. It cares about binding and validation of requests from view, routing to the appropriate service, error handling, and routing to the next view. That's it. The business logic belongs in the service, because you want it to be the same for web, tablet, mobile, etc. *service is where the business logic lives. It worries about validation according to business rules and collaborating with model and persistence layers to fulfill use cases. It knows about use cases, units of work, and transactions. *model objects can be value objects if you prefer a more functional style or be given richer business logic if you're so inclined. *persistence isolates all database interactions. You can consider cross-cutting concerns like security, transactions, monitoring, logging, etc. as aspects if you use a framework like Spring that includes aspect-oriented programming. A: Though, you aren't really asking a specific question here, it seems you may just need some general guidance to get you going on the right path. Since we don't have an in-depth view of the application as a whole as you do, it would be odd enough to suggest a single methodology for you. n-tier architecture seems to be a popular question recently, but it sparked me to write a blog series on it. Check these SO questions, and blog posts. I think they will greatly help you. * *Implement a Save method for my object *When Building an N-Tier application, how should I organize my names spaces? Blog Series on N-Tier Architecture (with example code) * *http://www.dcomproductions.com/blog/2011/09/n-tier-architecture-best-practices-part-1-overview/ A: For a big project i would recommend the MVVM pattern so you will be able to test your code fully, and later it will be much easier to extend it or change parts of it. Even you will be able to change the UI,without changing the code in the other layers. A: If your job is to refactor the code then first of all ask your boss if you should really, really should just refactor it or add functionality to it. In both cases you need an automated test harness around that code. If you are lucky and you should add functionality to it, then you at least have a starting point and a goal. Otherwise you will have to pick the starting point by yourself and do not have a goal. You can refactor code endlessly. That can be quite frustrating without a goal. Refactoring code without tests a recipe for disaster. Refactoring code means improving its structure without changing its behavior. If you do not make any tests, you cannot be sure that you did not break something. Since you need to test regularly and a lot, then these tests must be automated. Otherwise you spend too much time with manual testing. Legacy code is hard to press into some test harness. You will need to modify it in order to get it testable. Your effort to wrap tests around the code will implicitly lead to some layered structure of code. Now there is the hen and egg problem: You need to refactor the code in order to test it, but you have no tests right now. The answer is to start with “defensive” refactor techniques and do manual testing. You can find more details about these techniques in Micheal Feather's book Working Effectively with Legacy Code. If you need to refactor a lot of legacy code, you should really read it. It is a real eye opener. To your questions: * *There is no perfect design. There are only potentially better ones. *If the application does not have any unit tests, then this is the biggest flaw. Introduce tests first. On the other hand: Those code snippets are not that bad at all. It seems that DistrictDAO something like the technical version of District. Maybe there was some attempt to introduce some domain model. And: At least DistrictGateway gets the DatabaseManager injected as constructor parameter. I have seen worse. *Yes, the try-catch blocks can be seen as code duplicates, but that is nothing unusual. You can try to reduce the catch clauses with a sensible choice of Exception classes. Or you can use delegates or use some AOP techniques, but that will make the code less readable. For more see this other question. *Fit the legacy code into some test harness. A better design will implicitly emerge. Any way: First of all clarify what your boss means with refactoring code. Just refactoring code without some goal is not productive and will not make the boss happy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PNG area chart with Google Charts API? I want to make an area chart with Google's Chart API, but it needs to be the PNG format one so I can build a PDF. Is that possible? The Chart Wizard does not seem to support area charts. Also, I want to do it in perl and the URI::GoogleChart module. A: I spent a lot of time on this and discovered that I can do this: See the example visually or the code below: http://chart.apis.google.com/chart ?chxl=1:|week1|week2 &chxp=1,20,90 &chxr=0,0,120 &chxs=0,676767,11.5,0.5,l,676767|1,676767,9.5,0,_,676767 &chxt=y,x &chs=300x278 &cht=lxy &chco=FF9900,FF0000 &chds=6.667,100,0,110,0,100,0,118.333 &chd=t:-1|110,80|-1|43,32 &chdl=Total+Num|Special+Num &chdlp=t &chg=1,-1,1,0 &chls=2|2 &chma=8,0,0,7|54,2 &chtt=%23+Total+and+%23+Red+Items &chts=000000,11.5 &chm=b,FF9900,0,1,0|B,FF0000,1,9,0 Where the last line b,color,startLine,endLine,0 means fill down to endLine and B,color,startLine,arbitraryNumber,0 means fill down to the bottom of the chart. The solution came from Google's docs with some experimentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Advantage of using Object.create Similar to, but different from this question. The code below is from JavaScript: The Definitive Guide. He's basically defining an inherit method that defers to Object.create if it exists, otherwise doing plain old Javascript inheritance using constructors and swapping prototypes around. My question is, since Object.create doesn't exist on plenty of common browsers IE, what's the point of even trying to use it? It certainly clutters up the code, and one of the commenters on the previous question mentioned that Object.create isn't too fast. So what's the advantage in trying to add extra code in order to occasionally utilize this ECMA 5 function that may or may not be slower than the "old" way of doing this? function inherit(p) { if (Object.create) // If Object.create() is defined... return Object.create(p); // then just use it. function f() {}; // Define a dummy constructor function. f.prototype = p; // Set its prototype property to p. return new f(); // Use f() to create an "heir" of p. } A: The speed difference is not very noticeable, since by nature you probably won't be creating too many objects (hundreds, even thousands isn't what I call a lot), and if you are and speed is a critical issue you probably won't be coding in JS, and if both of the above aren't true, then I'm sure within a few releases of all popular JS engines the difference will be negligible (this is already the case in some). In answer to your question, the reasons aren't speed-related, but because the design pattern of Object.create is favoured to the old method (for the reasons outlined in that and other answers). They allow for proper utilisation of the ES5 property attributes (which make for more scalable objects, and thus more scalable apps), and can help with inheritance hierarchies. It's forward engineering. If we took the line of "well it isn't implemented everywhere so let's not get our feet wet", things would move very slowly. On the contrary, early and ambitious adoption helps the industry move forward, helps business decision makers support new technologies, helps developers improve and perfect new ideas and the supporting frameworks. I'm an advocate for early (but precautionary and still backward-compatible) adoption, because experience shows that waiting for enough people to support a technology can leave you waiting far too long. May IE6 be a lesson to those who think otherwise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: detach all packages while working in R While working to solve another problem I got this problem: I can remove all R objects by: rm(list = ls(all = TRUE)) Is there equivalent command that can detach installed packages during working session? > sessionInfo() R version 2.12.2 (2011-02-25) Platform: i386-pc-mingw32/i386 (32-bit) locale: [1] LC_COLLATE=English_United States.1252 [2] LC_CTYPE=English_United States.1252 [3] LC_MONETARY=English_United States.1252 [4] LC_NUMERIC=C [5] LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base require(ggplot2) Loading required package: ggplot2 Loading required package: reshape Loading required package: plyr Attaching package: 'reshape' The following object(s) are masked from 'package:plyr': round_any Loading required package: grid Loading required package: proto sessionInfo() R version 2.12.2 (2011-02-25) Platform: i386-pc-mingw32/i386 (32-bit) locale: [1] LC_COLLATE=English_United States.1252 [2] LC_CTYPE=English_United States.1252 [3] LC_MONETARY=English_United States.1252 [4] LC_NUMERIC=C [5] LC_TIME=English_United States.1252 attached base packages: [1] grid stats graphics grDevices utils datasets methods [8] base other attached packages: [1] ggplot2_0.8.9 proto_0.3-9.1 reshape_0.8.4 plyr_1.4 I tried this way, although even it worked in not a global solution : pkg <- c("package:ggplot2_0.8.9", "package:proto_0.3-9.1", "package:reshape_0.8.4", "package:plyr_1.4") detach(pkg, character.only = TRUE) Error in detach(pkg, character.only = TRUE) : invalid 'name' argument In addition: Warning message: In if (is.na(pos)) stop("invalid 'name' argument") : the condition has length > 1 and only the first element will be used What I am loking for is something global like: rm(list = ls(all = TRUE)) for objects, expect it would not remove attached base packages thanks; A: Building on Gavin's answer but not quite to a full function would be this sequence: sess.pkgs <- function (package = NULL) { z <- list() if (is.null(package)) { package <- grep("^package:", search(), value = TRUE) keep <- sapply(package, function(x) x == "package:base" || !is.null(attr(as.environment(x), "path"))) package <- sub("^package:", "", package[keep]) } pkgDesc <- lapply(package, packageDescription) if (length(package) == 0) stop("no valid packages were specified") basePkgs <- sapply(pkgDesc, function(x) !is.null(x$Priority) && x$Priority == "base") z$basePkgs <- package[basePkgs] if (any(!basePkgs)) { z$otherPkgs <- package[!basePkgs] } z } lapply(paste("package:",sess.pkgs()$otherPkgs, sep=""), detach, character.only = TRUE, unload = TRUE) A: Please try this: detachAllPackages <- function() { basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base") package.list <- search()[ifelse(unlist(gregexpr("package:",search()))==1,TRUE,FALSE)] package.list <- setdiff(package.list,basic.packages) if (length(package.list)>0) for (package in package.list) detach(package, character.only=TRUE) } detachAllPackages() A: or if you have RStudio, simply uncheck all the checked boxes in Packages Tab to detach A: #Detach all packages detachAllPackages <- function() { basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base") package.list <- search()[ifelse(unlist(gregexpr("package:",search()))==1,TRUE,FALSE)] package.list <- setdiff(package.list,basic.packages) if (length(package.list)>0) for (package in package.list) detach(package, character.only=TRUE) } detachAllPackages() this will make sure all packages gets detached apart from your basic packages A: nothing It may be worth to add solution made available by Romain François. When loaded the package nothing, which is currently available on GitHub, will unload all of the loaded packages; as in the example that Romain provides: loadedNamespaces() [1] "base" "datasets" "grDevices" "graphics" "methods" "stats" [7] "utils" require(nothing, quietly = TRUE) loadedNamespaces() [1] "base" Installation With use of the devtools package: devtools::install_github("romainfrancois/nothing") pacman An alternative approach uses pacman package available through CRAN: pacman::p_unload(pacman::p_loaded(), character.only = TRUE) A: Most of the times its the plyr vs dplyr issue. Use this in the beginning of the code: detach("package:plyr", unload=TRUE) So whenever the script runs, its clears the plyr package A: You were close. Note what ?detach has to say about the first argument name of detach(): Arguments: name: The object to detach. Defaults to ‘search()[pos]’. This can be an unquoted name or a character string but _not_ a character vector. If a number is supplied this is taken as ‘pos’. So we need to repeatedly call detach() once per element of pkg. There are a couple of other arguments we need to specify to get this to work. The first is character.only = TRUE, which allows the function to assume that name is a character string - it won't work without it. Second, we also probably want to unload any associated namespace. This can be achieved by setting unload = TRUE. So the solution is, for example: pkg <- c("package:vegan","package:permute") lapply(pkg, detach, character.only = TRUE, unload = TRUE) Here is a full example: > require(vegan) Loading required package: vegan Loading required package: permute This is vegan 2.0-0 > sessionInfo() R version 2.13.1 Patched (2011-09-13 r57007) Platform: x86_64-unknown-linux-gnu (64-bit) locale: [1] LC_CTYPE=en_GB.utf8 LC_NUMERIC=C [3] LC_TIME=en_GB.utf8 LC_COLLATE=en_GB.utf8 [5] LC_MONETARY=C LC_MESSAGES=en_GB.utf8 [7] LC_PAPER=en_GB.utf8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods [7] base other attached packages: [1] vegan_2.0-0 permute_0.7-0 loaded via a namespace (and not attached): [1] grid_2.13.1 lattice_0.19-33 tools_2.13.1 > pkg <- c("package:vegan","package:permute") > lapply(pkg, detach, character.only = TRUE, unload = TRUE) [[1]] NULL [[2]] NULL > sessionInfo() R version 2.13.1 Patched (2011-09-13 r57007) Platform: x86_64-unknown-linux-gnu (64-bit) locale: [1] LC_CTYPE=en_GB.utf8 LC_NUMERIC=C [3] LC_TIME=en_GB.utf8 LC_COLLATE=en_GB.utf8 [5] LC_MONETARY=C LC_MESSAGES=en_GB.utf8 [7] LC_PAPER=en_GB.utf8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods [7] base loaded via a namespace (and not attached): [1] grid_2.13.1 lattice_0.19-33 tools_2.13.1 If you want to turn this into a function, study the code in sessionInfo() to see how it identifies what it labels as "other attached packages:". Combine that bit of code with the idea above in a single function and you are home and dry. I'll leave that bit up to you though. A: So, someone should have simply answered the following. lapply(paste('package:',names(sessionInfo()$otherPkgs),sep=""),detach,character.only=TRUE,unload=TRUE) (edit: 6-28-19) In the latest version of R 3.6.0 please use instead. invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE, unload=TRUE)) Note the use of invisible(*) is not necessary but can be useful to prevent the NULL reply from vertically spamming the R window. (edit: 9/20/2019) In version 3.6.1 It may be helpful to convert loaded only names(sessionInfo()$loadedOnly) to explicitly attached packages first, and then detach the packages, as so. lapply(names(sessionInfo()$loadedOnly), require, character.only = TRUE) invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE, unload=TRUE, force=TRUE)) One can attempt to unload base packages via $basePkgs and also attempt using unloadNamespace(loadedNamespaces()). However these typically are fraught with errors and could break basic functionality such as causing sessionInfo() to return only errors. This typically occurs because of a lack of reversibility in the original package's design. Currently timeDate can break irreversibly, for example. (edit: 9/24/20) for version 4.0.2 The following first loads packages to test and then gives a sequence to fully detach all packages except for package "base" and "utils". It is highly recommended that one does not detach those packages. invisible(suppressMessages(suppressWarnings(lapply(c("gsl","fBasics","stringr","stringi","Rmpfr"), require, character.only = TRUE)))) invisible(suppressMessages(suppressWarnings(lapply(names(sessionInfo()$loadedOnly), require, character.only = TRUE)))) sessionInfo() #the above is a test invisible(lapply(paste0('package:', c("stringr","fBasics")), detach, character.only=TRUE,unload=TRUE)) #In the line above, I have inserted by hand what I know the package dependencies to be. A user must know this a priori or have their own automated #method to discover it. Without removing dependencies first, the user will have to cycle through loading namespaces and then detaching otherPkgs a #second time through. invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE,unload=TRUE)) bspkgs.nb<-sessionInfo()$basePkgs[sessionInfo()$basePkgs!="base"] bspkgs.nbu<-bspkgs.nb[bspkgs.nb!="utils"] names(bspkgs.nbu)<-bspkgs.nbu suppressMessages(invisible(lapply(paste0('package:', names(bspkgs.nbu)), detach, character.only=TRUE,unload=TRUE))) #again this thoroughly removes all packages and loaded namespaces except for base packages "base" and "utils" (which is highly not recommended). A: Combining bits from various answers gave the most robust solution I could find... packs <- c(names(sessionInfo()$otherPkgs), names(sessionInfo()$loadedOnly)) if(length(packs) > 0){ message('Unloading packages -- if any problems occur, please try this from a fresh R session') while(length(packs) > 0){ newpacks <- c() for(packi in 1:length(packs)){ u=try(unloadNamespace(packs[packi])) if(class(u) %in% 'try-error') newpacks <- c(newpacks,packs[packi]) } packs <- newpacks Sys.sleep(.1) } } A: Why not the below to remove all attached packages ? intialPackages = search() # added as 1st line of R script to get list of default packages # below lines are added when newly attached packages needs to be removed newPackages = search()[!(search() %in% intialPackages)] try(sapply(newPackages, detach, character.only=TRUE, unload=TRUE, force=TRUE), silent=TRUE) A: if you're having problems with packages that have similarly named functions conflicting with each other, you can always reference the namespace of the package who's function you DO want. pkg_name::function_i_want()
{ "language": "en", "url": "https://stackoverflow.com/questions/7505547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: Check If Two Sets Are Equal - Scheme ;checks to see if two sets (represented as lists) are equal (define (setsEqual? S1 S2) (cond ( (null? (cdr S1)) (in_member S1 S2)) ( (in_member (car S1) S2) (setsEqual? (cdr S1) S2)) (else false))) ;checks for an element in the list (define (in_member x list) (cond ( (eq? x (car list)) true) ( (null? list) false) (else (in_member x (cdr list))))) Can't seem to find a base case to get this working. Any help is appreciated! A: What is a set? (It's a list---okay, what is a list?) Here's a hint: there are two variants of "list": '() (aka null, aka empty) and those made with cons. Your function(s) should follow the structure of the data they consume. Yours don't. I recommend reading How to Design Programs (text available online); it will teach you a "design recipe" for tackling problems like these. The rough outline is: describe your data semi-formally (that answers what is a list?), formulate examples and tests; use your description of the data to create a template for processing that kind of data; finally, fill in the template. The key thing is that the template is determined by the data definition. It's reusable, and filling in the template for a specific function can often be done in seconds---if you've created your template and examples correctly. HtDP Chapter 9 talks about processing lists, specifically. That'll help with in_member. Chapter 17 talks about processing multiple complex arguments (eg, two lists at once). One more hint: if I were writing this function, I would make use of the following fact about sets: two sets are equal if each is a subset of the other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically generated page URLs don't work this morning This morning dynamically generated links to FB pages from our app stopped working. Link to a page like this http://www.facebook.com/pages/125567350861413 used to work just fine, now it requires page name http://www.facebook.com/pages/Daniels-Real-Estate/125567350861413 Why would this be changed? Was there a problem with old pages link format? We tweaked our code to take into account page name and made it work. But if a user changes the name of a page the link to this page will break, until we refresh the list of pages in our db. We'll write a chron job that will refresh the list of page names for all users using our app multiple times a day, but we'd prefer not having to do that. Anyone else ran into this issue? What was your workaround (other than the above)? A: While this is probably an off-topic question, you can get the page url using the graph api: http://graph.facebook.com/125567350861413 and looking at the link property. As to why Facebook changed this, you would have to ask them at their developer group or log a bug.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Upgrading Magento from 1.5.0.1 to 1.5.1.x complications I started developing for Magento 1.5.0.1 as one developer on one server. Now I'm bringing in other developers and am migrating to svn using the following strategy: Move relevant directories to a repository, and create softlinks to all those directories. There is an issue using softlinks (documented here). What I'd like to do is upgrade to 1.5.1.x which has the option in the Configuration to enable softlinks. But for some reason when I run ./mage list-upgrades I get No upgrades available Why is that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between Python's httplib and urllib2? Possible Duplicate: Python urllib vs httplib? I am just curious when I would want to use httplib over urllib2 and vice versa. A: Basically - httplib is lower level, while urllib is high-level. Use urllib2 whenever you just need to do something basic, like read the contents of a web site. Use httplib when you need to do something more crazy (hopefully rarely). A: You may wanna give python-requests a look instead of urllib2 if you want to do some higher level HTTP code. httplib is rarely used directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: months worth of data in database table help I have a table of records like the following Month Amount Sum 1 100 100 2 50 150 3 NULL NULL 4 NULL NULL 5 50 200 ETC. How do I keep a running total sum column and I'd like to cascade the previous valid sum into null records like follows in one SQL Statement? 1 100 100 2 50 150 3 0 150 4 0 150 5 50 200 Any ideas? A: This isn't something you'd typically store in the database, but rather get with a query. You would do a subquery on the table to get a sum: SELECT t1.Month, t1.Amount, SUM(SELECT t2.Amount FROM my_table t2 WHERE t2.Month <= t1.Month) FROM my_table t1 In this way I use the table twice, once as t1 and once as t2. A: Assuming the new month and amount being inserted are represented by variables @month and @amount: INSERT INTO t (Month, Amount, [Sum]) SELECT @month, CASE WHEN @amount IS NULL THEN 0 ELSE @amount END, CASE WHEN @amount IS NULL THEN SUM(Amount) ELSE SUM(Amount) + @amount END FROM t If the months are always going to consecutive, you could use MAX(Month) + 1 instead of @month as the inserted value. (Though I agree with @JHolyHead's caveat that I'd be hesitant to store a running total inside the table...) A: Either store the running sum value somewhere else where you can read and update it on every transaction, or do some clever logic in a SP that calculates it during the transaction. If I'm honest, I wouldn't store it. I'd probably prefer to calculate it in the application when I need it. That way you can filter by date/whatever other criteria you like. A: Works from version 2005 ;with a as( select month, coalesce(amount, 0) amount, row_number() over(order by /*year?,*/ month) rn from yourtable ), cte as ( select month, amount, amount [sum1] from a where rn = 1 union all select a.month, a.amount, a.amount + b.amount from cte join a on a.rn = cte.rn - 1 ) select month, amount, [sum1] from cte I surgest you do not use column names like 'sum' not even for computed columns. Don't waste a table column on a sum, imagine what happens when someone updates a column in the database. Just use a computed column in a view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating a nested list class within python I can't figure out what I'm doing wrong. I have to create a nested list(of possible solutions to a problem), so I created a class that appends a solution to a list of existing solutions(since each solution is being calculated one at a time) This function works fine: def appendList(list): #print list list2.append(list) x =0 while x < 10: x = x+1 one = "one" two = "two" appendList([(one), (two)]) print list2 with a result of: [['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two']] but when I take this exact same function and put it in a class, I get an error saying: TypeError: appendList() takes exactly 1 argument (2 given) Here's the class and how I call it: class SolutionsAppendList: list2 = [] def appendList(list): #print list list2.append(list) appendList.appendList([('one'), ('two')]) I'm sure I'm making a very basic error but I can't seem to figure out why, since I'm using the same function in the class. Any suggestions/advice would be great. Thanks A: When working with a class instance the special variable self is always passed as the first argument to the method calls. You need to modify your function declaration to accommodate this: class SolutionList: def appendList(self, list): #rest of your function here. A: Since you're dealing with classes here, it's important to use instance variables. These can be accessed by using the self keyword. And if you're dealing with class methods, be sure to make their first argument self. So, modified... class SolutionsAppendList: def __init__(self): self.list = [] def appendList(self, list): #print list self.list.append(list) What's cool about this is that you no longer need list2. Instance variables (self.list). Are different than local variables (the list you pass to the appendList() method). EDIT: I"ve also added an __init__ method, which is called once an instance of the SolutionsAppendList object is created. In my first reply, I overlooked the fact that self.* is not available outside of a method. This is the edited code (Thanks David). A: It should be: class SolutionsAppendList: list2 = [] def appendList(self, list): #print list self.list2.append(list) Class methods should always have self (reference to instance) as the first parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I use canvas for simple image animation with js? I'm making a simple animation with js. My animation is done simply by changing a picture 13 times per second. I have implemented the animation in two very simple manners. The first implementation is using a simple img tag and replacing the src attribute each time. The second implementation is using canvas and drawing the current image each time. I'm not sure which one is better.. I tend to go with the first implementation since it will work on browsers that doesn't support html5 but I'm not sure if there is a performance benefit by doing this with canvas. Please add an explanation to your answer. A: Changing the source should be the most efficient, given you're pre-loading the images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make list from two database items I want to make a list from some data that I have in my database. The first two sets of data in my database are first name and last name. I want my list to show both first and last name instead of now where it only shows the first name. How do I do that? My code looks like this: private void fillData() { Cursor contactCursor = mDbHelper.fetchAllReminders(); startManagingCursor(contactCursor); String[] from = new String[]{DbAdapter.KEY_FIRST}; int[] to = new int[]{R.id.contactlist}; SimpleCursorAdapter contacts = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from, to); setListAdapter(contacts); } A: Here is a full implementation. You will need to create a custom row and a custom Array adapter. Here is a full tutorial http://commonsware.com/Android/excerpt.pdf This will tell you everything you need to know to get this done. Also refer here where ive posted another example. How to add an EditText to a ListView EDIT: How to build a custom listview and return data from a databse You first create a listview activity. public class meeting_list extends ListActivity { Cursor model = null; meetingAdapter adapter = null; //This should be what ever your database helper is from your SQLite base. meetingHelper helper = null; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.meeting_list); helper = new meetingHelper(this); model = helper.getAll(); startManagingCursor (model); adapter = new meetingAdapter(model); setListAdapter(adapter); registerForContextMenu(getListView()); //Ondestroy is used to close the database to free up resources @Override public void onDestroy(){ super.onDestroy(); helper.close(); } @Override public void onListItemClick(ListView list, View view, int position, long id){ Intent i = new Intent(meeting_list.this, meeting_create_edit.class); // i.putExtra(ID_EXTRA, String.valueOf(id)); startActivity(i); } //Here create a class to extend the Cursor Adapter class meetingAdapter extends CursorAdapter{ meetingAdapter(Cursor c){ super(meeting_list.this, c); } @Override public void bindView(View row, Context ctxt, Cursor c) { meetingHolder holder = (meetingHolder)row.getTag(); holder.populateFrom(c, helper); } @Override public View newView(Context ctxt, Cursor c, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.mrow, parent, false); meetingHolder holder = new meetingHolder(row); row.setTag(holder); return row; } } //Here create a class to actually hold the view for the row in the listview. static class meetingHolder{ private TextView mtitle = null; private TextView maddress = null; private ImageView Icon = null; meetingHolder(View row){ mtitle=(TextView)row.findViewById(R.id.mtitle); maddress = (TextView)row.findViewById(R.id.address); Icon = (ImageView)row.findViewById(R.id.Micon); } //Here populate the row with the data from your database void populateFrom(Cursor c, meetingHelper helper){ mtitle.setText(helper.getMettingTitle(c)); maddress.setText(helper.getAddress(c)); This should do it. Just substitute your informations where it should be. This is a tutorial ive put together for you. A: Now i have tried to edit the code according to your guide, what i have done for now looks like this: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); mDbHelper = new DbAdapter(this); mDbHelper.open(); fillData(); } private void fillData() { Cursor contactCursor = mDbHelper.fetchAllReminders(); startManagingCursor(contactCursor); String[] from = new String[]{DbAdapter.KEY_FIRST}; int[] to = new int[]{R.id.contactlist}; SimpleCursorAdapter contactsfirst = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from, to); String[] from2 = new String[]{DbAdapter.KEY_LAST}; int[] to2 = new int[]{R.id.contactlist}; SimpleCursorAdapter contactslast = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from2, to2); setListAdapter(contactsfirst,last); } And my xml file looks like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/first" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40sp" /> <TextView android:id="@+id/last" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40sp" /> </LinearLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7505573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android OverlayItem.setMarker(): Change the marker for one item Trying to change the marker from an overlay item I noticed the setMarker() makes the item not visible. Here's the code sample. //Create new marker Drawable icon = this.getResources().getDrawable(R.drawable.marker); //Set the new marker to the overlay overlayItem.setMarker(icon); A: A bounding rectangle needs to be specified for the Drawable: //Create new marker Drawable icon = this.getResources().getDrawable(R.drawable.marker); //Set the bounding for the drawable icon.setBounds( 0 - icon.getIntrinsicWidth() / 2, 0 - icon.getIntrinsicHeight(), icon.getIntrinsicWidth() / 2, 0); //Set the new marker to the overlay overlayItem.setMarker(icon); A: I believe this would work: public void addOverlay(final OverlayItem overlay) { creditOverlay.add(overlay); populate(); boundCenter(customMarker); } You will have to call boundCenter or boundCenterBottom while adding overlay in map overlay list. In SetMarker() just set the custom maker.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How the wcf blocks the client when IsOneWay=false? Host : has a function which is : IsOneWay=False this function when called - pops a MessageBox in the HOST. Client : has a winform that has only button that calls the Host's func. if the function in the host IsOneWay=true - i can multi press the client button ( he doesnt care if i released the messagebox on the Host or not). but if the IsOneWay=False - then he let me press just once ( until i release the MesageBox on the Host).. host does he do that ? How the Client knows that he should be blocked until the user releases the MessageBox on the Host side ? A: The WCF host isn't responding to the client until the message box is dismissed. If you were to break into the debugger on the client side you should see that your code is still within the WCF call to the host. If you waited long enough it would eventually time out. WCF can do this because IsOneWay=false requires the server to return before the client can continue executing. When IsOneWay=true the client sends the request and the server responds right away with success allowing the client to continue (before any server code is executed). IsOneWay=false Client Server ------ | ------ 1. click --> method --> messagebox waits for OK (client can't continue until server returns) 2. continue <-- method <-- user dismisses messagebox IsOneWay=true Client Server ------ | ------ 1. click --> method --> messagebox waits for OK (client continues regardless of server state) 2. click --> method --> 2nd messagebox waits for OK user dismisses messageboxes etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7505575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQLite: Query for Latitude/Longitude Delta I have a SQLite table with fields Latitude and Longitude (neg and pos numbers) I have a latitude *delta* and a longitude *delta* of (for example '23') based on a Latitude of 50 and a longitude of 75 (again, for example) How do I query the table for a list of all records which are + or - 23 latitudes and + or - 23 longitudes when there are both positive and negative latitude and longitude values in the table. The lat/long fields are of type NUMERIC and are indexed ASC. select [fields] from [table] where latitude of 50 -+23 and longitude of 75 -+23 A: * *Lookup the delta and stating values first *Calculate the +/- values based on the delta and the starting values per-record *Use the "BETWEEN operator" to get the result (scroll down on that link to find the info) If you're using an ORM between you and the database, or a programming language on top of the DB, you might be able to do steps 1 and 2 on the fly, thereby only executing one DB query in step 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add menu items separators which work as expected on OSX? On Windows platform, with the VCL, when we want to add a separator in a menu, we add a TMenuItem with a Caption := '-'; With FireMonkey, we add a TMenuItem with a Text := '-'; It works as expected on Windows platform, the item with the Text='-' is displayed as a separator. But, when I run the same application on OSX, I have the minus sign visible... I haven't found any property on the TMenuItem to specify it is a separator... I have tried with a TMainMenu and a TMenuBar (UseOSMenu := True|False;) and I still have this issue. Any idea to create a real separator? (otherwise, I will check the OS and remove it if OSX...) A: This is a bug in FireMonkey. I am sure they will solve it. But meanwhile you can use the below code. Call the procedure FixSeparatorItemsForMac in the OnActivate event of your main form. Dont forget mac specific files in the uses list. uses ... {$IFDEF MACOS} ,Macapi.ObjectiveC,MacApi.AppKit,MacApi.Foundation,FMX.Platform.Mac {$ENDIF} {$IFDEF MACOS} Procedure FixSeparatorItemsForMenuItem(MenuItem:NSMenuItem); var i:Integer; subItem:NSMenuItem; begin if (MenuItem.hasSubmenu = false) then exit; for i := 0 to MenuItem.submenu.itemArray.count -1 do begin subItem := MenuItem.submenu.itemAtIndex(i); if (subItem.title.isEqualToString(NSSTR('-'))= true) then begin MenuItem.submenu.removeItemAtIndex(i); MenuItem.submenu.insertItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem),i); end else begin FixSeparatorItemsForMenuItem(subItem); end; end; end; Procedure FixSeparatorItemsForMac; var NSApp:NSApplication; MainMenu:NSMenu; AppItem: NSMenuItem; i: Integer; begin NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); MainMenu := NSApp.mainMenu; if (MainMenu <> nil) then begin for i := 0 to MainMenu.itemArray.count -1 do begin AppItem := mainMenu.itemAtIndex(i); FixSeparatorItemsForMenuItem(AppItem); end; end; end; {$ENDIF} A: I never programmed for the Mac, and I don't eveb have a Mac but out of curiosity I found some Apple Documentation about it. The Menu Separator item is a disabled blank menu item, maybe you can fake with that: separatorItem Returns a menu item that is used to separate logical groups of menu commands. + (NSMenuItem *)separatorItem Return Value A menu item that is used to separate logical groups of menu commands. Discussion This menu item is disabled. The default separator item is blank space. (From: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSMenuItem_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSMenuItem) A: I don't have the facilities to test this, but it's worth a try. By default, FireMonkey creates it's own fully styled menus, but set the TMenuBar.UseOSMenu property to true and it uses OS calls to create the menus. You can then combine this with the advice for creating Cocoa menus already discussed. From http://docwiki.embarcadero.com/RADStudio/en/FireMonkey_Application_Design#Menus : "Setting the TMenuBar.UseOSMenu property to True causes FireMonkey to create the menu tree with OS calls, resulting in a native menu. On Windows, this menu is at the top of the parent form, and displayed using the current Appearance theme. On Mac OS X, the menu is displayed in the global menu bar on top of the main screen whenever the application has focus."
{ "language": "en", "url": "https://stackoverflow.com/questions/7505581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: IE7 Absolute Position starts at top of line as opposed to other browsers I created a fiddle that exemplifies the problem: http://jsfiddle.net/vZtBb/ This is working exactly as I want it, but the problem is that in IE7 the absolutely positioned span (hover-tooltip-container) starts at the top of the line instead of at the bottom like it does in the other browsers. If you add a border to hover-tooltip-container, you can see this. This is a problem because I want the tooltip to go up, but the anchor to still be exposed. You should be able to mouse over the tooltip as well, but the gap in IE7 makes this impossible. If there is any way to get the hover-tooltip-container span to start in the same place on the line in IE7, IE8, and FFX, that would be perfect. Javascript is not a solution. A: The most simple thing you could do with the code you already have, is add a star hack to adjust the bottom rule within .hover-tooltip, for IE7. .hover-tooltip { display: block; padding: 15px; position: absolute; margin: 0 auto; bottom: 1em; *bottom: 0; width: 100%; border: 2px outset #c0c0c0; background-color: #f0f0f0; text-align: center; } However, the double, nested absolute positions of .hover-tooltip-container and .hover-tooltip seem unnecessary. A: I did something quite different (also renamed your classes, to much of a hassle to play with those looooooooooong name). http://jsfiddle.net/vZtBb/16/ I removed the nested absolute positionning : They are the one causing the issue, since element in absolute position are taken out of context. So, 2 solo, nested absolute positionned element means that one element is in nothing (glitchy and really not wanted). Instead of that, I placed your tooltip box in absolute, but made it start higher than the anchor by use of a negative position (top:-70px). It's sketchy a bit, but you should get my point. A: Trying putting this after the .hover-tooltip div: <div class="clear fix"></div> and this css: .clearfix:after {content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;} .clearfix {display: inline-block; } html[xmlns] .clearfix {display: block; }* html .clearfix {height: 1%; } A: I was able to solve the problem by having the "container" element float left and have relative position. This achieves the appearance of breaking out of containers but still provides a reference for the tooltip to go up from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Complaing on redeclare in same fil, but only on declare. Bug? I am getting following error message: [Wed Sep 21 21:19:46 2011] [error] [client 127.0.0.1] PHP Fatal error: Cannot redeclare db_get_groups() (previously declared in /Library/WebServer/Documents/SMICAdmin/databasescripts/db_get_groups.php:4) in /Library/WebServer/Documents/SMICAdmin/databasescripts/db_get_groups.php on line 24, referer: http://localhost/SMICAdmin/index.php As you can see, the error message complains that the same function, db_get_groups(), twice in the same script. But it's not, the entire file is included here (db_get_groups.php): <?php function db_get_groups($dbconnection){ //Line 4 $query = "SELECT id FROM groups"; $result = mysqli_query($dbconnection, $query); $rows = mysqli_fetch_all($result, MYSQLI_ASSOC); $grouplist = Array(); foreach ($rows as $key => $value) { error_log(" Value -> ".$value['id']); $grouplist[] = $value['id']; } return $grouplist; } //Line 24 ?> When doing a search for "db_get_groups" in the entire project I can only find the only declaration below and the file is inluded in two other files for usage. I did try to find if I done some import of the file more than once in some way, couldn't find any. What's the problem and how do I fix it? Feels really wired this one... A: Use: require_once("db_get_groups.php"); Or, include_once("db_get_groups.php"); Instead of just require or include. A: The bottom line is that the only way you would ever see that error message is if the function is defined twice. There's two common ways this could happen. You should double check both of these: * *Another file declares the function db_get_groups. *db_get_groups.php is included multiple times. Consider using include_once / require_once instead of just include / require. A: Try removing that definition, and calling db_get_groups(), see if there are any hints in the error logs. If that doesn't go anywhere, are you perhaps including the file more than one time? Are you including both those other files that include it somewhere? Did you use require/include or require_once/include_once? Try *_once. Are there any symbolic links to that file? If so, could you be including them as well? Finally, it could help you if you added a log() or echo() outside the function (before it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7505592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Tabs Script - Question on adding something simple I have a jQuery tabs script found here. What I am trying to do is add a class of "left" to one of them and a class of "right" to another one. I am doing this because the border radius is different for the left and right side. Since this script puts together my tabs, I can't just go in and add it how I want so I need a little help. Specifications should have a left class, and Features should have a right class. How can I add more information to the variable Tabs, and tell it which class to use? Part of my code is: var Tabs = { 'Specifications' : 'test.php?action=specifications', 'Features' : 'test.php?action=features', } /* Looping through the Tabs object: */ var z=0; $.each(Tabs,function(i,j){ /* Sequentially creating the tabs and assigning a color from the array: */ var tmp = $('<li><a href="#" class="tab">'+i+'</a></li>'); /* Setting the page data for each hyperlink: */ tmp.find('a').data('page',j); /* Adding the tab to the UL container: */ $('ul#tab').append(tmp); }) Thanks in advance! A: Add more data to your initial Tabs object: var Tabs = { 'Specifications':{class:"left",url:'test.php?action=specifications'}, 'Features':{class:"right",url:'test.php?action=features'} } /* Looping through the Tabs object: */ var z=0; $.each(Tabs,function(i,j){ /* Sequentially creating the tabs and assigning a color from the array: */ var tmp = $('<li><a href="#" class="tab">'+i+'</a></li>') /* Setting the page data for each hyperlink: */ .find('a') .addClass(j.class) .data('page',j.url) .end() /* Adding the tab to the UL container: */ .appendTo($('ul#tab')); }) A: Use power of JSON: http://jsfiddle.net/b8Kpg/3/ var Tabs = [ {'title':'Specifications', 'url': 'test.php?action=specifications', 'class': 'left'} {'title':'Features', 'url': 'test.php?action=features', 'class': 'right'} ] $(Tabs).each(function(){ /* Sequentially creating the tabs and assigning a color from the array: */ var tmp = $('<li><a href="#" class="tab">'+this.title+'</a></li>'); /* Setting the page data for each hyperlink: */ tmp.find('a').data('page',this.url); tmp.addClass(this.class); /* Adding the tab to the UL container: */ $('ul#tab').append(tmp); })
{ "language": "en", "url": "https://stackoverflow.com/questions/7505593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP CodeIgniter Batch Insert Not Accepting My Array I'm unable to get the following code to work, and it has something to do with the forming of the array. The array is actually build after a foreach() loop runs a few times, then I want to batch insert, but it comes up malformed. Why? foreach ($results as $r) { $insert_array = array( 'ListingRid' => $r['ListingRid'], 'StreetNumber' => $r['StreetNumber'], 'StreetName' => $r['StreetName'], 'City' => $r['City'], 'State' => $r['State'], 'ZipCode' => $r['ZipCode'], 'PropertyType' => $r['PropertyType'], 'Bedrooms' => $r['Bedrooms'], 'Bathrooms' => $r['Bathrooms'], 'YearBuilt' => (2011 - $r['Age']), 'Status' => $r['Status'], 'PictureCount' => $r['PictureCount'], 'SchoolDistrict' => $r['SchoolDistrict'], 'ListedSince' => $r['EntryDate'], 'MarketingRemarks' => $r['MarketingRemarks'], 'PhotoUrl' => (!empty($photo_url) ? $photo_url : 'DEFAULT'), 'ListingAgentFirstName' => $r['ListingAgentFirstName'], 'ListingAgentLastName' => $r['ListingAgentLastName'], 'ContactPhoneAreaCode1' => (!empty($a['ContactPhoneAreaCode1']) ? $a['ContactPhoneAreaCode1'] : 'DEFAULT'), 'ContactPhoneNumber1' => (!empty($a['ContactPhoneNumber1']) ? $a['ContactPhoneNumber1'] : 'DEFAULT'), 'ListingOfficeName' => (!empty($r['ListingOfficeName']) ? $r['ListingOfficeName'] : 'DEFAULT'), 'OfficePhoneComplete' => (!empty($o['OfficePhoneComplete']) ? $o['OfficePhoneComplete'] : 'DEFAULT'), 'last_updated' => date('Y-m-d H:i:s') ); $insert[] = $insert_array; } $this->db->insert_batch('listings', $insert); Here's the errors: A PHP Error was encountered Severity: Warning Message: array_keys() [function.array-keys]: The first argument should be an array Filename: database/DB_active_rec.php Line Number: 1148 A PHP Error was encountered Severity: Warning Message: sort() expects parameter 1 to be array, null given Filename: database/DB_active_rec.php Line Number: 1149 Any ideas? Thanks! A: Looks like you need to wrap your array in a second array. You're supposed to provide an array of row arrays. $insert_array = array(array(...)); A: I've reduced your code to the bare minimum and it seems to work. $i = 0; while ($i <= 10) { $insert_array = array( 'code' => 'asd' ); $insert[] = $insert_array; $i++; } $this->db->insert_batch('group', $insert); You should check the elements of the array, comment them all and de-comment them one by one until you got the culprit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there way to get DATA in embedded jRuby? I am using org.jruby.embed.ScriptingContainer class, runScriptlet and parse(script).run() both does not provide DATA (text after __END__ at the end of the script). I am curious if I can get it by using other jRuby embedding mechanisms. Besides, is it a bug? Does C Ruby do it same way too?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP regex help with replacement I can't get this regex to work: $string = 'blah blah |one|'; $search = array('/|one|/','/|two|/'); $string = preg_replace($search,"'<img src=\"\"'.str_replace('|','','\\0').'\".png\"/>'",$string); I need it to return blah blah <img src="one.png"/> in this case, but having trouble dealing with the function inside the replacement. A: Is there any reason for this "function call" (which is just a string)? How about capture groups? And you have to escape the |, because they are special characters (alternation): $string = 'blah blah |one|'; $search = array('/\\|(one)\\|/','/\\|(two)\\|/'); $string = preg_replace($search,'<img src="$1.png"/>',$string); DEMO A: You can capture the name without the |s using parenthesis: /\|(one)\|/ Then you can reference the captured name using $1 (instead of $0). A: This should work if what you want is put the text inside || as the source and also may have more than one image to convert on the same string: <?php $string = 'blah blah |source| more blah blah |another| bye'; $string = preg_replace('/\|([^\|]*)\|/',"<img src='$1.jpg' />",$string); var_dump($string); ?> A: No need to over complicate it with the array replacement and inline function. Simply capture the value between the pipes and use it directly. preg_replace('/\|(one|two)\|/', '<img src="$1.png" />', $string);
{ "language": "en", "url": "https://stackoverflow.com/questions/7505613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save partially completed change to work on other change I'm in the middle of a large change (let's say ProjectA), and have to switch gears to a different project on the same files(ProjectB). I don't want my work to get into trunk yet, and it may be a few days before I get back to ProjectA. What's the right way to set this up? Should I create a ProjectA branch and check the partially completed work into it, then switch my working copy back to trunk and work on ProjectB there? When I'm done, what do I do to merge ProjectA back into trunk? I'm comfortable with resolved for conflicts, I just need to know the commands for branching, switching, and merging... If I'm even on the right track. Currently we just do all our work in trunk. If that's part of the problem, let me know. Sorry if this is a dupe, but I've been trying to figure this out for a while. A: Assuming that doing all your work in trunk is a good idea, and assuming that you don't need to switch back and forth (that is, you complete the work on ProjectB before returning to ProjectA), I would do the following: * *Record my work on ProjectA with svn diff > ProjectA-WIP.diff *Work on ProjectB and then commit *Apply your in-progress changes from ProjectA with patch -Np0 -i ProjectA-WIP.diff *Ensure that everything is fine *Continue working on ProjectA I often follow this very same procedure. Let's say Project A is a new feature, and Project B is a bug fix; clearly I cannot mix them in the same commit, and I must fix the bug before resuming work on the new feature. How to solve conflicts When conflicts are not trivial, and patch is not helping you at all, you could make svn resolve your conflicts with a bit of trickery. After having committed your work on ProjectB: * *In your working copy, go back to the revision you produced the diff against; it is recorded in ProjectA-WIP.diff: Index: some/src/file.c =================================================================== --- some/src/file.c (revision NNNN) +++ some/src/file.c (working copy) * *If your old revision was NNNN, just use svn up -r NNNN *Apply the patch; there won't be any conflicts this time *Update svn up *Resolve any conflicts with the help of the usual Subversion's conflict handling tools
{ "language": "en", "url": "https://stackoverflow.com/questions/7505614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Changing the dimensions of Childbrowswer plugin for Phonegap in iOS I am using the Childbrowser plugin with Phonegap on iOS to do facebook connect with in my app. It all works but when the Childbrowser window opens it takes the full screen. How can I get it to just pop up in a small window in a corner, do the work then quit? A: I needed the same thing... Since I couldn't find ready-to-use solution here, I decided to do it myself... I see this is very old post so I guess you already found a solution, but just in case you haven't and someone else might find it useful and save a couple of minutes :) NOTE: my target is iPad only, so I opted for UIPopoverViewController, for an iPhone there were other ViewControllers that could be used, but the idea would be the same... What I did is edited ChildBrowserCommand.h and added: #define POPOVER_WIDTH 400 #define POPOVER_HEIGHT 300 @interface ChildBrowserCommand : PGPlugin <ChildBrowserDelegate, UIPopoverControllerDelegate> { ChildBrowserViewController* childBrowser; UIPopoverController *popover; } @property (nonatomic, retain) ChildBrowserViewController *childBrowser; @property (nonatomic, retain) UIPopoverController *popover; Also, I edited ChildBrowserCommand.m, synthetized popover, and changed: //[ cont presentModalViewController:childBrowser animated:YES ]; with: if (popover == NULL) { popover = [[UIPopoverController alloc] initWithContentViewController:childBrowser]; [popover setPopoverContentSize:CGSizeMake(POPOVER_WIDTH, POPOVER_HEIGHT) animated:YES]; popover.delegate = self; } [popover presentPopoverFromRect:cont.view.bounds inView:cont.view permittedArrowDirections:0 animated:YES]; and also added dismiss line: -(void) onClose { NSString* jsCallback = [NSString stringWithFormat:@"ChildBrowser._onClose();",@""]; [self.webView stringByEvaluatingJavaScriptFromString:jsCallback]; [popover dismissPopoverAnimated:YES]; } Finally, I removed (commented out) dismissModal from ChildBrowserViewController.m (btw, kind of wrong place to have it there in the first place): -(void)closeBrowser { if(delegate != NULL) { [delegate onClose]; } //[super dismissModalViewControllerAnimated:YES]; } As a result, ChildBrowser opens in UIPopoverViewController with specified size (and no arrows in my case, if you want some, just specify UIPopoverArrowDirection), dismisses nicely when finished and/or when clicked outside of the popover window... Best Regards, Srdjan
{ "language": "en", "url": "https://stackoverflow.com/questions/7505617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Colors in JavaScript console Can Chrome's built-in JavaScript console display colors? I want errors in red, warnings in orange and console.log's in green. Is that possible? A: Check this out: Animation in console, plus CSS (function() { var frame = 0; var frames = [ "This", "is", "SPARTA!", " ", "SPARTA!", " ", "SPARTA!", " ", "SPARTA!", " ", "SPARTA!", " ", "SPARTA!" ]; var showNext = () => { console.clear(); console.log( `%c `, "background: red; color: white; font-size: 15px; padding: 3px 41%;" ); console.log( `%c ${frames[frame]}`, "background: red; color: white; font-size: 25px; padding: 3px 40%;" ); console.log( `%c `, "background: red; color: white; font-size: 15px; padding: 3px 41%;" ); setTimeout( showNext, frames[frame] === "SPARTA!" || frames[frame] === " " ? 100 : 1500 ); // next frame and loop frame++; if (frame >= frames.length) { frame = 0; } }; showNext(); })(); https://jsfiddle.net/a8y3jhfL/ you can paste ASCII in each frame to watch an ASCII animation A: I doubt that anyone will actually see it but I have a simple solution for those who want to mix several colors in the same line: export enum Colors { Black = '\033[30m', Red = '\x1b[31m', Green = '\x1b[32m', Yellow = '\x1b[33m', Blue = '\033[34m', Magenta = '\033[35m', Cyan = '\033[36m', White = '\033[37m' } function color(text: string, color: color: Colors) { return `${color}${text}\x1b[0m`; } console.log(`This is ${color('green text', Colors.Green)} but this is black. This is red ${color('red', Colors.Red)} etc`); A: Older versions of Chrome do not allow you to get console.log()s to show in a specific color programmatically, but calling console.error() will put a red X icon on error lines and make the text red, and console.warn() gets you a yellow ! icon. You can then filter console entries with the All, Errors, Warnings, and Logs buttons beneath the console. It turns out Firebug has supported custom CSS for console.logs since 2010 and Chrome support has been added as of Chrome 24. console.log('%c Oh my heavens! ', 'background: #222; color: #bada55', 'more text'); When %c appears anywhere in the first argument, the next argument is used as the CSS to style the console line. Further arguments are concatenated (as has always been the case). A: If you want to be modern you can also use template literals here is a simple and complex example; Template literals let you use emojis, vars and way more cool stuff Simple Complex Code /* * Simple example */ console.log( `%c[line 42] | fooBar.js myFunc() -> YOU DEBUG MESSAGE HERE `, ` color:white; background-color:black; border-left: 1px solid yellow; padding: 4px;` ); /* * Complex example */ const path = `../this/goes/to/my/dir`; const line = 42; const ref = `myFunc()`; const message = `A FANCY DEBUG MESSAGE `; const styling = ` color:white; background-color:black; border-left: 1px solid yellow; padding: 8px; font-weight: 600; font-family: Courier; `; console.log( `%c ✨ F A N C Y - L O G G E R ✨`, `${styling} font-size: 16px; border-top: 1px solid yellow;` ); console.log( `%c Path: ${path} `, `${styling} font-size: 10px; font-weight: 100;` ); console.log( `%c Line: ${line}`, `${styling} font-size: 10px; font-weight: 100;` ); console.log( `%c Ref: ${ref} `, `${styling} font-size: 10px; font-weight: 100;` ); console.log( `%c Message: ${message} `, `${styling} font-size: 12px; border-bottom: 1px solid yellow;` ); A: Here is an extreme example with rainbow drop shadow. var css = "text-shadow: -1px -1px hsl(0,100%,50%), 1px 1px hsl(5.4, 100%, 50%), 3px 2px hsl(10.8, 100%, 50%), 5px 3px hsl(16.2, 100%, 50%), 7px 4px hsl(21.6, 100%, 50%), 9px 5px hsl(27, 100%, 50%), 11px 6px hsl(32.4, 100%, 50%), 13px 7px hsl(37.8, 100%, 50%), 14px 8px hsl(43.2, 100%, 50%), 16px 9px hsl(48.6, 100%, 50%), 18px 10px hsl(54, 100%, 50%), 20px 11px hsl(59.4, 100%, 50%), 22px 12px hsl(64.8, 100%, 50%), 23px 13px hsl(70.2, 100%, 50%), 25px 14px hsl(75.6, 100%, 50%), 27px 15px hsl(81, 100%, 50%), 28px 16px hsl(86.4, 100%, 50%), 30px 17px hsl(91.8, 100%, 50%), 32px 18px hsl(97.2, 100%, 50%), 33px 19px hsl(102.6, 100%, 50%), 35px 20px hsl(108, 100%, 50%), 36px 21px hsl(113.4, 100%, 50%), 38px 22px hsl(118.8, 100%, 50%), 39px 23px hsl(124.2, 100%, 50%), 41px 24px hsl(129.6, 100%, 50%), 42px 25px hsl(135, 100%, 50%), 43px 26px hsl(140.4, 100%, 50%), 45px 27px hsl(145.8, 100%, 50%), 46px 28px hsl(151.2, 100%, 50%), 47px 29px hsl(156.6, 100%, 50%), 48px 30px hsl(162, 100%, 50%), 49px 31px hsl(167.4, 100%, 50%), 50px 32px hsl(172.8, 100%, 50%), 51px 33px hsl(178.2, 100%, 50%), 52px 34px hsl(183.6, 100%, 50%), 53px 35px hsl(189, 100%, 50%), 54px 36px hsl(194.4, 100%, 50%), 55px 37px hsl(199.8, 100%, 50%), 55px 38px hsl(205.2, 100%, 50%), 56px 39px hsl(210.6, 100%, 50%), 57px 40px hsl(216, 100%, 50%), 57px 41px hsl(221.4, 100%, 50%), 58px 42px hsl(226.8, 100%, 50%), 58px 43px hsl(232.2, 100%, 50%), 58px 44px hsl(237.6, 100%, 50%), 59px 45px hsl(243, 100%, 50%), 59px 46px hsl(248.4, 100%, 50%), 59px 47px hsl(253.8, 100%, 50%), 59px 48px hsl(259.2, 100%, 50%), 59px 49px hsl(264.6, 100%, 50%), 60px 50px hsl(270, 100%, 50%), 59px 51px hsl(275.4, 100%, 50%), 59px 52px hsl(280.8, 100%, 50%), 59px 53px hsl(286.2, 100%, 50%), 59px 54px hsl(291.6, 100%, 50%), 59px 55px hsl(297, 100%, 50%), 58px 56px hsl(302.4, 100%, 50%), 58px 57px hsl(307.8, 100%, 50%), 58px 58px hsl(313.2, 100%, 50%), 57px 59px hsl(318.6, 100%, 50%), 57px 60px hsl(324, 100%, 50%), 56px 61px hsl(329.4, 100%, 50%), 55px 62px hsl(334.8, 100%, 50%), 55px 63px hsl(340.2, 100%, 50%), 54px 64px hsl(345.6, 100%, 50%), 53px 65px hsl(351, 100%, 50%), 52px 66px hsl(356.4, 100%, 50%), 51px 67px hsl(361.8, 100%, 50%), 50px 68px hsl(367.2, 100%, 50%), 49px 69px hsl(372.6, 100%, 50%), 48px 70px hsl(378, 100%, 50%), 47px 71px hsl(383.4, 100%, 50%), 46px 72px hsl(388.8, 100%, 50%), 45px 73px hsl(394.2, 100%, 50%), 43px 74px hsl(399.6, 100%, 50%), 42px 75px hsl(405, 100%, 50%), 41px 76px hsl(410.4, 100%, 50%), 39px 77px hsl(415.8, 100%, 50%), 38px 78px hsl(421.2, 100%, 50%), 36px 79px hsl(426.6, 100%, 50%), 35px 80px hsl(432, 100%, 50%), 33px 81px hsl(437.4, 100%, 50%), 32px 82px hsl(442.8, 100%, 50%), 30px 83px hsl(448.2, 100%, 50%), 28px 84px hsl(453.6, 100%, 50%), 27px 85px hsl(459, 100%, 50%), 25px 86px hsl(464.4, 100%, 50%), 23px 87px hsl(469.8, 100%, 50%), 22px 88px hsl(475.2, 100%, 50%), 20px 89px hsl(480.6, 100%, 50%), 18px 90px hsl(486, 100%, 50%), 16px 91px hsl(491.4, 100%, 50%), 14px 92px hsl(496.8, 100%, 50%), 13px 93px hsl(502.2, 100%, 50%), 11px 94px hsl(507.6, 100%, 50%), 9px 95px hsl(513, 100%, 50%), 7px 96px hsl(518.4, 100%, 50%), 5px 97px hsl(523.8, 100%, 50%), 3px 98px hsl(529.2, 100%, 50%), 1px 99px hsl(534.6, 100%, 50%), 7px 100px hsl(540, 100%, 50%), -1px 101px hsl(545.4, 100%, 50%), -3px 102px hsl(550.8, 100%, 50%), -5px 103px hsl(556.2, 100%, 50%), -7px 104px hsl(561.6, 100%, 50%), -9px 105px hsl(567, 100%, 50%), -11px 106px hsl(572.4, 100%, 50%), -13px 107px hsl(577.8, 100%, 50%), -14px 108px hsl(583.2, 100%, 50%), -16px 109px hsl(588.6, 100%, 50%), -18px 110px hsl(594, 100%, 50%), -20px 111px hsl(599.4, 100%, 50%), -22px 112px hsl(604.8, 100%, 50%), -23px 113px hsl(610.2, 100%, 50%), -25px 114px hsl(615.6, 100%, 50%), -27px 115px hsl(621, 100%, 50%), -28px 116px hsl(626.4, 100%, 50%), -30px 117px hsl(631.8, 100%, 50%), -32px 118px hsl(637.2, 100%, 50%), -33px 119px hsl(642.6, 100%, 50%), -35px 120px hsl(648, 100%, 50%), -36px 121px hsl(653.4, 100%, 50%), -38px 122px hsl(658.8, 100%, 50%), -39px 123px hsl(664.2, 100%, 50%), -41px 124px hsl(669.6, 100%, 50%), -42px 125px hsl(675, 100%, 50%), -43px 126px hsl(680.4, 100%, 50%), -45px 127px hsl(685.8, 100%, 50%), -46px 128px hsl(691.2, 100%, 50%), -47px 129px hsl(696.6, 100%, 50%), -48px 130px hsl(702, 100%, 50%), -49px 131px hsl(707.4, 100%, 50%), -50px 132px hsl(712.8, 100%, 50%), -51px 133px hsl(718.2, 100%, 50%), -52px 134px hsl(723.6, 100%, 50%), -53px 135px hsl(729, 100%, 50%), -54px 136px hsl(734.4, 100%, 50%), -55px 137px hsl(739.8, 100%, 50%), -55px 138px hsl(745.2, 100%, 50%), -56px 139px hsl(750.6, 100%, 50%), -57px 140px hsl(756, 100%, 50%), -57px 141px hsl(761.4, 100%, 50%), -58px 142px hsl(766.8, 100%, 50%), -58px 143px hsl(772.2, 100%, 50%), -58px 144px hsl(777.6, 100%, 50%), -59px 145px hsl(783, 100%, 50%), -59px 146px hsl(788.4, 100%, 50%), -59px 147px hsl(793.8, 100%, 50%), -59px 148px hsl(799.2, 100%, 50%), -59px 149px hsl(804.6, 100%, 50%), -60px 150px hsl(810, 100%, 50%), -59px 151px hsl(815.4, 100%, 50%), -59px 152px hsl(820.8, 100%, 50%), -59px 153px hsl(826.2, 100%, 50%), -59px 154px hsl(831.6, 100%, 50%), -59px 155px hsl(837, 100%, 50%), -58px 156px hsl(842.4, 100%, 50%), -58px 157px hsl(847.8, 100%, 50%), -58px 158px hsl(853.2, 100%, 50%), -57px 159px hsl(858.6, 100%, 50%), -57px 160px hsl(864, 100%, 50%), -56px 161px hsl(869.4, 100%, 50%), -55px 162px hsl(874.8, 100%, 50%), -55px 163px hsl(880.2, 100%, 50%), -54px 164px hsl(885.6, 100%, 50%), -53px 165px hsl(891, 100%, 50%), -52px 166px hsl(896.4, 100%, 50%), -51px 167px hsl(901.8, 100%, 50%), -50px 168px hsl(907.2, 100%, 50%), -49px 169px hsl(912.6, 100%, 50%), -48px 170px hsl(918, 100%, 50%), -47px 171px hsl(923.4, 100%, 50%), -46px 172px hsl(928.8, 100%, 50%), -45px 173px hsl(934.2, 100%, 50%), -43px 174px hsl(939.6, 100%, 50%), -42px 175px hsl(945, 100%, 50%), -41px 176px hsl(950.4, 100%, 50%), -39px 177px hsl(955.8, 100%, 50%), -38px 178px hsl(961.2, 100%, 50%), -36px 179px hsl(966.6, 100%, 50%), -35px 180px hsl(972, 100%, 50%), -33px 181px hsl(977.4, 100%, 50%), -32px 182px hsl(982.8, 100%, 50%), -30px 183px hsl(988.2, 100%, 50%), -28px 184px hsl(993.6, 100%, 50%), -27px 185px hsl(999, 100%, 50%), -25px 186px hsl(1004.4, 100%, 50%), -23px 187px hsl(1009.8, 100%, 50%), -22px 188px hsl(1015.2, 100%, 50%), -20px 189px hsl(1020.6, 100%, 50%), -18px 190px hsl(1026, 100%, 50%), -16px 191px hsl(1031.4, 100%, 50%), -14px 192px hsl(1036.8, 100%, 50%), -13px 193px hsl(1042.2, 100%, 50%), -11px 194px hsl(1047.6, 100%, 50%), -9px 195px hsl(1053, 100%, 50%), -7px 196px hsl(1058.4, 100%, 50%), -5px 197px hsl(1063.8, 100%, 50%), -3px 198px hsl(1069.2, 100%, 50%), -1px 199px hsl(1074.6, 100%, 50%), -1px 200px hsl(1080, 100%, 50%), 1px 201px hsl(1085.4, 100%, 50%), 3px 202px hsl(1090.8, 100%, 50%), 5px 203px hsl(1096.2, 100%, 50%), 7px 204px hsl(1101.6, 100%, 50%), 9px 205px hsl(1107, 100%, 50%), 11px 206px hsl(1112.4, 100%, 50%), 13px 207px hsl(1117.8, 100%, 50%), 14px 208px hsl(1123.2, 100%, 50%), 16px 209px hsl(1128.6, 100%, 50%), 18px 210px hsl(1134, 100%, 50%), 20px 211px hsl(1139.4, 100%, 50%), 22px 212px hsl(1144.8, 100%, 50%), 23px 213px hsl(1150.2, 100%, 50%), 25px 214px hsl(1155.6, 100%, 50%), 27px 215px hsl(1161, 100%, 50%), 28px 216px hsl(1166.4, 100%, 50%), 30px 217px hsl(1171.8, 100%, 50%), 32px 218px hsl(1177.2, 100%, 50%), 33px 219px hsl(1182.6, 100%, 50%), 35px 220px hsl(1188, 100%, 50%), 36px 221px hsl(1193.4, 100%, 50%), 38px 222px hsl(1198.8, 100%, 50%), 39px 223px hsl(1204.2, 100%, 50%), 41px 224px hsl(1209.6, 100%, 50%), 42px 225px hsl(1215, 100%, 50%), 43px 226px hsl(1220.4, 100%, 50%), 45px 227px hsl(1225.8, 100%, 50%), 46px 228px hsl(1231.2, 100%, 50%), 47px 229px hsl(1236.6, 100%, 50%), 48px 230px hsl(1242, 100%, 50%), 49px 231px hsl(1247.4, 100%, 50%), 50px 232px hsl(1252.8, 100%, 50%), 51px 233px hsl(1258.2, 100%, 50%), 52px 234px hsl(1263.6, 100%, 50%), 53px 235px hsl(1269, 100%, 50%), 54px 236px hsl(1274.4, 100%, 50%), 55px 237px hsl(1279.8, 100%, 50%), 55px 238px hsl(1285.2, 100%, 50%), 56px 239px hsl(1290.6, 100%, 50%), 57px 240px hsl(1296, 100%, 50%), 57px 241px hsl(1301.4, 100%, 50%), 58px 242px hsl(1306.8, 100%, 50%), 58px 243px hsl(1312.2, 100%, 50%), 58px 244px hsl(1317.6, 100%, 50%), 59px 245px hsl(1323, 100%, 50%), 59px 246px hsl(1328.4, 100%, 50%), 59px 247px hsl(1333.8, 100%, 50%), 59px 248px hsl(1339.2, 100%, 50%), 59px 249px hsl(1344.6, 100%, 50%), 60px 250px hsl(1350, 100%, 50%), 59px 251px hsl(1355.4, 100%, 50%), 59px 252px hsl(1360.8, 100%, 50%), 59px 253px hsl(1366.2, 100%, 50%), 59px 254px hsl(1371.6, 100%, 50%), 59px 255px hsl(1377, 100%, 50%), 58px 256px hsl(1382.4, 100%, 50%), 58px 257px hsl(1387.8, 100%, 50%), 58px 258px hsl(1393.2, 100%, 50%), 57px 259px hsl(1398.6, 100%, 50%), 57px 260px hsl(1404, 100%, 50%), 56px 261px hsl(1409.4, 100%, 50%), 55px 262px hsl(1414.8, 100%, 50%), 55px 263px hsl(1420.2, 100%, 50%), 54px 264px hsl(1425.6, 100%, 50%), 53px 265px hsl(1431, 100%, 50%), 52px 266px hsl(1436.4, 100%, 50%), 51px 267px hsl(1441.8, 100%, 50%), 50px 268px hsl(1447.2, 100%, 50%), 49px 269px hsl(1452.6, 100%, 50%), 48px 270px hsl(1458, 100%, 50%), 47px 271px hsl(1463.4, 100%, 50%), 46px 272px hsl(1468.8, 100%, 50%), 45px 273px hsl(1474.2, 100%, 50%), 43px 274px hsl(1479.6, 100%, 50%), 42px 275px hsl(1485, 100%, 50%), 41px 276px hsl(1490.4, 100%, 50%), 39px 277px hsl(1495.8, 100%, 50%), 38px 278px hsl(1501.2, 100%, 50%), 36px 279px hsl(1506.6, 100%, 50%), 35px 280px hsl(1512, 100%, 50%), 33px 281px hsl(1517.4, 100%, 50%), 32px 282px hsl(1522.8, 100%, 50%), 30px 283px hsl(1528.2, 100%, 50%), 28px 284px hsl(1533.6, 100%, 50%), 27px 285px hsl(1539, 100%, 50%), 25px 286px hsl(1544.4, 100%, 50%), 23px 287px hsl(1549.8, 100%, 50%), 22px 288px hsl(1555.2, 100%, 50%), 20px 289px hsl(1560.6, 100%, 50%), 18px 290px hsl(1566, 100%, 50%), 16px 291px hsl(1571.4, 100%, 50%), 14px 292px hsl(1576.8, 100%, 50%), 13px 293px hsl(1582.2, 100%, 50%), 11px 294px hsl(1587.6, 100%, 50%), 9px 295px hsl(1593, 100%, 50%), 7px 296px hsl(1598.4, 100%, 50%), 5px 297px hsl(1603.8, 100%, 50%), 3px 298px hsl(1609.2, 100%, 50%), 1px 299px hsl(1614.6, 100%, 50%), 2px 300px hsl(1620, 100%, 50%), -1px 301px hsl(1625.4, 100%, 50%), -3px 302px hsl(1630.8, 100%, 50%), -5px 303px hsl(1636.2, 100%, 50%), -7px 304px hsl(1641.6, 100%, 50%), -9px 305px hsl(1647, 100%, 50%), -11px 306px hsl(1652.4, 100%, 50%), -13px 307px hsl(1657.8, 100%, 50%), -14px 308px hsl(1663.2, 100%, 50%), -16px 309px hsl(1668.6, 100%, 50%), -18px 310px hsl(1674, 100%, 50%), -20px 311px hsl(1679.4, 100%, 50%), -22px 312px hsl(1684.8, 100%, 50%), -23px 313px hsl(1690.2, 100%, 50%), -25px 314px hsl(1695.6, 100%, 50%), -27px 315px hsl(1701, 100%, 50%), -28px 316px hsl(1706.4, 100%, 50%), -30px 317px hsl(1711.8, 100%, 50%), -32px 318px hsl(1717.2, 100%, 50%), -33px 319px hsl(1722.6, 100%, 50%), -35px 320px hsl(1728, 100%, 50%), -36px 321px hsl(1733.4, 100%, 50%), -38px 322px hsl(1738.8, 100%, 50%), -39px 323px hsl(1744.2, 100%, 50%), -41px 324px hsl(1749.6, 100%, 50%), -42px 325px hsl(1755, 100%, 50%), -43px 326px hsl(1760.4, 100%, 50%), -45px 327px hsl(1765.8, 100%, 50%), -46px 328px hsl(1771.2, 100%, 50%), -47px 329px hsl(1776.6, 100%, 50%), -48px 330px hsl(1782, 100%, 50%), -49px 331px hsl(1787.4, 100%, 50%), -50px 332px hsl(1792.8, 100%, 50%), -51px 333px hsl(1798.2, 100%, 50%), -52px 334px hsl(1803.6, 100%, 50%), -53px 335px hsl(1809, 100%, 50%), -54px 336px hsl(1814.4, 100%, 50%), -55px 337px hsl(1819.8, 100%, 50%), -55px 338px hsl(1825.2, 100%, 50%), -56px 339px hsl(1830.6, 100%, 50%), -57px 340px hsl(1836, 100%, 50%), -57px 341px hsl(1841.4, 100%, 50%), -58px 342px hsl(1846.8, 100%, 50%), -58px 343px hsl(1852.2, 100%, 50%), -58px 344px hsl(1857.6, 100%, 50%), -59px 345px hsl(1863, 100%, 50%), -59px 346px hsl(1868.4, 100%, 50%), -59px 347px hsl(1873.8, 100%, 50%), -59px 348px hsl(1879.2, 100%, 50%), -59px 349px hsl(1884.6, 100%, 50%), -60px 350px hsl(1890, 100%, 50%), -59px 351px hsl(1895.4, 100%, 50%), -59px 352px hsl(1900.8, 100%, 50%), -59px 353px hsl(1906.2, 100%, 50%), -59px 354px hsl(1911.6, 100%, 50%), -59px 355px hsl(1917, 100%, 50%), -58px 356px hsl(1922.4, 100%, 50%), -58px 357px hsl(1927.8, 100%, 50%), -58px 358px hsl(1933.2, 100%, 50%), -57px 359px hsl(1938.6, 100%, 50%), -57px 360px hsl(1944, 100%, 50%), -56px 361px hsl(1949.4, 100%, 50%), -55px 362px hsl(1954.8, 100%, 50%), -55px 363px hsl(1960.2, 100%, 50%), -54px 364px hsl(1965.6, 100%, 50%), -53px 365px hsl(1971, 100%, 50%), -52px 366px hsl(1976.4, 100%, 50%), -51px 367px hsl(1981.8, 100%, 50%), -50px 368px hsl(1987.2, 100%, 50%), -49px 369px hsl(1992.6, 100%, 50%), -48px 370px hsl(1998, 100%, 50%), -47px 371px hsl(2003.4, 100%, 50%), -46px 372px hsl(2008.8, 100%, 50%), -45px 373px hsl(2014.2, 100%, 50%), -43px 374px hsl(2019.6, 100%, 50%), -42px 375px hsl(2025, 100%, 50%), -41px 376px hsl(2030.4, 100%, 50%), -39px 377px hsl(2035.8, 100%, 50%), -38px 378px hsl(2041.2, 100%, 50%), -36px 379px hsl(2046.6, 100%, 50%), -35px 380px hsl(2052, 100%, 50%), -33px 381px hsl(2057.4, 100%, 50%), -32px 382px hsl(2062.8, 100%, 50%), -30px 383px hsl(2068.2, 100%, 50%), -28px 384px hsl(2073.6, 100%, 50%), -27px 385px hsl(2079, 100%, 50%), -25px 386px hsl(2084.4, 100%, 50%), -23px 387px hsl(2089.8, 100%, 50%), -22px 388px hsl(2095.2, 100%, 50%), -20px 389px hsl(2100.6, 100%, 50%), -18px 390px hsl(2106, 100%, 50%), -16px 391px hsl(2111.4, 100%, 50%), -14px 392px hsl(2116.8, 100%, 50%), -13px 393px hsl(2122.2, 100%, 50%), -11px 394px hsl(2127.6, 100%, 50%), -9px 395px hsl(2133, 100%, 50%), -7px 396px hsl(2138.4, 100%, 50%), -5px 397px hsl(2143.8, 100%, 50%), -3px 398px hsl(2149.2, 100%, 50%), -1px 399px hsl(2154.6, 100%, 50%); font-size: 40px;"; console.log("%cExample %s", css, 'all code runs happy'); A: from Chrome 60, they removed the facility of blue text color while writing console.info and does many much changes in console API. if you write a string literal in the es6 pattern, using the backticks `` as the identifier (called as template string ) in console.log() then below way can colorize the console output. console.log(`%cToday date=>%c${new Date()}`,`color:#F74C2F`, `color:green`); // output :Today date (in red color) => Date (in green color) A: To chain CSS3 styles which spans across multiple lines, you can do like this, var styles = [ 'background: linear-gradient(#D33106, #571402)' , 'border: 1px solid #3E0E02' , 'color: white' , 'display: block' , 'text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)' , 'box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset' , 'line-height: 40px' , 'text-align: center' , 'font-weight: bold' ].join(';'); console.log('%c a spicy log message ?', styles); Result Find more :- https://coderwall.com/p/fskzdw/colorful-console-log Cheers. A: By default, there are few inbuilt console methods to display warnings, errors and normal console along with the specific icons and text colors. console.log('console.log'); console.warn('console.warn'); console.error('console.error'); But If you still want to apply your own styles, You can use %c with the message and CSS style rules as a second parameter. console.log('%cconsole.log', 'color: green;'); console.warn('%cconsole.warn', 'color: green;'); console.error('%cconsole.error', 'color: green;'); Note : While running the above code snippets, Kindly check the results in the browser console instead of snippet results. A: I wrote template-colors-web https://github.com/icodeforlove/Console.js to allow us to do this a bit easier console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red); The above would be extremely hard to do with the default console.log. For a live interactive demo click here. A: Update: I have written a JavaScript library last year for myself. It contains other features e.g verbosity for debug logs and also provides a download logs method that exports a log file. Have a look at the JS Logger library and its documentation. I know It's a bit late to answer but as the OP asked to get custom color messages in console for different options. Everyone is passing the color style property in each console.log() statement which confuses the reader by creating complexity in the code and also harm the overall look & feel of the code. What I suggest is to write a function with few predetermined colors (e.g success, error, info, warning, default colors) which will be applied on the basis of the parameter passed to the function. It improves the readability and reduces the complexity in the code. It is too easy to maintain and further extend according to your needs. Given below is a JavaScript function that you have to write once and than use it again and again. function colorLog(message, color) { color = color || "black"; switch (color) { case "success": color = "Green"; break; case "info": color = "DodgerBlue"; break; case "error": color = "Red"; break; case "warning": color = "Orange"; break; default: color = color; } console.log("%c" + message, "color:" + color); } Output: The default color is black and you don't have to pass any keyword as parameter in that case. In other cases, you should pass success, error, warning, or info keywords for desired results. Here is working JSFiddle. See output in the browser's console. A: I actually just found this by accident being curious with what would happen but you can actually use bash colouring flags to set the colour of an output in Chrome: console.log('\x1b[36m Hello \x1b[34m Colored \x1b[35m World!'); console.log('\x1B[31mHello\x1B[34m World'); console.log('\x1b[43mHighlighted'); Output: See this link for how colour flags work: https://misc.flogisoft.com/bash/tip_colors_and_formatting Basically use the \x1b or \x1B in place of \e. eg. \x1b[31m and all text after that will be switched to the new colour. I haven't tried this in any other browser though, but thought it worth mentioning. A: OPTION 1 // log-css.js v2 const log = console.log.bind() const css = (text, options) => { let cssOptions = '' for (let prop in options) { const value = options[prop] prop = camelCaseToDashCase(prop) cssOptions += `${prop}: ${value}; ` } return [`%c${text}`, cssOptions.trim()] function camelCaseToDashCase(value) { return value.replace(/[A-Z]/g, matched => `-${matched.toLowerCase()}`) } } Example: log(...css('Example =P', { backgroundColor: 'blue', color: 'white', // fontFamily: 'Consolas', fontSize: '25px', fontWeight: '700', // lineHeight: '25px', padding: '7px 7px' })) OPTION 2 I create now the log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY // log-css.js v1 const log = console.log.bind(); const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) { return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')]; }; Example: log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px')); A: Emoji You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color. But you can use emojis instead! for example, you can use⚠️ for warning messages and for error messages. Or simply use these notebooks as a color: console.log(': error message'); console.log(': warning message'); console.log(': ok status message'); console.log(': action message'); console.log(': canceled status message'); console.log(': Or anything you like and want to recognize immediately by color'); Bonus: This method also helps you to quickly scan and find logs directly in the source code. But some Linux distribution default emoji font is not colorful by default and you may want to make them colorful, first. How to open emoji panel? mac os: control + command + space windows: win + . linux: control + . or control + ; A: colors = { reset: '\033[0m', //text color black: '\033[30m', red: '\033[31m', green: '\033[32m', yellow: '\033[33m', blue: '\033[34m', magenta: '\033[35m', cyan: '\033[36m', white: '\033[37m', //background color blackBg: '\033[40m', redBg: '\033[41m', greenBg: '\033[42m', yellowBg: '\033[43m', blueBg: '\033[44m', magentaBg: '\033[45m', cyanBg: '\033[46m', whiteBg: '\033[47m' } console.log('\033[31m this is red color on text'); console.log('\033[0m this is reset'); console.log('\033[41m this is red color on background'); A: I recently wanted to solve for a similar issue and constructed a small function to color only keywords i cared about which were easily identifiable by surrounding curly braces {keyword}. This worked like a charm: var text = 'some text with some {special} formatting on this {keyword} and this {keyword}' var splitText = text.split(' '); var cssRules = []; var styledText = ''; _.each(splitText, (split) => { if (/^\{/.test(split)) { cssRules.push('color:blue'); } else { cssRules.push('color:inherit') } styledText += `%c${split} ` }); console.log(styledText , ...cssRules) technically you could swap out the if statement with a switch/case statement to allow multiple stylings for different reasons A: I wrote a reallllllllllllllllly simple plugin for myself several years ago: To add to your page all you need to do is put this in the head: <script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript"> Then in JS: jconsole.color.red.log('hellllooo world'); The framework has code for: jconsole.color.red.log(); jconsole.color.orange.log(); jconsole.color.yellow.log(); jconsole.color.green.log(); jconsole.color.blue.log(); jconsole.color.purple.log(); jconsole.color.teal.log(); as well as: jconsole.css.log("hello world","color:red;"); for any other css. The above is designed with the following syntax: jconsole.css.log(message to log,css code to style the logged message) A: There are a series of inbuilt functions for coloring the console log: //For pink background and red text console.error("Hello World"); //For yellow background and brown text console.warn("Hello World"); //For just a INFO symbol at the beginning of the text console.info("Hello World"); //for custom colored text console.log('%cHello World','color:blue'); //here blue could be replaced by any color code //for custom colored text with custom background text console.log('%cHello World','background:red;color:#fff') A: Yes just add %c sign before your message and the style followed by your message. console.log('%c Hello World','color:red;border:1px solid dodgerblue'); If you are using node and want to color console in terminal then you can use escape sequences like console.log('\x1b[33m%s\x1b[0m', 'hi!') will color console yellow, else you can use libraries like chalk to color console const chalk = require('chalk') console.log(chalk.yellow('hi!')) A: I wrote a npm module that gives one the possibility to pass: * *Custom colors - to both text and background; *Prefixes - to help identify the source, like [MyFunction] *Types - like warning, success, info and other predefined message types https://www.npmjs.com/package/console-log-plus Output (with custom prefixes): clp({ type: 'ok', prefix: 'Okay', message: 'you bet' }); clp({ type: 'error', prefix: 'Ouch', message: 'you bet' }); clp({ type: 'warning', prefix: 'I told you', message: 'you bet' }); clp({ type: 'attention', prefix: 'Watch it!', message: 'you bet' }); clp({ type: 'success', prefix: 'Awesome!', message: 'you bet' }); clp({ type: 'info', prefix: 'FYI', message: 'you bet' }); clp({ type: 'default', prefix: 'No fun', message: 'you bet' }); Output (without custom prefixes): Input: clp({ type: 'ok', message: 'you bet' }); clp({ type: 'error', message: 'you bet' }); clp({ type: 'warning', message: 'you bet' }); clp({ type: 'attention', message: 'you bet' }); clp({ type: 'success', message: 'you bet' }); clp({ type: 'info', message: 'you bet' }); clp({ type: 'default', message: 'you bet' }); To make sure the user won't render an invalid color, I wrote a color validator as well. It will validate colors by name, hex, rgb, rgba, hsl or hsla values A: I created a package for the same. cslog Install it with npm i cslog Use It like this import log from 'cslog' log.h2("This is heading 2") log.p("This is colored paragraph") log.d(person, "Person Info") You can give your custom colors as well. here A: Google has documented this https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css The CSS format specifier allows you to customize the display in the console. Start the string with the specifier and give the style you wish to apply as the second parameter. One example: console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large"); A: In Chrome & Firefox (+31) you can add CSS in console.log messages: console.log('%c Oh my heavens! ', 'background: #222; color: #bada55'); The same can be applied for adding multiple CSS to same command. References * *MDN: Styling console output *Chrome: Console API Reference A: I've discovered that you can make logs with colors using ANSI color codes, what makes easier to find specific messages in debug. Try it: console.log( "\u001b[1;31m Red message" ); console.log( "\u001b[1;32m Green message" ); console.log( "\u001b[1;33m Yellow message" ); console.log( "\u001b[1;34m Blue message" ); console.log( "\u001b[1;35m Purple message" ); console.log( "\u001b[1;36m Cyan message" ); A: You can try: console.log("%cI am red %cI am green", "color: red", "color: green"); The output: A: template system, useful if you want to create colorful line text without creating full style for every block var tpl = 'background-color:greenyellow; border:3px solid orange; font-size:18px; font-weight: bold;padding:3px 5px;color:'; console.log('%cMagenta %cRed %cBlue', `${tpl} magenta`, `${tpl} Red`,`${tpl} #4274fb`); A: You can use a custom stylesheet to color your debugger. You can put this code in C:\Documents and Settings&lt;User Name>\Local Settings\Application Data\Google\Chrome\User Data\Default\User StyleSheets\Custom.css if you are in WinXP, but the directory varies by OS. .console-error-level .console-message-text{ color: red; } .console-warning-level .console-message-text { color: orange; } .console-log-level .console-message-text { color:green; } A: const coloring = fn => ({ background, color = 'white' }) => (...text) => fn(`%c${text.join('')}`, `color:${color};background:${background}`); const colors = { primary: '#007bff', success: '#28a745', warning: '#ffc107', danger: '#dc3545', info: '#17a2b8', }; const dir = (key = '', value = {}) => { logs.primary(`++++++++++++start:${key}++++++++++++++`); console.dir(value); logs.primary(`++++++++++++end:${key}++++++++++++++`); }; const logs = Object.keys(colors) .reduce((prev, curr) => ({ ...prev, [curr]: coloring(console.log)({ background: colors[curr] }) }), { dir }); logs.success('hello succes'); logs.warning('hello fail'); A: Here's another approach (in Typescript), which overrides the console.log function and inspects the message passed in order to apply CSS formatting depending on a beginning token in the message. A benefit of this method is the callee's don't need to use some wrapper console.log function, they can stick to using vanilla console.log() and so if this override ever goes away the functionality will just revert to the default console.log: // An example of disabling logging depending on environment: const isLoggingEnabled = process.env.NODE_ENV !== 'production'; // Store the original logging function so we can trigger it later const originalConsoleLog = console.log; // Override logging to perform our own logic console.log = (args: any) => { if (!isLoggingEnabled) { return; } // Define some tokens and their corresponding CSS const parsing = [ { token: '[SUCCESS]', css: 'color: green; font-weight: bold;', }, { token: '[ERROR]', css: 'color: red; font-weight: bold;', }, { token: '[WARN]', css: 'color: orange; font-weight: bold;', }, { token: '[DEBUG]', css: 'color: blue;', }, ]; // Currently only supports console.log(...) with a single string argument. if (typeof args === 'string') { const message: string = args; let formattedArgs: string[] = []; for (let i = 0; i < parsing.length; i += 1) { const parser = parsing[i]; if (args.startsWith(parser.token)) { formattedArgs = [`%c${message.substring(parser.token.length + 1, message.length)}`, parser.css]; break; } } originalConsoleLog.apply(console, formattedArgs); } else { originalConsoleLog.apply(console, args); } }; Example usage: console.log('[ERROR] Something went wrong!'); Output: A: If you want to color your terminal console, then you can use npm package chalk npm i chalk
{ "language": "en", "url": "https://stackoverflow.com/questions/7505623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1161" }
Q: What is the need for many-to-one mapping in hibernate? Why don't we just specify the table name and column name? How specifying many-to-one helps in generating query? A: Hibernate is an ORM tool. Object Relational Mapping. The tool needs to understand the relationships between classes. If you continue down your line of thought, why do we need to map one-to-many, or any other relationship? Lets say you have a class Child, many of which can be on instances of Parent. If your relationship is bidirectional, a child instance would have a reference to an instance of Parent. So if you loaded a child instance, hibernate needs to know how that child is related to its Parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coding a javascript carousel slider from scratch with jquery - using variables So my code works to a degree. I have a slider, with some left & right buttons. What I'm trying to do is make sure that it can't slide past a certain point one way or the other, as there will be a fixed number of slides. So I've introduced a variable called slideWidth which I'm trying to use to keep track of the current margin. If it reaches a certain number I only want one button to work. My code below doesn't seem to change though - I can hit the left button unlimited times, and never the right... <script> $(document).ready(function() { var slideWidth=0; if (slideWidth == 0) { $("#slideLeft").click(function(){ $(".slideOverflowHide").animate({"margin-left": "-=1100px"}, "slow"); slideWidth = slideWidth - 1100; }); }else if (slideWidth == -3300){ $("#slideRight").click(function(){ $(".slideOverflowHide").animate({"margin-left": "+=1100px"}, "slow"); slideWidth = slideWidth + 1100; }); }else{ $("#slideRight").click(function(){ $(".slideOverflowHide").animate({"margin-left": "+=1100px"}, "slow"); slideWidth = slideWidth + 1100; }); $("#slideLeft").click(function(){ $(".slideOverflowHide").animate({"margin-left": "-=1100px"}, "slow"); slideWidth = slideWidth - 1100; }); } }); </script> A: This code is inside out. You should be performing the width check inside the click functions. $("#slideLeft").click(function(){ if(slideWidth == 0) { A: The if check runs only once on document.ready when slideWidth is still 0, so the click event never gets attached to the slideRight button. Also, the if check needs to be moved inside the click events, so it would run every time you click one of the buttons (left or right). Plus, you only need to attach the click events once per button. I can see your trying to do it twice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error: wrong number of arguments (1 for 0) => if no debug or .to_yaml used I get an error with the following code, but with a logger row or debug is the output correct. It's a little bit strange for me. (Rails 3.1.0 and 3.0.9 and Ruby 1.8.7) Controller contains: def index @privatmessages = Privatmessage.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @privatmessages } end end index.htm.erb <% @privatmessages.each do |privatmessage| %> <%= privatmessage.id %> <% end %> That code produce the error: ArgumentError in Privatmessages#index Showing ../app/views/privatmessages/index.html.erb where line #2 raised: wrong number of arguments (1 for 0) But the output is correct and without errors, if I add the following line at the controller: logger.info "Messages: {#@privatmessages.to_yaml}" or if I add inside of the each loop at the index.html.erb the line: <%= debug privatmessage %> Has anyone an advice for me? A: Issue found and solved! The problem was that I used "send" as a column name in the table, but "send" is a reserved method for Rails core. After renaming the column in the table to "sendout" it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C#: Decoding JPEG images with 12-bit precision using Silverlight FJCore library? In my C# Silverlight application, I am trying to decode DICOM images in compressed JPEG transfer syntax, using the FJCore class library. The DICOM images are normally compressed with 12-bit precision. When trying to decode such an image using the original FJCore source code, I get an exception saying "Unsupported codec type", because in the original FJCore implementation only SOF0 (Baseline DCT) and SOF2 (Progressive DCT) Start-of-Frame markers are supported. If I change the implementation to also accept the SOF1 marker (Extended Sequential DCT) and treat SOF1 frames the same way as SOF0 frames, the images are decoded, but only 8 bits are accounted for. A typical 12-bit precision image now looks like this after decoding with the modified FJCore library: Ideally, the image should look like this: As far as I have been able to tell from the FJCore implementation, the image precision is recorded in the JpegFrame class, but it is never used. The original FJCore implementation seems to only fully support grayscale images with 8 bit precision. I am planning to "take the bull by the horns" and try to extend FJCore myself to support 12-bit precision for grayscale images. But before I do, I thought I should pose the question here in StackOverflow to see if anyone has encountered and solved this problem before? In that case, I would be very happy to learn how you solved the problem. Many thanks in advance! Anders @ Cureos A: I just updated my own JPEG decoder to handle the extended mode and what I needed to change was my inverse DCT. Before changing the code, the output looked similar to your sample image above. I have always stored 16-bit coefficient values from the entropy decode, but my DCT calculation was corrupting the larger values by using 16-bit integers to hold temporary values while doing the math. I changed the DCT code to use 32-bit integers for the calculations and that solved the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Column width in IE7 and Safari 5/OSX too narrow If you check out the site below in Safari 5/OSX or IE7/Win, the right bottom column starting with "Stay Updated" (#secondary) is super-narrow. In the CSS it's set to the same width as the "column" directly above it, #socialsidebar. Instead of being 31.6667% of the total width of the page I think it might be rendering as 31.6667% of #socialsidebar. http://216.172.167.18/~julia/books/ The width is correct in every other modern browser. Any ideas why this would be happening for Safari 5/OSX and IE7/Win and how to fix it? Thank you for your help! A: Using the IE developer toolbar and setting a width of 100% to #secondary seems to fix this. I would recommend setting up a seperate IE7 stylesheet the same way you setup custom classes on your <html> tag: <!--[if IE 7 ]> <link rel="stylesheet" type="text/css" media="all" href="ie7.css"> <![endif]--> or <!--[if IE 7 ]> <script type="text/css> enter code here </script> <![endif]--> As to why exactly it's happening, IE7 has some weird display quirks to it. I rarely dig deep enough to figure out what's exactly going on, as I prefer to spend as little time with it as possible. A possible resource: http://www.satzansatz.de/cssd/onhavinglayout.html A: I was missing a close-div for the #socialsidebar div. D'OH. Thanks to everyone else who got sucked into my web of stupidity and took the time to look at this. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7505631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does the Facebook 'share' button on Stack overflow work? I am looking to add social icons to our site, giving customers the ability to "like", tweet and share content on their facebook and twitter profiles. I have noticed to the left of this box, the facebook and twitter icons do exactly what I am trying to accomplish but I am not familiar with how to do this. Looking at the source code, there are JS references to: <script type="text/javascript"> StackExchange.ready(function() { var shareUrl = "http%3a%2f%2fstackoverflow.com%2fq%2f7505636%2f337690"; var shareMsg = "Advice+integrating+Facebook+%27share%27+and+link%2fimage+capabilities+with+our+site"; StackExchange.share.facebook($("#fb-share-7505636"), shareUrl, shareMsg); StackExchange.share.twitter($("#twitter-share-7505636"), shareUrl, shareMsg); }); </script> Our site works this way: While anybody can visit the primary site at any time, individuals can sign up as representatives with their own unique URL that acts as a referrer to give 'credit' on rewards. I have reviewed the facebook developer site and to be honest I am slightly overwhelmed. I want to give our members the ability to click a Facebook icon from within their dashboard, prompting them to post on their wall with a set image, set title, and description. I have read in the documentation this is done by setting meta tags in the head but it does not seem to matter for my site (or I am clearly doing it wrong). What if the URL facebook is looking for (share URL) is behind a password protected page or an area of the site which would not allow content based on a missing PHP SESSION variable? Edit I have also seen a lot on the net which says I have to integrate the Facebook JS SDK but then goes on to talk about authentication/permission to write on walls, etc. Yes the link to the left does not ask for permission to do anything other than to 1) log into the FB account, 2) post on the user's wall. This site is a perfect example The link above is great but it assumes I need to authorize a 'share' which does not occur on this site. A: When you click on the share button, you call a script on facebook.com that will then in turn access the page pointed to in the querystring (?u=xxxxxx). Facebook will parse that page and grab the first few images it finds, a description and title from the page. That is what it shows to you and allows you to add some additional text (as well as edit the title/description/and choose different images). If that page contains the specific meta tags that facebook asks you to add to the page, then they'll use those to populate the title/description/image. This allows the webpage author to control how their page shows up in a facebook feed (although the user could still edit it before posting). These meta tags would need to be in that particular page to be used by facebook. If facebook cannot access the page because it's password protected, etc. - then it cannot parse the meta tags and will then just show the user the URL as the title with no description and thumbnail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Proper way to implement a dropdownbox in WP7 ? I have seen 2 ways. * *Fake a ASP.NET stlye and have the options appear over a textbox on the same screen. *When the box is touched open a new screen that lets you scroll through all options and pick one. When one is selected that value is copied to the placeholder on the orginal screen. I am working on a project where we are doing #1 and I am thinking #2 is the proper way ? A: Use ListPicker from the silverlight toolkit if you're looking to match the WP7 paradigm (which you should want to :) ) Silverlight Toolkit A: These other stackoverflow questions may provide some insight (possible duplicate?): How to get dropdown like menu in wp7? Windows Phone Dropdown Don't forget to use the search function at the top right hand before asking a question!
{ "language": "en", "url": "https://stackoverflow.com/questions/7505640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Devise remember fails on deployment currently anytime we deploy our app we all get logged out of the app, and have to sign back in using devise + rails 3. Our deployment process is Load balancer points to an EC2 instance (prod) we push the new code to a new ec2 instance to test it out, and then switch the load balance to the new ec2 instance. Then we all get kicked out of the app, and have to sign back in. Any ideas why that is? Thanks A: Where do you store your session data? If you are storing that in the database, then check your deployment steps. Maybe you are cleaning up the sessions table in one of the deployment steps and that is logging everyone out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server convert datetime to int in query I have a field that contains time in seconds after midnight, however SQL Server will only display it as datetime yyyy-mm-dd hh.ss.xxx. I am trying to query this and convert the data to seconds after midnight, the way it should be, e.g. 01:00 would be 3600. I have tried SELECT CONVERT(int, timefield) but the result is a column named (No column name) and values are -1 or -2. What am I doing wrong here? Thanks for any help! A: Use the function DATEDIFF: SELECT DATEDIFF(SECOND, 0, '12:00:00') From http://www.eggheadcafe.com/software/aspnet/35057980/mssql-timetosec.aspx A: You want something like this SELECT [Total Seconds] = (DATEPART(hh, GETDATE()) * 3600) + (DATEPART(mi, GETDATE()) * 60) + DATEPART(ss, GETDATE()) Hope my answer help you to solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hiding mutators, clarification needed Suppose you have a class Dog, that has public class Dog { private String name; private double age; // some setters // some getters Additionally, you have a class DogHandler, that makes an instance of the Dog d and passes it to Owner I suppose, i can ... make a copy of a Dog before passing it to Owner, but that's an expensive operation and i'd rather avoid it. ... come up with an interface that Dog implements which contains getters only, cast Dog to that interface and pass the result along ... initialize settable variables in a constructor and simply not allow changes for this instance of an object Are there any other ways to make sure receiver of the object cant modify it? How do you take a simple bean containing some data and make it read-only? A: This can be achieved in few ways, I can propose you 2 of them: a) interface with getters is good idea b) create derived class from Dog which has setters method blocked, like this: class UnmodifiedDog extends Dog { public UnmodifiedDog(double age, String name) { super.setAge(age); super.setName(name); } @Override public void setAge(double age) { throw new UnsupportedOperationException(); } @Override public void setName(String name) { throw new UnsupportedOperationException(); } } In DogHandler: Dog createDog() { return new UnmodifiedDog(10, "Fido"); } and you can pass this to the Owner: owner.receiveDog(dogHandler.createDog()); A: The approaches you mention in the question are pretty much the standard steps to take to make Dog immutable. The only other tip would be to mandate that Dog cannot be overridden by declaring the class to be final. A: Among the solutions mentioned here, you can also take advantage of visibility modifiers. If Dog and Owner are in separate packages, you can set the visibility of the mutators to default (package) scope or protected scope. This will allow you to keep Dog and DogHandler in the same package (and therefore allow them both to mutate the Dog object accordingly), while keeping Owner objects separate (and therefore preventing them from making any modification to the Dog objects). A: Here is an example using an interface and package access setters. package blah.animal; public interface Dog { double getAge(); String getName(); } package blah.animal; public class DogImpl implements Dog { private double age; // double seems wrong for age. private String name; ... getters (defined by Dog interface) // package access setters. void setAge(double newValue) { age = newValue; } void setName(String newValue) { name = newValue; } package blah.animal; public class DogHandler { public static Dog newDog(double age, String name) { Dog returnValue = new DogImpl(); returnValue.setAge(age); returnValue.setName(name); return returnValue; } } package.blah.somethingelse; public class Blam { private Dog myDog; public Blam() { myDog = DogHandler.newDog(1.4D, "Tippy"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Exchange Web Services (EWS) - Exchange 2010 soap calls via suds Im trying to send an email via Exchange Web Services using suds 0.4.1: import suds from suds.client import Client from suds.transport.https import WindowsHttpAuthenticated url = "file:///C:/Services.wsdl" user = 'domain\\user' password = "hardtoguess" ntlm = WindowsHttpAuthenticated(username=user,password=password) c = Client(url, transport=ntlm) xml = ''' <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <CreateItem MessageDisposition="SendAndSaveCopy" xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"> <SavedItemFolderId> <DistinguishedFolderId Id="sentitems" xmlns="http://schemas.microsoft.com/exchange/services/2006/types"/> </SavedItemFolderId> <Items> <Message xmlns="http://schemas.microsoft.com/exchange/services/2006/types"> <ItemClass>IPM.Note</ItemClass> <Subject>Sent via Python->Exchange->EWS</Subject> <Body BodyType="Text">This message has been sent to you via Python, Exchange and EWS :)</Body> <ToRecipients> <Mailbox> <EmailAddress>imran.azad@localhost</EmailAddress> </Mailbox> </ToRecipients> </Message> </Items> </CreateItem> </soap:Body></soap:Envelope>''' attr = c.service.CreateItem(__inject={'msg':xml}) xml = ''' <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <soap:Body> <ResolveNames xmlns="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" ReturnFullContactData="true"> <UnresolvedEntry>azadi</UnresolvedEntry> </ResolveNames> </soap:Body> </soap:Envelope> ''' attr = c.service.ResolveNames(__inject={'msg':t}) print attr I'm able to authenticate fine, however I keep getting the following error: Traceback (most recent call last): File "soap.py", line 10, in <module> c = Client(url, transport=ntlm) File "build\bdist.win32\egg\suds\client.py", line 112, in __init__ File "build\bdist.win32\egg\suds\reader.py", line 152, in open File "build\bdist.win32\egg\suds\wsdl.py", line 159, in __init__ File "build\bdist.win32\egg\suds\wsdl.py", line 220, in build_schema File "build\bdist.win32\egg\suds\xsd\schema.py", line 93, in load File "build\bdist.win32\egg\suds\xsd\schema.py", line 305, in open_imports File "build\bdist.win32\egg\suds\xsd\sxbasic.py", line 542, in open File "build\bdist.win32\egg\suds\xsd\sxbasic.py", line 563, in download File "build\bdist.win32\egg\suds\xsd\schema.py", line 397, in instance File "build\bdist.win32\egg\suds\xsd\schema.py", line 226, in __init__ File "build\bdist.win32\egg\suds\xsd\schema.py", line 305, in open_imports File "build\bdist.win32\egg\suds\xsd\sxbasic.py", line 542, in open File "build\bdist.win32\egg\suds\xsd\sxbasic.py", line 563, in download File "build\bdist.win32\egg\suds\xsd\schema.py", line 397, in instance File "build\bdist.win32\egg\suds\xsd\schema.py", line 226, in __init__ File "build\bdist.win32\egg\suds\xsd\schema.py", line 305, in open_imports File "build\bdist.win32\egg\suds\xsd\sxbasic.py", line 542, in open File "build\bdist.win32\egg\suds\xsd\sxbasic.py", line 560, in download File "build\bdist.win32\egg\suds\reader.py", line 79, in open File "build\bdist.win32\egg\suds\reader.py", line 95, in download File "build\bdist.win32\egg\suds\transport\https.py", line 60, in open File "build\bdist.win32\egg\suds\transport\http.py", line 62, in open File "build\bdist.win32\egg\suds\transport\http.py", line 118, in u2open File "C:\Python26\lib\urllib2.py", line 391, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 409, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 369, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1170, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1143, in do_open r = h.getresponse() File "C:\Python26\lib\httplib.py", line 990, in getresponse response.begin() File "C:\Python26\lib\httplib.py", line 391, in begin version, status, reason = self._read_status() File "C:\Python26\lib\httplib.py", line 355, in _read_status raise BadStatusLine(line) httplib.BadStatusLine Any advice would be much appreciated. Thanks A: I've also been experiencing this issue. However, I only get this error intermittently. I found another post referring to a possible solution, and it helps some (I get the error less) but it hasn't fixed the issue completely. The problem seems to be that the Exchange server closes the connection before sending a valid response. If anyone else can add more I would greatly appreciate it. This one has been driving me crazy. Perhaps this may help you: urllib2 is throwing an error for an url , while it's opening properly in browser I'm not sure if you're doing it already, but I needed to setup my script to download the messages.xsd, types.xsd, and the services.wsdl locally and patch it. with the following: def setup(self): '''Patches the WSDL file to include a service tag. Returns path to local WSDL file.''' trans = self.transport try: makedirs(self.localdir) except OSError: # Directory already exists pass # Download messags.xsd file messages_url = '%s/messages.xsd' % self.urlprefix with open('%s/%s' % (self.localdir, 'messages.xsd'), 'w') as msg_xsd: msg_xsd.write(trans.geturl(messages_url, trans.authtype)) # Download types.xsd file types_url = '%s/types.xsd' % self.urlprefix with open('%s/%s' % (self.localdir, 'types.xsd'), 'w') as types_xsd: types_xsd.write(trans.geturl(types_url, trans.authtype)) # Modify WSDL to add service description service_url = '%s/Exchange.asmx' % self.urlprefix servicexml = ''' <wsdl:service name="ExchangeServices"> <wsdl:port name="ExchangeServicePort" binding="tns:ExchangeServiceBinding"> <soap:address location="%s"/> </wsdl:port> </wsdl:service> </wsdl:definitions>''' % service_url localwsdl = '%s/%s' % (self.localdir, 'Services.wsdl') wsdlxml = trans.geturl(self.wsdl, trans.authtype) with open(localwsdl, 'w') as wsdl: wsdl.write(wsdlxml.replace('</wsdl:definitions>', servicexml)) return localwsdl Hopefully this will point you in the right direction. Simply talking to Exchange with suds has been a major challenge. I found some help here, as well as the sample code that has provided the base for my project: http://lists.fedoraproject.org/pipermail/suds/2010-September/001144.html Update: Sending the correct SOAP headers with RequestServerVersion: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope> <soap:Header> <t:RequestServerVersion Version="Exchange2010"/> </soap:Header> <soap:Body> </soap:Body> </soap:Envelope> I've truncated the xml for brevity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Shorter way to get an iterator for a std::vector Lets say that I have got a vector like this. std::vector<a_complicated_whatever_identifier *> *something = new std::vector<a_complicated_whatever_identifier *>; // by the way, is this the right way to do this? Now I want to get an iterator for this... so I would do this like this. std::vector<a_complicated_whatever_identifier *>::iterator iter; But I find it a little too much for my code. I wonder, is there any more, brief way to ask for an iterator regardless of the type? I was thinking in something like. something::iterator iter; // OK, don’t laugh at me, I am still beginning with C++ Well, it obviously fail, but I guess you get the idea. How to accomplish this or something similar? A: Use a typedef. typedef std::vector<complicated *>::iterator complicated_iter Then set them like this: complicated_iter begin, end; A: In C++11 you'll be able to use auto. auto iter = my_container.begin(); In the meantime just use a typedef for the vector: typedef std::vector<a_complicated_whatever_identifier *> my_vector; my_vector::iterator iter = my_container.begin(); A: You would typically give your containers sensible typedefs, and then it's a breeze: typedef std::pair<int, Employee> EmployeeTag; typedef std::map<Foo, EmployeeTag> SignInRecords; for (SignInRecords::const_iterator it = clock_ins.begin(); ... ) ^^^^^^^^^^^^^^^^^ Usually, having a handy typedef for the container is more practical and self-documenting that an explicit typedef for the iterator (imagine if you're changing the container). With the new C++ (11), you can say auto it = clock_ins.cbegin() to get a const-iterator. A: You should rarely have much need/use for defining an iterator directly. In particular, iterating through a collection should normally be done by a generic algorithm. If there's one already defined that can do the job, it's best to use it. If there's not, it's best to write your own algorithm as an algorithm. In this case, the iterator type becomes a template parameter with whatever name you prefer (usually something referring at least loosely to the iterator category): template <class InputIterator> void my_algorithm(InputIterator start, InputIterator stop) { for (InputIterator p = start; p != stop; ++p) do_something_with(*p); } Since they've been mentioned, I'll point out that IMO, typedef and C++11's new auto are (at least IMO) rarely a good answer to this situation. Yes, they can eliminate (or at least reduce) the verbosity in defining an object of the iterator type -- but in this case, it's basically just treating the symptom, not the disease. As an aside, I'd also note that: * *A vector of pointers is usually a mistake. *Dynamically allocating a vector is even more likely a mistake. At least right off, it looks rather as if you're probably accustomed to something like Java, where you always have to use new to create an object. In C++, this is relatively unusual -- most of the time, you want to just define a local object so creation and destruction will be handled automatically. A: // by the way, is this the right way to do this? What you are doing is correct. The best approach depends on how you want to use that vector. But I find it a little too much for my code. I wonder, is there any more, brief way to ask for an iterator regardless of the type? Yes, you can define the vector as a type: typedef std::vector<a_complicated_whatever_identifier *> MyVector; MyVector * vectPtr = new MyVector; MyVector::iterator iter; A: If you have a recent compiler, I suggest giving c++11 a spin. Most compilers support it in the form of the --std=c++0x flag. You can do all kinds of nifty things related to type inference: std::list<std::map<std::string, some_complex_type> > tables; for (auto& table: tables) { std::cout << table.size() << std::endl; } for (auto it = tables.begin(); it!= tables.end(); ++it) { std::cout << it->size() << std::endl; } Also look at decltype and many other handyness: // full copy is easy auto clone = tables; // but you wanted same type, no data? decltype(tables) empty; Contrived example of combining typedefs with the above: typedef decltype(tables) stables_t; typedef stables_t::value_type::const_iterator ci_t;
{ "language": "en", "url": "https://stackoverflow.com/questions/7505654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ComboBox selected item text disappears when scrolling listbox I have Combo boxes inside a list box and whenever the list box is scrolled and the combo box is scrolled off of the screen the list box is firing a selection change event on the combo box and setting the selected index of the combo box to null. If I scroll back and forth multiple times you will see the selected item display and be removed by scrolling the list back and forth. Does anyone have an idea on ow to fix this? I need the combo box to retain the selected index. I have even changed the collection that holds the Combo-box data to a list from an observable collection and it still does the same thing. I am using silver light v4, .net 4 Thanks... A: This is probably a result of the default virtualising nature of the ListBox. As items scroll off the displayed the items are actually removed from the Visual Tree. If you don't have too many items in the list set the ItemsPanel property of the ListBox to an ItemsPanelTemplate containing a simple StackPanel. Better would be to cease using the selection change event in this scenario, use a binding on the SelectedItem property instead. A: I had the same issue, but with a datagrid. I tried this (preferable solution), but it didnt work for me. Silverlight ComboBox and SelectedItem So i had to go with this.... http://forums.silverlight.net/post/396922.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7505657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it good practice (or a good idea) to leave out HREF on links that are hooked up via JavaScript? Expanding on this question, For items that trigger dialogs and menus (i.e. non navigational), is it good practice to leave out the HREF attribute in links that have events that are hooked up via JavaScript? In these cases, does it makes sense to have HREF there at all? From this: <a href="javascript://">some text</a> Or even worse, this: <a href="#">some text</a> (which forces you to use event.preventDefault()) to this: <a>some text</a> A: ==Edited a little more== Bad, bad idea. It wont show up as a link for one thing. If you need a button, but are use an <a> as one, just using a <button> or <input type="button">. As you said, "non-navigational". The entire point of <a> is navigational. Out of those two tho, use href="#" putting javascript:// in a link is worse than adding inline styles. A: Pragmatically - this is what I have learned over 16 years of JS * *have the href, if not you need to set the cursor to hand or pointer *make the href go to a "sorry you need javascript" page if you do not want to use # or as I learned recently #somethingNotExisting *NEVER have href="javascript:anything()" *return false or preventDefault in the onclick which is preferably set in an onload handler UPDATE: For menus and such, the agreed markup are lists with css and using links in such menus is recommended if the links actually loads content to gracefully degrade to plain html navigation if script is off A: You should use the command element instead. The command element represents a command that the user can invoke. HTML5: Edition for Web Authors This has the benefit of being semantically correct. There's at least one fork of html5shiv which 'enables' support for the element in older browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to create git remote branch for svn repository I am using GIT on top of one centralized SVN repository. The SVN repository only contains trunk, no tags and branches. What I did before is using git svn to clone the remote repository to my local git workspace, I am the only developer works on it so everything works well. Now, few more developers come in and we should work on this svn repository, what I want to create remote git branches for the subversion trunk, so that all developers can work together on these git branches. I do not want to create subversion branches because they are too heavy. But after doing some search, it seems like git svn does not support this feature, or am I missed something? I've been also thinking that make my git local branch remote to share with other developers, but not sure if this works either. A: I found a great description on how to achieve that here: part 1 part2 I takes some steps to set this up, but then it works successfully. You can freely exchange commits between the git repositories, and also sync each one of them with the SVN repository (in both directions). A: The problem lies in the differences between how git and svn retain their histories. Subversion assumes that all developer coordination occurs via the central repository, while git assumes that each repository will be assembling changesets independently. You and your teammates will be able to exchange branches over git, but when it comes time to sync the final result, you're going to run into problems. That's why git-svn doesn't explicitly support this feature. I note from your comments that you don't want your developers working with SVN directly for collaboration... I'm sure you have your reasons for this, but realize that runs counter to git-svn's design. git-svn is best thought of as a Subversion client, rather than a bridge between a git repository network and a central SVN repository. You might want to consider allowing your team to create shared work branches in Subversion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java Generics: How does Java determine whether it's a set or get process for a bounded wildcard Ok guys. This is a revision class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null. A: If I understood your question properly, I guess it's because Integer is both super- and subtype to itself. A: Yes, you are confusing three things: * *java method names are just names, you can call them anything you want *there is a convention in Java to use what are called getters and setters. If you have a field (data or next in your example), then you define two methods: . public void setData(E data) { this.data = data; } public E getData() { return this.data; } This convention is called Java Beans. You'd do the same for node by the way. 3) Java selects the method to call based upon the types of the parameters that you pass to the method. This is called method overloading. It means that you can define things like: public void setFile(String name) { // do something here } public void setFile(File file) { // do something here } so you can call: setFile(new File("barbar")); or setFile("c:\stuff"); and the correct method will be chosen. The generic types that you have just confuse the situation even more :-) A: Java doesn't care about get/set in the method name; it's all based on method parameter types. Consider interface G<T> T f1(); void f2(T t); void f3(); Substitute T with different types, methods signatures are changed too; for example, G<Int> methods Int f1(); void f2(Int t); void f3(); So we can do the following G<Int> o = ...; Int i = o.f1(); o.f2(i); o.f3(); What happens with wildcards? Actually compiler can't directly reason about wildcards; they must be replaced with fixed albeit unknown types; this process is called "wildcard capture". For example, given a G<? super Int> type, compiler internally treats it as G<W>, where W is an unknown supertype of Int. G<W> has methods W f1(); void f2(W t); void f3(); So we can do G<? super Int> o = ...; Object i = o.f1(); // f1() returns W, which is subtype of Object o.f2( new Int(42) ); // f2() accepts W; Int is a subtype of W, accepted. o.f3(); Similarly G<? extends Int> o = ...; // G<W>, where W is a subtype of Int Int i = o.f1(); // f1() returns W, which is subtype of Int o.f2( new Int(42) ); // error: f2() accepts W; Int is NOT a subtype of W o.f3(); A: I think i have the answer to this problem. It's true that method name doesn't play a role here but rather whether the reference assignment is valid. Compiler error for clause 10 & 11 is due to the following in terms of parameter assignment. ? extends Integer = Integer One cannot assign the Integer to ? extends Integer since the ? extends Integer could have type which is lower than Integer (figuratively speaking). Of course this works for clause 12. A: The question really changed now... The answer to this is PECS (or here, page 28) Also see, What is PECS (Producer Extends Consumer Super)? or How can I add to List<? extends Number> data structures?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQL Date range query not working correctly I have a problem getting certain data from my database by querying a date range. In my database i have a DATE type field within the format YYYY-MM-DD. I want to get all data within a date range of today + 2 weeks (Expiring). I have wrote: $format = 'Y-m-j'; $date = date ( $format ); $new = date ( $format, strtotime ( '+14 day' . $date ) ); $start = date("Y-m-d", strtotime($new)); $today = date('Y-m-d'); $q = "SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'"; while($row = mysql_fetch_assoc($q)){ $listing_id = $row['listing_id']; echo "$listing_id"; } So what I want to achieve is for the query to pull all the rows from now until 5th October. I've echo'd the variables and they show they're in the correct form (YYYY-MM-DD) to compare within the database but no results are returning. Any help would be greatly appreciated. Many thanks in return. A: If dd_end is a date you may want to read a certain section on the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE. A: Well, assuming that the mysql database has the same date that your server, you could let the mysql database do all the date calculations. A little something like this: SELECT * FROM listing WHERE dd_end BETWEEN CURDATE() AND (CURDATE() + INTERVAL 14 DAY) On the other hand, i think Paul S's answer may fix your problem. Edit: You forgot to call mysql_query before the mysql_fetch_assoc() function. $result = mysql_query($q); while ($row = mysql_fetch_assoc($result)) { $listing_id = $row['listing_id']; echo "$listing_id"; } A: Read: http://php.net/manual/en/function.strtotime.php strtotime has a second argument. $format = 'Y-m-j'; $date = date ( $format ); $new = date ( $format, strtotime ( '+14 day' . $date ) ); $start = date("Y-m-d", strtotime($new)); Should be: $new = strtotime('+14 day', time()); $start = date("Y-m-d", $new); $today = date('Y-m-d'); $q = mysql_query("SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'"); while($row = mysql_fetch_assoc($q)){ $listing_id = $row['listing_id']; echo "$listing_id"; } A: May this is the right way ? $start = date("Y-m-d", strtotime('+14 day' . $date));
{ "language": "en", "url": "https://stackoverflow.com/questions/7505664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: autohotkey: sometimes button is not clicked I wrote such autohotkey script to auto-logon my program: SendMode Input ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. Run info.exe WinWait, User identification, Sleep 300 ControlSend, Edit1, user, User identification ControlSend, Edit2, password, User identification ControlClick, Button1, User identification The problem is - sometimes Button1 is not clicked. When i'm execution script in most cases Button1 is clicked, but sometimes it doesn't. When script autoexecuted on locked workstation (this is the scenario I actually need), Button1 is never clicked. I've tried to insert Sleep, 1000 after each line in script but it didn't helped. The question is why, and how to fix/workaround the problem I will try today to replace ControlSend, Edit2, password, User identification ControlClick, Button1, User identification with ControlSend, Edit2, password{Enter}, User identification probably this will work... A: I spent a week tring to solve my problem anf finally resolved it. Hope this will help to someone. Never try to send CAPITALIZED letter to autohotkey, instead send shiftdown and shiftup Wrong: ControlSend, Edit2, passworD, User identification Right: ControlSend, Edit2, passwor{SHIFTDOWN}d{SHIFTUP}, User identification Also it would be better to avoid ControlClick if possible. To click a button ControlSend a Space to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I sum up properties of a JSON object in coffescript? I have an object that looks like this one: object = title : 'an object' properties : attribute1 : random_number: 2 attribute_values: a: 10 b: 'irrelevant' attribute2 : random_number: 4 attribute_values: a: 15 b: 'irrelevant' some_random_stuff: 'random stuff' I want to extract the sum of the 'a' values on attribute1 and attribute2. What would be the best way to do this in Coffeescript? (I have already found one way to do it but that just looks like Java-translated-to-coffee and I was hoping for a more elegant solution.) A: Here is what I came up with (edited to be more generic based on comment): sum_attributes = (x) => sum = 0 for name, value of object.properties sum += value.attribute_values[x] sum alert sum_attributes('a') # 25 alert sum_attributes('b') # 0irrelevantirrelevant So, that does what you want... but it probably doesn't do exactly what you want with strings. You might want to pass in the accumulator seed, like sum_attributes 0, 'a' and sum_attributes '', 'b' A: Brian's answer is good. But if you wanted to bring in a functional programming library like Underscore.js, you could write a more succinct version: sum = (arr) -> _.reduce arr, ((memo, num) -> memo + num), 0 sum _.pluck(object.properties, 'a') A: total = (attr.attribute_values.a for key, attr of obj.properties).reduce (a,b) -> a+b or sum = (arr) -> arr.reduce((a, b) -> a+b) total = sum (attr.attribute_values.a for k, attr of obj.properties)
{ "language": "en", "url": "https://stackoverflow.com/questions/7505670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Updatepanel works as expected in asp.net dev server (vstudio2010) and refreshes whole page on IIS7/2008 I've got a rudimentary example from MSoft of an updatepanel. When I do a Ctrl+F5 to test locally on my VSTUDIO 2010 box I scroll down and hit the "Refresh Panel" button listed below and it updates without having to scroll back down. When I "publish" the site to my Server2008/IIS7 box I scroll down, hit the button, and have to scroll down the page again to see that the updatepanel has actually refreshed, but so has the whole page. I just updated the .net framework on the server today to the latest release and the site has an asp.net 4.0 application pool running in Integrated Pipeline Mode. Help? Is this a problem with dll references, web.config, bin folder? <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <fieldset> <legend>UpdatePanel content</legend> <!-- Other content in the panel. --> <%=DateTime.Now.ToString() %> <br /> <asp:Button ID="Button1" Text="Refresh Panel" runat="server" /> </fieldset> </ContentTemplate> </asp:UpdatePanel> A: Moved the script to an IIS7.5/Server 2008(R2) box and it worked fine. Not sure what I would have had to install on the 2008 box to make it work, but even updating the .NET framework to 4.0 didn't do the trick. Shrug.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to get only the top 50 friends from the friendslist using Graph API Can someone advice if there is a possibility of geting just the top 50 friends from Facebook using Graph API. I currently get all the friends from Facebook, which kind of slows down the requests and take a while for it process. Could someone advice on this. A: Use the limit and offset querystring parameters like this: me/friends?limit=50&offset=0 Test it here on the Facebook graph explorer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make PHP send an email with an inline image attachment WITHOUT using PHPMailer, Swiftmailer, PEAR, Zend_mail, or any other libraries at all, I want to send an email with an image attachment inline. The important part here is attaching it inline: I already am able to do everything else. Inline meaning that it is able to be used by the HTML in the email in an image tag. I really don't want to use PHPMailer or anything like that--I am not the only one who has tried to figure out how to do this on stackoverflow, and so far all the questions I've seen get nothing but arguments about why they should be using PEAR or Zend_mail or something. I don't want to do that, and I don't want to argue about it. A: is this what you are looking for?? <?php //define the receiver of the email $to = 'youraddress@example.com'; //define the subject of the email $subject = 'Test email with attachment'; //create a boundary string. It must be unique //so we use the MD5 algorithm to generate a random hash $random_hash = md5(date('r', time())); //define the headers we want passed. Note that they are separated with \r\n $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; //add boundary string and mime type specification $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; //read the atachment file contents into a string, //encode it with MIME base64, //and split it into smaller chunks $attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); //define the body of the message. ob_start(); //Turn on output buffering ?> --PHP-mixed-<?php echo $random_hash; ?> Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hello World!!! This is simple text email message. --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: 7bit <h2>Hello World!</h2> <p>This is something with <b>HTML</b> formatting.</p> --PHP-alt-<?php echo $random_hash; ?>-- --PHP-mixed-<?php echo $random_hash; ?> Content-Type: application/zip; name="attachment.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment <?php echo $attachment; ?> --PHP-mixed-<?php echo $random_hash; ?>-- <?php //copy current buffer contents into $message variable and delete current output buffer $message = ob_get_clean(); //send the email $mail_sent = @mail( $to, $subject, $message, $headers ); //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" echo $mail_sent ? "Mail sent" : "Mail failed"; ?> A: I don't know if this is what you want, but is easy to send an email with mail() function in PHP, in HTML format: http://php.net/manual/en/function.mail.php In the examples, there's one with HTML
{ "language": "en", "url": "https://stackoverflow.com/questions/7505673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows COM action invoke on UPNP I'm working with COM UPnP. I'm trying to send SetAVTransportURI action to urn:upnp-org:serviceId:AVTransport. SetAVTransportURI requires 3 params: * *InstanceID: 0 *CurrentURI: http://192.168.0.8/test/1.mp3 *CurrentURIMetaData: empty string after invoking action I'm receiving Failed to invoke action... here is my code: HRESULT ExtractServices(IUPnPDevice * pDevice) { BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:serviceId:AVTransport"); if(NULL == bstrServiceName) { return E_OUTOFMEMORY; } IUPnPServices * pServices = NULL; HRESULT hr = pDevice->get_Services(&pServices); if(SUCCEEDED(hr)) { IUPnPService * pAppService = NULL; hr = pServices->get_Item(bstrServiceName, &pAppService); if(SUCCEEDED(hr)) { printf("got AVTransport\r\n"); VARIANT vInArg; VARIANT vRetVal; VARIANT vOutVal; VariantInit(&vInArg); VariantInit(&vRetVal); VariantInit(&vOutVal); SAFEARRAYBOUND bounds[1]; bounds[0].lLbound = 0; bounds[0].cElements = 3; SAFEARRAY* saInArgs = SafeArrayCreate(VT_VARIANT,3,bounds); LONG lArg; lArg = 0; SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"0")); lArg = 1; SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"http://192.168.0.8/test/1.mp3")); lArg = 2; SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"NOT_IMPLEMENTED")); vInArg.pparray = &saInArgs; vInArg.vt = VT_VARIANT | VT_ARRAY | VT_BYREF; //VARIANT varInArgs; //VariantInit(&varInArgs); //varInArgs.vt = VT_VARIANT | VT_ARRAY; //V_ARRAY(&varInArgs) = saInArgs; hr = pAppService->InvokeAction(SysAllocString(L"SetAVTransportURI"),vInArg,&vRetVal,&vOutVal); if(SUCCEEDED(hr)) { printf("InvokeAction success"); } else if(hr == UPNP_E_ACTION_REQUEST_FAILED) { printf("The device had an internal error; the request could not be executed."); } else if(hr == UPNP_E_DEVICE_ERROR) { printf("An unknown error occurred."); } else if(hr == UPNP_E_DEVICE_TIMEOUT) { printf("The device has not responded within the 30 second time-out period."); } else if(hr == UPNP_E_ERROR_PROCESSING_RESPONSE) { printf("The device has sent a response that cannot be processed; for example, the response was corrupted\n"); } else if(hr == UPNP_E_INVALID_ACTION) { printf("The action is not supported by the device\n"); } else if(hr == UPNP_E_INVALID_ARGUMENTS) { printf("One or more of the arguments passed in vInActionArgs is invalid\n"); } else if(hr == UPNP_E_PROTOCOL_ERROR) { printf("An error occurred at the UPnP control-protocol level\n"); } else if(hr == UPNP_E_TRANSPORT_ERROR) { printf("An HTTP error occurred. Use the IUPnPService::LastTransportStatus property to obtain the actual HTTP status code\n"); } else { printf("Failed to invoke action...\n"); } pAppService->Release(); } pServices->Release(); } SysFreeString(bstrServiceName); return hr; } I think the problem is with passing params in VARIANT section, can anyone give me a hand with that? I have changed my code: HRESULT ExtractServices(IUPnPDevice * pDevice) { BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:serviceId:AVTransport"); if(NULL == bstrServiceName) { return E_OUTOFMEMORY; } IUPnPServices * pServices = NULL; HRESULT hr = pDevice->get_Services(&pServices); if(SUCCEEDED(hr)) { IUPnPService * pAppService = NULL; hr = pServices->get_Item(bstrServiceName, &pAppService); if(SUCCEEDED(hr)) { printf("got AVTransport\r\n"); VARIANT vInArg; VARIANT vRetVal; VARIANT vOutVal; VariantInit(&vInArg); VariantInit(&vRetVal); VariantInit(&vOutVal); SAFEARRAYBOUND bounds[1]; bounds[0].lLbound = 0; bounds[0].cElements = 2; SAFEARRAY* saInArgs = SafeArrayCreate(VT_VARIANT,1,bounds); VARIANT vParam; LONG lParam[1]; VariantInit(&vParam); vParam.vt = VT_BSTR; V_BSTR(&vParam) = SysAllocString(L"http://192.168.0.8/test/1.mp3"); lParam[0] = 0; SafeArrayPutElement(saInArgs,lParam,&vParam); VariantClear(&vParam); VariantInit(&vParam); vParam.vt = VT_BSTR; V_BSTR(&vParam) = SysAllocString(L""); lParam[0] = 1; SafeArrayPutElement(saInArgs,lParam,&vParam); VariantClear(&vParam); vInArg.vt = VT_ARRAY | VT_VARIANT; V_ARRAY(&vInArg) = saInArgs; //VARIANT varInArgs; //VariantInit(&varInArgs); //varInArgs.vt = VT_VARIANT | VT_ARRAY | VT_BSTR; //V_ARRAY(&varInArgs) = saInArgs; hr = pAppService->InvokeAction(SysAllocString(L"SetAVTransportURI"),vInArg,&vRetVal,&vOutVal); if(SUCCEEDED(hr)) { printf("InvokeAction success"); } else if(hr == UPNP_E_ACTION_REQUEST_FAILED) { printf("The device had an internal error; the request could not be executed."); } else if(hr == UPNP_E_DEVICE_ERROR) { printf("An unknown error occurred."); } else if(hr == UPNP_E_DEVICE_TIMEOUT) { printf("The device has not responded within the 30 second time-out period."); } else if(hr == UPNP_E_ERROR_PROCESSING_RESPONSE) { printf("The device has sent a response that cannot be processed; for example, the response was corrupted\n"); } else if(hr == UPNP_E_INVALID_ACTION) { printf("The action is not supported by the device\n"); } else if(hr == UPNP_E_INVALID_ARGUMENTS) { printf("One or more of the arguments passed in vInActionArgs is invalid\n"); } else if(hr == UPNP_E_PROTOCOL_ERROR) { printf("An error occurred at the UPnP control-protocol level\n"); } else if(hr == UPNP_E_TRANSPORT_ERROR) { printf("An HTTP error occurred. Use the IUPnPService::LastTransportStatus property to obtain the actual HTTP status code\n"); } else { printf("Failed to invoke action... %d\n",hr); } pAppService->Release(); } pServices->Release(); } SysFreeString(bstrServiceName); return hr; } and I still have problem with the args: One or more of the arguments passed in vInActionArgs is invalid...
{ "language": "en", "url": "https://stackoverflow.com/questions/7505675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Arel subselects with ActiveRecord? I'm using a slightly-modified version of the geocoded gem which returns this query when I call near on my model (calling Deal.near(southwest), where southwest is an array of geo coordinates): SELECT deals.*, 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) AS distance, CAST(DEGREES(ATAN2( RADIANS(addresses.lng - -122.42336332798004), RADIANS(addresses.lat - 37.772476604436974))) + 360 AS decimal) % 360 AS bearing FROM "deals" INNER JOIN "companies" ON "companies"."id" = "deals"."company_id" INNER JOIN "addresses" ON "addresses"."addressable_id" = "companies"."id" AND "addresses"."addressable_type" = 'Company' WHERE ( addresses.lat BETWEEN 37.483013038215276 AND 38.06194017065867 AND addresses.lng BETWEEN -122.78956461309022 AND -122.05716204286986 ) GROUP BY deals.id, deals.created_at, deals.updated_at, deals.active, deals.company_id, deals.title, deals.limitations, deals.redemption_count, addresses.lat, addresses.lng HAVING 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) <= 20 ORDER BY 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) ASC My issue is that this will return multiple Deal records if that Deal's company has multiple Addresses, which I don't want. In MySQL, I could just omit address.lat, address.lng in the GROUP_BY clause and it will properly group the records, but I can't do this in PostgreSQL. I know I could wrap the whole query above in another SELECT and GROUP_BY, like this: SELECT id, created_at, updated_at, active, title, punches_to_complete, company_id, description, lat, lng, MIN(distance), bearing FROM ( ... ) AS t GROUP BY company_id ... where the ellipsis is the query from above. That (I believe) should get me the desired result in both MySQL and PostgreSQL. The only problem is that I have no idea how to write this in ARel! I had tried the following, a la this tip from the ARel guru, but I couldn't really make it work quite right (calling to_sql as the OP had said fixed his issue escapes the quotes, which freaks PostgreSQL out). Can anyone help me with this??? UPDATE: I've managed to get this done with an additional scope, like so: scope :nearest, lambda { |coords| subquery = "(#{Deal.near(coords).to_sql}) AS t1" columns = Deal.columns.map{ |c| c.name }.join(',') Deal.select(columns) .select('MIN(distance) AS distance') .from(subquery) .group(columns) .order('distance ASC') } However, this totally breaks chainability, as now I cannot call something like current_user.deals.nearest(coords), since that tags on an additional WHERE deals.user_id = 1 to the query outside of the subselect. I tried compensating for this by moving this logic into a class method and blanking the wheres clause on the SelectManager manually, like this: def self.nearest(coords) subquery = "(#{Deal.near(coords).to_sql}) AS t1" columns = Deal.columns.map{ |c| c.name }.join(',') query = Deal.select(columns) .select('MIN(distance) AS distance') .from(subquery) .group(columns) .order('distance ASC') query.arel.ast.cores[0].wheres = [] query end ... but that doesn't seem to work either: the additional WHERE clause is still appended: Failure/Error: @user.deals.nearest(southwest).first.distance.to_f.round(2).should == ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'deals.user_id' in 'where clause': SELECT id,created_at,updated_at,user_id,company_id, MIN(distance) AS distance FROM (SELECT deals.*, 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) AS distance, CAST(DEGREES(ATAN2( RADIANS(addresses.lng - -122.42336332798004), RADIANS(addresses.lat - 37.772476604436974))) + 360 AS decimal) % 360 AS bearing FROM deals INNER JOIN companies ON companies.id = deals.company_id INNER JOIN addresses ON addresses.addressable_id = companies.id AND addresses.addressable_type = 'Company' WHERE deals.user_id = 26 AND (addresses.lat BETWEEN 37.483013038215276 AND 38.06194017065867 AND addresses.lng BETWEEN -122.78956461309022 AND -122.05716204286986) GROUP BY deals.id,deals.created_at,deals.updated_at,deals.user_id,deals.company_id, addresses.lat, addresses.lng HAVING 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) <= 20 ORDER BY 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) ASC) AS t1 WHERE deals.user_id = 26 GROUP BY id,created_at,updated_at,user_id,company_id ORDER BY distance ASC LIMIT 1 Is what I'm trying to do even possible with ARel? The additional scopes above feel really dirty to me (parsing the subquery to raw SQL? I thought ARel was supposed to make it so I never did that!) Related question: Can ARel formulate cross-db queries for CTEs (Common Table Expressions)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to resize DevExpress controls I have a DevExpress LayoutControl set inside a WinForms Form. I would like the LayoutControl to resize horizontally when the form is resized, or at least make the LayoutControl resizable by the user. I have seen on DevExpress's page suggestions to change the SizeConstraintsType property to "default". I have also tried to anchor the control to the right and left of its parent. I have worked on increasing the MaxSize, also. Does anyone know how to do this? I just basically want to do the equivalent to (in HTML) <table width=100%>. Does anyone know how to do this? Thanks in advance! A: The Developer's Express LayoutControl is a very nice tool, but has a couple gotchas. The LayoutControl itself should resize just fine docked inside any container control like a form, a user control or a panel control. In many cases the layout control is one of the first things you put on your form/control because everything else goes inside it to be "layedout". So you should set the "Dock" property of the layout control to "Fill" or to the desired edge of the form/control you want it to dock to. The "gotcha" here is that layout control's internal logic may limit its external dimensions or any internal item if it is capable of doing so and the layout items want to be a particular size. This is actually simpler than it sounds. For example lets say you have a label control inside your layout control. A label control by default will size itself to fit the width of its text. In turn the layout control will try to accommodate the label's desired size by shrinking/growing the size of the layout item. So this one label control could be messing with your layout controls resizing. I chose label as the example because it is the most common control to mess up your layout design. The way I fix this is to change the label's "AutoSizeMode" property to "vertical" (if you want text wrapping) or "none" (if you want to force it be the size the layout control wants it to be). This free up the layout control to make the width decisions. Also if you are allowing the layout control to be resized by the end user (say with DevExpress' SplitterControl) the layout will again try to become its optimal size and not allow the SplitterControl to move away from this optimal size if the other controls are more easily resized (like a grid, tree, list, etc...). In this case adding an "EmptySpaceItem" to the layout control will allow it to fill any empty space when being resized. To add an EmptySpaceItem to your layout, right click the layout control in the Visual Studio designer and select "Customize Layout". The customize dialog will have a list of items you can drag onto the layout control including the EmptySpaceItem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to show the overflow:hidden content using jQuery / JS when a user clicks on an image? I am building a feed reader and on my first page I show a lot of post previews. A user has the option to click on the title and visit the source link. In addition I would like to give them the option to click on a small icon, like a plus sign + to view the rest of the post preview in my page. As you can see on http://jsfiddle.net/BLUzJ/ I have set a max-height and overflow:hidden if the content of post preview is more than this. 95% of the post previews have a lot of text hidden. For now the max-height is set to 10.3em as below #text { max-height:10.3em; overflow:hidden; } When an icon in the post (I guess there will be in a corner of the post preview) is clicked, the max-height changes to allow user to read the rest. My application is written in PHP, and I get the title, image, content from RSS feeds. I think that this is a jQuery, JavaScript solution but I do not know how to do it. Thank you for your ideas and examples. A: Using jquery, since you added that tag: http://jsfiddle.net/r4F8Q/3/ * *added an element with class .toggle, which could be your icon *added css rule for #text.expanded which removed max-height *jquery adds/removes class expanded from element #text A: To show all of the content of the post, you can set the max-height of the element whose icon has been clicked to auto. Once you get a hold of the element that you wish to expand (either by using document.getElementById("id") or by traversing the DOM), you can set this property by doing the following: x.style.maxHeight = "none"; You can set this as the onclick event for the expand icon, if you wish. Do note that this will not animate the expansion; for that you should probably use something like jQuery. EDIT: Updated the jsFiddle with a simple example, which expands when the title is clicked. http://jsfiddle.net/BLUzJ/6/ A: Here is a starting fiddle. It expands on clicking the text. You would obviously have to do some more work to have a trigger that expands/collapses the section. http://jsfiddle.net/BLUzJ/10/
{ "language": "en", "url": "https://stackoverflow.com/questions/7505687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: checked/unchecked checkboxes I am trying to pass a value for when a checkbox is either in a checked state or if it's not checked. However, it doesn't appear to pass the non-checked state. the code I am using is below: if (document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').checked == true){ document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').value = 'on'; } else { document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').value = 'off'; } I have added an alert: alert(document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').value); which surprisingly shows the 'off' value - however - this isn't passed successfully. What am I missing? A: This is normal, expected and well-defined behaviour. * *Checkboxes have an arbitrary value; *When a checkbox's checked attribute is on, it is submitted as part of a form with that value; *When a checkbox's checked attribute is off, it is not submitted at all. HTML 4.01 says: Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful. And: When the user submits a form (e.g., by activating a submit button), the user agent processes it as follows. * *Step one: Identify the successful controls *Step two: Build a form data set A form data set is a sequence of control-name/current-value pairs constructed from successful controls. [..] HTML5 says similar things. You could write your back-end code to expect fields with a certain name, and react accordingly when they are missing. A: You can handle the true on/off values of a checkbox this way (will post when checkbox is on and off). Basically this uses a hidden form field with the name PRODUCT_REVIEW_EMAILS_FIELD and populates it with the value. Hidden form fields always post. <form> <input id="tempCheckbox" type="checkbox" name="Temp_PRODUCT_REVIEW_EMAILS_FIELD"> <input id="checkboxvalue" type="hidden" name="PRODUCT_REVIEW_EMAILS_FIELD" value="Off"> </form> <script type="text/javascript"> document.getElementById("tempCheckbox").onclick = function () { if (this.checked) { document.getElementById("checkboxvalue").value = "On"; } else { document.getElementById("checkboxvalue").value = "Off"; } } // used to run on page load to verify the correct value is set incase your server side // script defaults the checkbox to on document.getElementById("tempCheckbox").onclick(); </script> A: You can do it on the server side so not to relay on JavaScript. To do it you must add a reference input field right before every checkbox. <form> <input type="hidden" name="checkboxes" value="reference"/> <input type="checkbox" name="checkboxes" value="checked"/> </form> This will make parameters come in array of values: "reference-checked" sequence if checkbox is checked and just "reference" if it is unchecked. You can have arbitrary amount of such checkboxes, this will not affect your logic. Now for the server side. Assuming that you get your 'checkboxes' as a String array, here's the logic (in Java) to parse the values: List<Boolean> parsed = new ArrayList<Boolean>(); for (int i = 0; i < checkboxes.length; i++) { if (i < checkboxes.length - 1 && "checked".equals(checkboxes[i + 1])) { parsed.add(true); i++; else { parsed.add(false); } } Now you have a nice array of booleans that correlates to the order, amount and state of checkboxes you have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GET ajax request I'm sending GET request (which returns JSON). The code looks like: $.ajax({ url: "http://www.new.marketprice.ru/retrieveRegions.html", dataType: "jsonp", data: { searchStr: request.term }, error: function() { console.log('epic fail'); }, success: function( data ) { console.log(data); } }); It returns (into console); Resource interpreted as Other but transferred with MIME type undefined. epic fail But in Network tab I see GET request with returned data: [ { "region":"Московская область","countryId":1, "cityId":23,"regionId":12345,"city":"Москва","country":"Россия"}, {"region":"Ленинградская область","countryId":1,"cityId":453, "regionId":54321,"city":"Санкт Петербург","country":"Россия"} ] Why does error callback is called? UPD Okay, I set json and now no warning but error: XMLHttpRequest cannot load http://www.new.marketprice.ru/retrieveRegions.html?searchStr=test. Origin http://new.marketprice.ru is not allowed by Access-Control-Allow-Origin It's so strange because running script is located at same domain :( A: It is only a json response not JSONP. Generally for JSONP the request will have callback method and response will be wrapped in that function name A: Your headers don't specify the correct mime-type (application/json-p) and jQuery(?) is confused because it's not sure if it should process it as json or not. See if you can get your server to respond with the correct type. The appropriate header is called Content-Type. EDIT: whoops, and the OP is right, its not even JSON-P. Try changing what jquery is expecing to just 'json' first. A: i was also in problem like this just try by using one more argument callback=? or json=jsonp
{ "language": "en", "url": "https://stackoverflow.com/questions/7505695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving to CoreData - Add to Top All, Is it possible to save to the top of the CoreData? If so, how? For example, every time something is added to the data store, I want it to be inserted at the top. This way, when the results are fetched they would come back sorted by most recent first without having to save the NSDate and fetch with a predicate. Here is a crude example: Most recent Earlier Yesterday Last Week Thanks, James A: What is the "top"? Core Data does not assign any particular order to the objects it stores. If you want to impose some order on the objects, add an attribute to the entity that you want to be ordered and then sort on that attribute when you fetch the objects. So, you could add a serialNumber attribute that always increases. Sorting on that serial number would order the objects. A: Add a creationDate in the model, and the following code to your custom implementation of the object: - (void)awakeFromInsert { [self setPrimitiveCreationDate:[NSDate date]]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to disable UIViewController interaction and show activity indicator while loading data from web service or core data? Question says it all. Is there a best recipe to follow to disable user interaction and show a activity indicator while fetching data from a web service or loading data from a core data fetch operation? I'm using ASIHTTPRequest, JSONKit and Core Data in my particular app so any sample code using those Apis would be preferred. Thanks - wg A: Create a UIView with transparent background and that takes the whole screen. It will intercept the interaction and won't let the user tap on the other items on the screen. Then you can add an UIActivityIndicator (and even a UILabel) as a subview of this transparent fullscreen view or whatever you need. Note that there are multiple existing projects like SVProgressHUD that do that already too and that I strongly recommand. A: A very very simple and easy way to accomplish both tasks is using MBProgressHUD. Check it's repository in Github Example usage: + (MBProgressHUD *)showHUDAddedTo:(UIView *)view animated:(BOOL)animated; + (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated; These two class methods will show/hide a simple activity indicator with a translucid background. It also has properties to show text, progress and a good delegate. A: Use the up mentioned HUD control on rootViewContoller. It will not let user to interact with UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .less css files in .NET and Visual Studio * *Is the recommended way of handling .less files to use pre-compiled static files or use some sort runtime conversion using for example a HttpHandler? What are the pros and cons of the different ways of doing it? *What's the recommended techniques of solving the above suggested approach? Tools, libraries etc? A: Because you are on .NET, I recommend you check out the DotLess project. It's open source and very active. They have an HTTP Handler that plugs into IIS, it grabs any request for a .less file and returns a valid CSS file. I don't know what amount of caching they use, but you can probably rely on the browser to cache a good amount of it.. The DotLess project also has an executable that will compile when you want (like during a project build), or on demand prgrammatically. The pros and cons for which way you do it really depends on your project. I think the best workflow may be to use LESS.js for development because you don't need external dependencies besides the javascript file, and all the changes are live right away. Then as the project is promoted through various testing and production environments, you can install the web server filter or precompile it. Again, it depends on how you want to solve it for your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Case when exists then select I have requirement to select the field from the table in case statement like instead of some static value. WHEN EXISTS(SELECT c.customer_name FROM Sales.Customer AS c WHERE c.PersonID = @BusinessEntityID) THEN c.customer_name How can this be achieved or is this possible . I have taken the following from msdn site. Need to tweak to fulfill my requirement. USE AdventureWorks2008R2; GO CREATE FUNCTION dbo.GetContactInformation(@BusinessEntityID int) RETURNS @retContactInformation TABLE ( BusinessEntityID int NOT NULL, FirstName nvarchar(50) NULL, LastName nvarchar(50) NULL, ContactType nvarchar(50) NULL, PRIMARY KEY CLUSTERED (BusinessEntityID ASC) ) AS -- Returns the first name, last name and contact type for the specified contact. BEGIN DECLARE @FirstName nvarchar(50), @LastName nvarchar(50), @ContactType nvarchar(50); -- Get common contact information SELECT @BusinessEntityID = BusinessEntityID, @FirstName = FirstName, @LastName = LastName FROM Person.Person WHERE BusinessEntityID = @BusinessEntityID; SET @ContactType = CASE -- Check for employee WHEN EXISTS(SELECT * FROM HumanResources.Employee AS e WHERE e.BusinessEntityID = @BusinessEntityID) THEN 'Employee' -- Check for vendor WHEN EXISTS(SELECT * FROM Person.BusinessEntityContact AS bec WHERE bec.BusinessEntityID = @BusinessEntityID) THEN 'Vendor' -- Check for store WHEN EXISTS(SELECT * FROM Purchasing.Vendor AS v WHERE v.BusinessEntityID = @BusinessEntityID) THEN 'Store Contact' -- Check for individual consumer WHEN EXISTS(SELECT * FROM Sales.Customer AS c WHERE c.PersonID = @BusinessEntityID) THEN 'Consumer' END; -- Return the information to the caller IF @BusinessEntityID IS NOT NULL BEGIN INSERT @retContactInformation SELECT @BusinessEntityID, @FirstName, @LastName, @ContactType; END; RETURN; END; GO A: No idea what the rest of your code looks like, but typically this would be: SELECT name = COALESCE(c.customer_name, o.other_entity_name) FROM dbo.MainEntity AS m LEFT OUTER JOIN dbo.Customers AS c ON m.something = c.something LEFT OUTER JOIN dbo.OtherTable AS o ON m.something = o.something; But other than a general idea, you haven't given quite enough information to supply a complete answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Need help decreasing width of table I'm trying to decrease the width of this table because it's way too wide. I added this: style="width: 70%; to the table tag but it does not seem to work. <table align="center" class="data_table vert_scroll_table" style="width: 70%;">   <ctl:vertScroll height="300" headerStyleClass="data_table_scroll" bodyStyleClass="data_table_scroll" enabled="${user.scrollTables}"> <ctl:sortableTblHdrSetup topTotal="false" href="process.like_item_search"/> <table align="center" class="data_table vert_scroll_table" style="width: 70%;"> <tr> <ctl:sortableTblHdr title="MWSLIN" property="mwslin" type="top">MWSLIN</ctl:sortableTblHdr> <ctl:sortableTblHdr title="SOR" property="sorCode" type="top">SOR</ctl:sortableTblHdr> <ctl:sortableTblHdr title="Fiscal Year" property="fiscalYear" type="top">Fiscal<br/>Year</ctl:sortableTblHdr> <ctl:sortableTblHdr title="Workload Year" property="workloadYear" type="top">Workload<br/>Year</ctl:sortableTblHdr> <ctl:sortableTblHdr title="SAC" property="sac" type="top">SAC</ctl:sortableTblHdr> <ctl:sortableTblHdr title="TAMCN" property="tamcn" type="top">TAMCN</ctl:sortableTblHdr> <ctl:sortableTblHdr title="NSN" property="nsn" type="top">NSN</ctl:sortableTblHdr> <ctl:sortableTblHdr title="WORKTYPE" property="workTypeId" type="top">Work Type</ctl:sortableTblHdr> <ctl:sortableTblHdr title="NOMENCLATURE" property="nom" type="top">Nomenclature</ctl:sortableTblHdr> <ctl:sortableTblHdr title="SUP" property="sup" type="top">Sup</ctl:sortableTblHdr> <th class="narrow">Actions</th> </tr> <c:forEach var="bean" items="${likeItems}"> <tr> <td class="center">${bean.mwslin}</td> <td class="center">${bean.sorCode.shortName}</td> <td class="center">${bean.fiscalYear}</td> <td class="center">${bean.workloadYear}</td> <td class="center">${bean.sac}&nbsp;</td> <td class="center">${bean.tamcn}&nbsp;</td> <td class="center"><ctl:stringFormat format="@@@@-@@-@@@-@@@@">${bean.nsn}</ctl:stringFormat>&nbsp;</td> <td class="center">${bean.workTypeId.description}&nbsp;</td> <td class="center">${bean.nom}&nbsp;</td> <td class="center"><fmt:formatNumber type="currency" value="${bean.sup}"/>&nbsp;</td> <td> <a class="view" href="blah"><img class="edit" src="../images/icon_view.gif" border="0" alt="View"/></a> </td> </tr> </c:forEach> </table> </ctl:vertScroll> </c:when> <c:otherwise> <c:set var="no_results_msg" scope="page" value="There are no results that match your search criteria." /> <%@ include file="../../include/search-no-results.html" %> </c:otherwise> </c:choose> <%@ include file="../../include/footer.html" %> A: Using a pixel value attribute in table columns should force the text to wrap (if there's at least one space in it). Use style="width: 100px" and set the amount to whatever you need. Alternatively, set this attribute to the column's class name in CSS if you're able to. A: The issue you most likely have is that the <td>s, somewhere (in a CSS file, or in the document), have a fixed width. If that's the case, changing the <table> width won't do anything unless you have some other special styles on it. For a responsive table width, I'd suggest adding a percentage-based width to both the <table> and the <td> elements. You would do this in your CSS file. A: I suspect it's just expanding to fit its contents. As a fix, you might set a fixed width for columns such as "Work Type" that could get too wide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Fine Zoom instructions (JQuery) I am currently trying to use the "Fine Zoom" jquery tool for handling pan and zoom on a website. Here is the link to their instructions: http://codecanyon.net/item/fine-zoom/full_screen_preview/407907. I followed their instructions, but for whatever reason I am receiving indicating that "fancybox" is not a function. This is my call to fancybox: $("a#lnkPan").fancybox({ onComplete:function(){ $('#imgPan').finezoom(); } }); I added their js libraries as well. Has anyone been able to make "Fine Zoom" work? A: Fire up fiddler and take a look at the http traffic. My guess is your reference to the js file is 404'ing or erroring for some reason. A: I am the creator of finezoom. To use finezoom you just need to apply it to a image tag. In the web site I just only view an example how fine zoom can be used with fancybox that is another jQuery plugin. To use fine zoom just follow this steps: * *Load jQuery.js, finezoom.js and optionally jQueryMousewheel.js javascript files *Prepare your image tag, give it and ID or CLASS *Prepare your image tag *Then call finezoom on the image class or id: $('.class').finezoom(); That's all, after this you can zoom in, out, drag, pan an image. If you need more instructions just contact me or visit again the documentation page, I just updated it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are ASP.NET Application Cache and Application State storage affected by Session storage? If I modify an ASP.NET website's configuration to store session data in a SQL State Database, my understanding is that this will not affect the storage of the Application Cache or the Application State, which are always stored in local server volatile memory. Am I right? A: Correct. Session, Application State, and Cache are completely separate entities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Config MongoDB Servers Following the Oreily Scaling MongoDB book, I saw the following command: Let’s say we have three data centers: one in New York, one in San Francisco, and one on the moon. We start up one config server in each center. $ ssh ny-01 ny-01$ mongod $ ssh sf-01 sf-01$ mongod $ ssh moon-01 moon-01$ mongod $ ssh ny-02 ny-01$ mongos --configdb ny-01,sf-01,moon-01 Press Enter, and now all the config servers know about each other. The mongos is like the host of the party that introduces them all to each other. Question: Does ny-01, sf-01, and moon-01 mean the machine name or machine IP address? A: In the book example, hostname. I believe you can use either, but use IPs in order to avoid having to resolve them, and to be sure that any failure is not due to hostname resolution issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pre .NET 4 memory cache I want to use the new MemoryCache class but I am not yet using .NET 4. I do have a simple cache class (internally uses a dictionary). What would be a good approach in using this class like the MemoryCache? Does anyone know how MemoryCache is managed throughout the lifetime of an application (non asp.net)? A: Maybe you can use a tool like Structuremap for that? It's not really meant to do these things (it's a DI container) but it will work out well if you specify some items as a singleton, some items on a request basis etc. It just depends on how granular you want the lifetime management to be. A: Enterprise Library had a Caching block that was similar to what .Net 4 has now on the core framework. It was there for Version 5, but I think it has been removed from version 6. Getting an older version of the enterprise library will provide you with a caching mechanism.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android app force closes i have this android code .I have my layout for button defined in the xml file .i want to set the text for button here by getting it by id .but the app force closes.whats wrong ? package com.action ; import android.app.Activity; import android.os.Bundle; import android.widget.Button; public class ActionActivity extends Activity { @Override public void onCreate(Bundle i){ super.onCreate(i); Button button=(Button) findViewById(R.id.but); button.setText("Hey!!"); setContentView(R.layout.main); } } Thnx... A: You have to use setContentView(R.layout.main); before using findViewById(). If you don't do that, findViewById() will return null (since no view with that ID is in the current layout) and you will get a NullPointerException when trying to set the text on the TextView. The correct version of onCreate() should look like this: public void onCreate(Bundle i) { super.onCreate(i); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.but); button.setText("Hey!!"); } A: Put setContentView(R.layout.main) before creating the instance of Button. Like This: setContentView(R.layout.main); Button button=(Button) findViewById(R.id.but); button.setText("Hey!!"); A: you must put setContentView(R.Layout.main) before setting findViewById(R.id.but).Because it generates nullpointer Exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex non capturing groups in javascript I'm a bit rusty on my regex and javascript. I have the following string var: var subject = "javascript:loadNewsItemWithIndex(5, null);"; I want to extract 5 using a regex. This is my regex: /(?:loadNewsItemWithIndex\()[0-9]+/) Applied like so: subject.match(/(?:loadNewsItemWithIndex\()[0-9]+/) The result is: loadNewsItemWithIndex(5 What is cleanest, most readable way to extract 5 as a one-liner? Is it possible to do this by excluding loadNewsItemWithIndex( from the match rather than matching 5 as a sub group? A: The return value from String.match is an array of matches, so you can put parentheses around the number part and just retrieve that particular match index (where the first match is the entire matched result, and subsequent entries are for each capture group): var subject = "javascript:loadNewsItemWithIndex(5, null);"; var result = subject.match(/loadNewsItemWithIndex\(([0-9]+)/); // ^ ^ added parens document.writeln(result[1]); // ^ retrieve second match (1 in 0-based indexing) Sample code: http://jsfiddle.net/LT62w/ Edit: Thanks @Alan for the correction on how non-capturing matches work. Actually, it's working perfectly. Text that's matched inside a non-capturing group is still consumed, the same as text that's matched outside of any group. A capturing group is like a non-capturing group with extra functionality: in addition to grouping, it allows you to extract whatever it matches independently of the overall match. A: I believe the following regex should work for you: loadNewsItemWithIndex\(([0-9]+).*$ var test = new RegExp(/loadNewsItemWithIndex\(([0-9]+).*$/); test.exec('var subject = "javascript:loadNewsItemWithIndex(5, null);";'); The break down of this is loadNewsItemWithIndex = exactly that \( = open parentheses ([0-9]+) = Capture the number .* = Anything after that number $ = end of the line A: This should suffice: <script> var subject = "javascript:loadNewsItemWithIndex(5, null);"; number = subject.match(/[0-9]+/); alert(number); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7505762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: sendLine Won't Send integers (Twisted Python) I'm writing a MUD in Python using the Twisted library. I'm currently trying to send a integer through the sendLine method via to the LineReceiver module. However, whenever I try sending a integer I get the below error message while running my program: Unhandled Error Traceback (most recent call last): File "C:\Python27\lib\site-packages\twisted\python\log.py", line 84, in thLogger return callWithContext({"system": lp}, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\log.py", line 69, in thContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118 allWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, llWithContext return func(*args,**kw) --- <exception caught here> --- File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", 46, in _doReadOrWrite why = getattr(selectable, method)() File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 460, ead rval = self.protocol.dataReceived(data) File "C:\Python27\lib\site-packages\twisted\protocols\basic.py", line 56 dataReceived why = self.lineReceived(line) File "server.py", line 37, in lineReceived self.sendLine(level) File "C:\Python27\lib\site-packages\twisted\protocols\basic.py", line 62 sendLine return self.transport.write(line + self.delimiter) exceptions.TypeError: unsupported operand type(s) for +: 'int' and 'str' The line which is causing the error is: self.sendLine(SomeVarWhichIsANumber) A: so... send a string: self.sendLine(str(SomeVarWhichIsANumber))
{ "language": "en", "url": "https://stackoverflow.com/questions/7505767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: IE7 Bug - the main-box moves to the left on hover I'm trying to fix this issue in IE7 that when you hover on it it won't remain in its position but will go to the left side. I've tried display:inline but it won't work in this case. You can test it here: http://www.sneakyrascal.com/kayak/results.html This is the code I am using for the main-box(the middle one): .results #container{ float:left; width: 527px; margin:38px 0 0 20px; padding-left:1px; position: relative; border: #ccc 1px solid; background: #fff; } Thanks in advance A: The problem is caused by position:relative on #main-content. If you remove it the container will not jump any more: #main-content { margin-top: 20px; position: relative; /* delete this */ } Also you might have noticed that your .sites div was not lining up properly. Adding left: 0 will fix that: .results #container UL LI.box .left-side .sites{ width: 90px; text-align: center; position: absolute; bottom: 10px; left: 0; /* add this */ } A: Huhh, weird bug, you can fix it by properly containing your #main-content id. Just add this to it: display:inline-block;
{ "language": "en", "url": "https://stackoverflow.com/questions/7505772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python-Remove rows based on lack of character I would like to remove a row from my file if it contains a letter other than A, C, G, or T. So that ['TC', 'CY', 'GS', 'GA', 'CT'] will become ['TC', 'GA', 'CT']. The files will have an unknown number of rows and will contain patterns of 2 or more letters in any order. In addition, I do not know the other letters that are present (Y or S or something else). How would I go about setting up a program for this preferably in Python? I already can import my file and read the rows. Thanks! A: How about this, as a one liner: valid = [l.strip() for l in fh if all(c in 'ACGT' for c in l.strip())] where fh is your file handle. A: You can solve it with a simple regular expression and a list comprehension. >>> import re >>> data = ['TC', 'CY', 'GS', 'GA', 'CT'] >>> [x for x in data if re.match(r'^[ACGT]+$', x)] ['TC', 'GA', 'CT'] A: A little slow one-liner because of type casting(you can decrease it by assigning set("ACGT") before), but a small one: >>> l ['TC', 'CY', 'GS', 'GA', 'CT'] >>> [i for i in l if not set(i) - set("ACGT")] ['TC', 'GA', 'CT']
{ "language": "en", "url": "https://stackoverflow.com/questions/7505775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: user#create render = 'new' does not work generates no template errors Note: I am running Rails 3.1.0 In Lesson #8: Sign up In the tutorial at time index ~25:53 - I am following the instructions to render the new page when the create action is called. the 'create' action for users_controller is a follows: def create @user = User.new @title = "signup" render = "new" end When trying to render - I still get the "Missing Template" error displayed in the tutorial even after following the screencast. It suggests that I still require a template -> views/users/create Any ideas? is this related to Rails 3.1.0? A: Replace: render = "new" With: render "new" It's a method requiring an argument. A: You have to use: render :new render is a method. render :new is basically the same as render(:new). When you do render = "new" you just assign the string "new" to a new local variable render.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I check for NSFileHandle has data available? I'm working with NSTask, configured with 3 NSPipe, and want to read from standardOutput and standardError. I do it inside while - 1st for stdout, next for stderr. I can't use readInBackgroundAndNotify and waitForDataInBackgroundAndNotify, since my code is already running in separate thread, and I don't want run NSRunLoop there and detach new background threads... But reading both - stdout and stderr cause some hang on availableData when no data present in one of these channels. So I use this code: @implementation NSFileHandle (isReadableAddon) - (BOOL)isReadable { int fd = [self fileDescriptor]; fd_set fdset; struct timeval tmout = { 0, 0 }; // return immediately FD_ZERO(&fdset); FD_SET(fd, &fdset); if (select(fd + 1, &fdset, NULL, NULL, &tmout) <= 0) return NO; return FD_ISSET(fd, &fdset); } @end However, when isReadable returns YES and I call [fileHandle availableData], my thread still blocks. Why? I expected call availableData method without blocking when isReadable returned YES. A: Swift 4 version (for macOS): extension FileHandle { var isReadable: Bool { var fdset = fd_set() FileDescriptor.fdZero(&fdset) FileDescriptor.fdSet(fileDescriptor, set: &fdset) var tmout = timeval() let status = select(fileDescriptor + 1, &fdset, nil, nil, &tmout) return status > 0 } } /// References: /// - http://swiftrien.blogspot.com/2015/11/swift-code-library-replacements-for.html /// - https://github.com/kylef-archive/fd/blob/master/Sources/FDSet.swift public struct FileDescriptor { public static func fdZero(_ set: inout fd_set) { set.fds_bits = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) } public static func fdSet(_ fd: Int32, set: inout fd_set) { let intOffset = Int32(fd / 32) let bitOffset = fd % 32 let mask = Int32(1) << bitOffset switch intOffset { case 0: set.fds_bits.0 = set.fds_bits.0 | mask case 1: set.fds_bits.1 = set.fds_bits.1 | mask case 2: set.fds_bits.2 = set.fds_bits.2 | mask case 3: set.fds_bits.3 = set.fds_bits.3 | mask case 4: set.fds_bits.4 = set.fds_bits.4 | mask case 5: set.fds_bits.5 = set.fds_bits.5 | mask case 6: set.fds_bits.6 = set.fds_bits.6 | mask case 7: set.fds_bits.7 = set.fds_bits.7 | mask case 8: set.fds_bits.8 = set.fds_bits.8 | mask case 9: set.fds_bits.9 = set.fds_bits.9 | mask case 10: set.fds_bits.10 = set.fds_bits.10 | mask case 11: set.fds_bits.11 = set.fds_bits.11 | mask case 12: set.fds_bits.12 = set.fds_bits.12 | mask case 13: set.fds_bits.13 = set.fds_bits.13 | mask case 14: set.fds_bits.14 = set.fds_bits.14 | mask case 15: set.fds_bits.15 = set.fds_bits.15 | mask case 16: set.fds_bits.16 = set.fds_bits.16 | mask case 17: set.fds_bits.17 = set.fds_bits.17 | mask case 18: set.fds_bits.18 = set.fds_bits.18 | mask case 19: set.fds_bits.19 = set.fds_bits.19 | mask case 20: set.fds_bits.20 = set.fds_bits.20 | mask case 21: set.fds_bits.21 = set.fds_bits.21 | mask case 22: set.fds_bits.22 = set.fds_bits.22 | mask case 23: set.fds_bits.23 = set.fds_bits.23 | mask case 24: set.fds_bits.24 = set.fds_bits.24 | mask case 25: set.fds_bits.25 = set.fds_bits.25 | mask case 26: set.fds_bits.26 = set.fds_bits.26 | mask case 27: set.fds_bits.27 = set.fds_bits.27 | mask case 28: set.fds_bits.28 = set.fds_bits.28 | mask case 29: set.fds_bits.29 = set.fds_bits.29 | mask case 30: set.fds_bits.30 = set.fds_bits.30 | mask case 31: set.fds_bits.31 = set.fds_bits.31 | mask default: break } } public static func fdClr(_ fd: Int32, set: inout fd_set) { let intOffset = Int32(fd / 32) let bitOffset = fd % 32 let mask = ~(Int32(1) << bitOffset) switch intOffset { case 0: set.fds_bits.0 = set.fds_bits.0 & mask case 1: set.fds_bits.1 = set.fds_bits.1 & mask case 2: set.fds_bits.2 = set.fds_bits.2 & mask case 3: set.fds_bits.3 = set.fds_bits.3 & mask case 4: set.fds_bits.4 = set.fds_bits.4 & mask case 5: set.fds_bits.5 = set.fds_bits.5 & mask case 6: set.fds_bits.6 = set.fds_bits.6 & mask case 7: set.fds_bits.7 = set.fds_bits.7 & mask case 8: set.fds_bits.8 = set.fds_bits.8 & mask case 9: set.fds_bits.9 = set.fds_bits.9 & mask case 10: set.fds_bits.10 = set.fds_bits.10 & mask case 11: set.fds_bits.11 = set.fds_bits.11 & mask case 12: set.fds_bits.12 = set.fds_bits.12 & mask case 13: set.fds_bits.13 = set.fds_bits.13 & mask case 14: set.fds_bits.14 = set.fds_bits.14 & mask case 15: set.fds_bits.15 = set.fds_bits.15 & mask case 16: set.fds_bits.16 = set.fds_bits.16 & mask case 17: set.fds_bits.17 = set.fds_bits.17 & mask case 18: set.fds_bits.18 = set.fds_bits.18 & mask case 19: set.fds_bits.19 = set.fds_bits.19 & mask case 20: set.fds_bits.20 = set.fds_bits.20 & mask case 21: set.fds_bits.21 = set.fds_bits.21 & mask case 22: set.fds_bits.22 = set.fds_bits.22 & mask case 23: set.fds_bits.23 = set.fds_bits.23 & mask case 24: set.fds_bits.24 = set.fds_bits.24 & mask case 25: set.fds_bits.25 = set.fds_bits.25 & mask case 26: set.fds_bits.26 = set.fds_bits.26 & mask case 27: set.fds_bits.27 = set.fds_bits.27 & mask case 28: set.fds_bits.28 = set.fds_bits.28 & mask case 29: set.fds_bits.29 = set.fds_bits.29 & mask case 30: set.fds_bits.30 = set.fds_bits.30 & mask case 31: set.fds_bits.31 = set.fds_bits.31 & mask default: break } } public static func fdIsSet(_ fd: Int32, set: inout fd_set) -> Bool { let intOffset = Int(fd / 32) let bitOffset = fd % 32 let mask = Int32(1) << bitOffset switch intOffset { case 0: return set.fds_bits.0 & mask != 0 case 1: return set.fds_bits.1 & mask != 0 case 2: return set.fds_bits.2 & mask != 0 case 3: return set.fds_bits.3 & mask != 0 case 4: return set.fds_bits.4 & mask != 0 case 5: return set.fds_bits.5 & mask != 0 case 6: return set.fds_bits.6 & mask != 0 case 7: return set.fds_bits.7 & mask != 0 case 8: return set.fds_bits.8 & mask != 0 case 9: return set.fds_bits.9 & mask != 0 case 10: return set.fds_bits.10 & mask != 0 case 11: return set.fds_bits.11 & mask != 0 case 12: return set.fds_bits.12 & mask != 0 case 13: return set.fds_bits.13 & mask != 0 case 14: return set.fds_bits.14 & mask != 0 case 15: return set.fds_bits.15 & mask != 0 case 16: return set.fds_bits.16 & mask != 0 case 17: return set.fds_bits.17 & mask != 0 case 18: return set.fds_bits.18 & mask != 0 case 19: return set.fds_bits.19 & mask != 0 case 20: return set.fds_bits.20 & mask != 0 case 21: return set.fds_bits.21 & mask != 0 case 22: return set.fds_bits.22 & mask != 0 case 23: return set.fds_bits.23 & mask != 0 case 24: return set.fds_bits.24 & mask != 0 case 25: return set.fds_bits.25 & mask != 0 case 26: return set.fds_bits.26 & mask != 0 case 27: return set.fds_bits.27 & mask != 0 case 28: return set.fds_bits.28 & mask != 0 case 29: return set.fds_bits.29 & mask != 0 case 30: return set.fds_bits.30 & mask != 0 case 31: return set.fds_bits.31 & mask != 0 default: return false } } } A: I also prefer using select but incase you want to work with a non-blocking read here's a gist that works for me. Swift 4 var flags = fcntl(fileDescriptor, F_GETFL) _ = fcntl(fileDescriptor, F_SETFL, flags | O_NONBLOCK) public var nonBlockingAvailableData: Data? { return self.__readDataOfLength(Int.max, untilEOF: false) } internal func __readDataOfLength(_ length: Int, untilEOF: Bool) -> Data? { let _closed: Bool = false let _fd = self.fileDescriptor var statbuf = stat() var dynamicBuffer: UnsafeMutableRawPointer? = nil var total = 0 if _closed || fstat(_fd, &statbuf) < 0 { fatalError("Unable to read file") } if statbuf.st_mode & S_IFMT != S_IFREG { /* We get here on sockets, character special files, FIFOs ... */ var currentAllocationSize: size_t = 1024 * 8 dynamicBuffer = malloc(currentAllocationSize) var remaining = length while remaining > 0 { let amountToRead = min(1024 * 8, remaining) // Make sure there is always at least amountToRead bytes available in the buffer. if (currentAllocationSize - total) < amountToRead { currentAllocationSize *= 2 dynamicBuffer = reallocf(dynamicBuffer!, currentAllocationSize) if dynamicBuffer == nil { fatalError("unable to allocate backing buffer") } } let amtRead = read(_fd, dynamicBuffer!.advanced(by: total), amountToRead) //Needs better errorhandling, check ERRNO? if amtRead == -1 { return nil } if 0 > amtRead { free(dynamicBuffer) fatalError("read failure") } if 0 == amtRead { break // EOF } total += amtRead remaining -= amtRead if total == length || untilEOF == false { break // We read everything the client asked for. } } } if length == Int.max && total > 0 { dynamicBuffer = reallocf(dynamicBuffer!, total) } if total == 0 { free(dynamicBuffer) } else if total > 0 { let bytePtr = dynamicBuffer!.bindMemory(to: UInt8.self, capacity: total) return Data(bytesNoCopy: bytePtr, count: total, deallocator: .free) } else { assertionFailure("The total number of read bytes must not be negative") free(dynamicBuffer) } return Data() } see the Linux select man page: Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Use jQuery to add scripts to the Head of a document I am looking for a way (using jQuery) that I can add other scripts into the head of a document. The reason I need to do this is because when building a "template" for a certain web design application I am only allowed to insert 1 js file into the head of the document. Some features that I would like to add to the design require more than 1 js file so I think I would like to have other js files added to the head of the document as the page loads. This would allow me to add the features to the design that I want. I have looked at jQuery's "getScript" call but am not sure if there is a better way to approach this. A: Forget about jQuery for this — Head JS sounds like it's exactly what you want. A: Try this: var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "http://somedomain.com/script.js"; $("head").append(script); A: Take a look at requireJS, it's got a lot more features and handles dependencies really well A: KulerGary, $(document).ready(function() { $('head').append("<script src='file.js' type='text/javascript'></script>"); }); I can't test but think its work. Cya.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: form action linking to wrong controller I have a a controller referral_medium_controller.php with the following content <?php class ReferralMediumsController extends AppController { var $name = 'ReferralMediums'; function admin_index() { //Checking that only super administrators can actually add new interest options if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) { $this->cakeError('error404'); } $this->pageTitle = __l('Referral Mediums'); $this->ReferralMediums->recursive = 0; $this->set('ReferralMediums', $this->paginate()); } function admin_view($id = null) { //Checking that only super administrators can actually add new interest options if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) { $this->cakeError('error404'); } $this->pageTitle = __l('Referral Mediums?'); if (is_null($id)) { $this->cakeError('error404'); } $referralMedium = $this->ReferralMediums->find('first', array( 'conditions' => array( 'ReferralMedium.id = ' => $id ) , 'fields' => array( 'ReferralMedium.id', 'ReferralMedium.created', 'ReferralMedium.modified', 'ReferralMedium.referral_medium', 'ReferralMedium.is_active', ) , 'recursive' => -1, )); if (empty($referralMedium)) { $this->cakeError('error404'); } $this->pageTitle.= ' - ' . $referralMedium['ReferralMedium']['id']; $this->set('ReferralMediums', $referralMedium); } function admin_add() { //Checking that only super administrators can actually add new interest options if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) { $this->cakeError('error404'); } $this->pageTitle = __l('Add Referral Medium'); if (!empty($this->data)) { $this->ReferralMedium->create(); if ($this->ReferralMedium->save($this->data)) { $this->Session->setFlash(__l('Referral Medium has been added') , 'default', null, 'success'); $this->redirect(array( 'action' => 'index' )); } else { $this->Session->setFlash(__l('Referral Medium could not be added. Please, try again.') , 'default', null, 'error'); } } } function admin_edit($id = null) { //Checking that only super administrators can actually add new interest options if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) { $this->cakeError('error404'); } $this->pageTitle = __l('Edit Referral Medium'); if (is_null($id)) { $this->cakeError('error404'); } if (!empty($this->data)) { if ($this->ReferralMedium->save($this->data)) { $this->Session->setFlash(__l('Referral Medium has been updated') , 'default', null, 'success'); $this->redirect(array( 'action' => 'index' )); } else { $this->Session->setFlash(__l('Referral Medium could not be updated. Please, try again.') , 'default', null, 'error'); } } else { $this->data = $this->ReferralMedium->read(null, $id); if (empty($this->data)) { $this->cakeError('error404'); } } $this->pageTitle.= ' - ' . $this->data['ReferralMedium']['id']; } function admin_delete($id = null) { //Checking that only super administrators can actually add new interest options if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) { $this->cakeError('error404'); } if (is_null($id)) { $this->cakeError('error404'); } if ($this->ReferralMedium->del($id)) { $this->Session->setFlash(__l('Referral Medium deleted') , 'default', null, 'success'); $this->redirect(array( 'action' => 'index' )); } else { $this->cakeError('error404'); } } } ?> a model referral_model.php with the following content <?php class ReferralMedium extends AppModel { var $name = 'ReferralMedium'; var $useTable="referral_mediums"; //$validate set in __construct for multi-language support //The Associations below have been created with all possible keys, those that are not needed can be removed var $hasOne = array( 'UserProfile' => array( 'className' => 'UserProfile', 'foreignKey' => 'referral_medium_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '' ) ); var $hasMany = array( 'UserProfile' => array( 'className' => 'UserProfile', 'foreignKey' => 'referral_medium_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'referral_medium' => array( 'rule' => 'notempty', 'allowEmpty' => false, 'message' => __l('Required') ) , ); } } ?> a add view referral_mediums/admin_add.ctp with the following code <?php /* SVN: $Id: $ */ ?> <div class="referralMedium form"> <?php echo $form->create('ReferralMedium', array('class' => 'normal'));?> <fieldset> <h2><?php echo __l('Add Referral Medium');?></h2> <?php echo $form->input('referral_medium'); echo $form->input('is_active'); ?> </fieldset> <div class="submit-block clearfix"> <?php echo $form->submit(__l('Add'));?> </div> <?php echo $form->end();?> </div> Now all works fine except if I click on the add button in the add form I get redirected to admin/referral_media/add instead of admin/referral_medium/add and I can't find the problem. I would be greatful I someone could help me with this. A: the plural of medium is media, not mediums. The controller name is plural, so it's referral_media. So you'll need to change your controller name (and the file name). A: Or change Config/bootstrap.php so it won't make controller names plural anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Powershell - Find the user who invoked the script I have a script(Let's call it myPSScript.ps1) which takes two parameters and performs predefined steps. Script is located in a Windows Server box which people login and execute the script. Supports two users to be logged in at the given time. I want to find out who invoked the script. (Get-WmiObject -Class Win32_Process | Where-Object {$_.ProcessName -eq 'explorer.exe'}).GetOwner() | Format-Table Domain, User This works when the user is logged in currently and trying to run the script. But what if I have a batch file in scheduled tasks and run the same script? In that case the same command returns a null exception, as there is no one logged into the machine. Is there a way to find out who/which process invoked the powershell script. I vaguely remember Start-Transcript records which user the command is run from etc, so this should be possible? Thanks! Sanjeev A: Interesting question. I wrote a script with three different ways to get the user like so: ([Environment]::UserDomainName + "\" + [Environment]::UserName) | out-file test.txt "$env:userdomain\$env:username" | out-file -append test.txt [Security.Principal.WindowsIdentity]::GetCurrent().Name | out-file -append test.txt notepad test.txt Saved it as test.ps1 and called it using runas as: runas /user:domain\user "powershell e:\test.ps1" And I got the domain\user all three times in the output. Used runas to just distinguish between the user I am logged in as (me!!) and the domain\user with which I was running it as. So it does give the user that is running the script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: What is wrong with this WebWorker (no errors, but console.log are not reached) I have the following code, trying to test out WebWorkers. I have an index.html file that looks like this: <html> <head></head> <body> <script type='text/javascript'> var worker = new Worker('./myworker.js'); console.log('after creation'); worker.addEventListener('message', function(msg){ console.log(msg); }); worker.postMessage(); </script> </body> </html> The contents of myworker.js (which resides in the same directory as index.html) is: this.onmessage = function(){ postMessage('got the msg, thanks'); }; When I load index.html (in Chrome 14), the 'after creation' console.log never happens. Nor anything else. Console.logs happen before the new Worker() creation, but nothing after seems to happen. A: Well butter my biscuit, apparently WebWorkers do not work when loaded locally (e.g. from file://). source: http://www.html5rocks.com/en/tutorials/workers/basics/ (bottom of content) A: If you are testing app in chrome you should start the chrome with --allow-file-access-from-files or test app using Local server
{ "language": "en", "url": "https://stackoverflow.com/questions/7505796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I store static content of a web page in a javascript variable? This is what I am trying to accomplish: Get the static content of an 'external' url and check it for certain keywords for example, "User Guide" or "page not found". I tried to use Ajax, dojo.xhr etc., but they don't support cross domain. In my case it is an external url. Also, I cannot use jQuery. I also looked at dojo.io.iframe but I couldn't find useful example to accomplish this. A dojo.io.iframe example would be really helpful. Please help. Thanks! A: Modern browsers restrict the use of cross-domain scripting. If you're the maintainer of the server, read Access-Control-Allow-Origin to get knowledge on how to enable cross-site scripting on your website. EDIT: To check whether an external site is down or not, you could use this method. That external site is required to have an image file. Most sites have a file called favicon.ico at their root directory. Example, testing whether http://www.google.com/ is online or not. var test = new Image(); //If you're sure that the element is not a JavaScript file //var test = document.createElement("script"); //If you're sure that the external website is reliable, you can use: //var test = document.createElement("iframe"); function rmtmp(){if(tmp.parentNode)tmp.parentNode.removeChild(tmp);} function online(){ //The website is likely to be up and running. rmtmp(); } function offline(){ //The file is not a valid image file, or the website is down. rmtmp(); alert("Something bad happened."); } if (window.addEventListener){ test.addEventListener("load", online, true); test.addEventListener("error", offline, true); } else if(window.attachEvent){ test.attachEvent("onload", online); test.attachEvent("onerror", offline); } else { test.onload = online; test.onerror = offline; } test.src = "http://www.google.com/favicon.ico?"+(new Date).getTime(); /* "+ (new Date).getTime()" is needed to ensure that every new attempt doesn't get a cached version of the image */ if(/^iframe|script$/i.test(test.tagName)){ test.style.display = "none"; document.body.appendChild(test); } This will only work with image resources. Read the comments to see how to use other sources. A: Try this: <script src="https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js.uncompressed.js" type="text/javascript" djConfig="parseOnLoad:true"></script> <script> dojo.require("dojo.io.script"); </script> <script> dojo.addOnLoad(function(){ dojo.io.script.get({ url: "http://badlink.google.com/", //url: "http://www.google.com/", load: function(response, ioArgs) { //if no (http) error, it means the link works alert("yes, the url works!") } }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7505803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP how to count xml elements in object returned by simplexml_load_file(), I have inherited some PHP code (but I've little PHP experience) and can't find how to count some elements in the object returned by simplexml_load_file() The code is something like this $xml = simplexml_load_file($feed); for ($x=0; $x<6; $x++) { $title = $xml->channel[0]->item[$x]->title[0]; echo "<li>" . $title . "</li>\n"; } It assumes there will be at least 6 <item> elements but sometimes there are fewer so I get warning messages in the output on my development system (though not on live). How do I extract a count of <item> elements in $xml->channel[0]? A: Here are several options, from my most to least favourite (of the ones provided). * *One option is to make use of the SimpleXMLIterator in conjunction with LimitIterator. $xml = simplexml_load_file($feed, 'SimpleXMLIterator'); $items = new LimitIterator($xml->channel->item, 0, 6); foreach ($items as $item) { echo "<li>{$item->title}</li>\n"; } *If that looks too scary, or not scary enough, then another is to throw XPath into the mix. $xml = simplexml_load_file($feed); $items = $xml->xpath('/rss/channel/item[position() <= 6]'); foreach ($items as $item) { echo "<li>{$item->title}</li>\n"; } *Finally, with little change to your existing code, there is also. $xml = simplexml_load_file($feed); for ($x=0; $x<6; $x++) { // Break out of loop if no more items if (!isset($xml->channel[0]->item[$x])) { break; } $title = $xml->channel[0]->item[$x]->title[0]; echo "<li>" . $title . "</li>\n"; } A: The easiest way is to use SimpleXMLElement::count() as: $xml = simplexml_load_file($feed); $num = $xml->channel[0]->count(); for ($x=0; $x<$num; $x++) { $title = $xml->channel[0]->item[$x]->title[0]; echo "<li>" . $title . "</li>\n"; } Also note that the return of $xml->channel[0] is a SimpleXMLElement object. This class implements the Traversable interface so we can use it directly in a foreach loop: $xml = simplexml_load_file($feed); foreach($xml->channel[0] as $item { $title = $item->title[0]; echo "<li>" . $title . "</li>\n"; } A: You get count by count($xml). I always do it like this: $xml = simplexml_load_file($feed); foreach($xml as $key => $one_row) { echo $one_row->some_xml_chield; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do we always prefer using parameters in SQL statements? I am very new to working with databases. Now I can write SELECT, UPDATE, DELETE, and INSERT commands. But I have seen many forums where we prefer to write: SELECT empSalary from employee where salary = @salary ...instead of: SELECT empSalary from employee where salary = txtSalary.Text Why do we always prefer to use parameters and how would I use them? I wanted to know the use and benefits of the first method. I have even heard of SQL injection but I don't fully understand it. I don't even know if SQL injection is related to my question. A: You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept: In your example, if you just use: var query = "SELECT empSalary from employee where salary = " + txtSalary.Text; // and proceed to execute this query You are open to SQL injection. For example, say someone enters txtSalary: 1; UPDATE employee SET salary = 9999999 WHERE empID = 10; -- 1; DROP TABLE employee; -- // etc. When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text. The correct way is to use parameterized queries, eg (C#): SqlCommand query = new SqlCommand("SELECT empSalary FROM employee WHERE salary = @sal;"); query.Parameters.AddWithValue("@sal", txtSalary.Text); With that, you can safely execute the query. For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user. A: Two years after my first go, I'm recidivating... Why do we prefer parameters? SQL injection is obviously a big reason, but could it be that we're secretly longing to get back to SQL as a language. SQL in string literals is already a weird cultural practice, but at least you can copy and paste your request into management studio. SQL dynamically constructed with host language conditionals and control structures, when SQL has conditionals and control structures, is just level 0 barbarism. You have to run your app in debug, or with a trace, to see what SQL it generates. Don't stop with just parameters. Go all the way and use QueryFirst (disclaimer: which I wrote). Your SQL lives in a .sql file. You edit it in the fabulous TSQL editor window, with syntax validation and Intellisense for your tables and columns. You can assign test data in the special comments section and click "play" to run your query right there in the window. Creating a parameter is as easy as putting "@myParam" in your SQL. Then, each time you save, QueryFirst generates the C# wrapper for your query. Your parameters pop up, strongly typed, as arguments to the Execute() methods. Your results are returned in an IEnumerable or List of strongly typed POCOs, the types generated from the actual schema returned by your query. If your query doesn't run, your app won't compile. If your db schema changes and your query runs but some columns disappear, the compile error points to the line in your code that tries to access the missing data. And there are numerous other advantages. Why would you want to access data any other way? A: In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections. Also read Protect from sql injection it will guide how you can protect your database. Hope it help you to understand also any question comment me. A: Old post but wanted to ensure newcomers are aware of Stored procedures. My 10¢ worth here is that if you are able to write your SQL statement as a stored procedure, that in my view is the optimum approach. I ALWAYS use stored procs and never loop through records in my main code. For Example: SQL Table > SQL Stored Procedures > IIS/Dot.NET > Class. When you use stored procedures, you can restrict the user to EXECUTE permission only, thus reducing security risks. Your stored procedure is inherently paramerised, and you can specify input and output parameters. The stored procedure (if it returns data via SELECT statement) can be accessed and read in the exact same way as you would a regular SELECT statement in your code. It also runs faster as it is compiled on the SQL Server. Did I also mention you can do multiple steps, e.g. update a table, check values on another DB server, and then once finally finished, return data to the client, all on the same server, and no interaction with the client. So this is MUCH faster than coding this logic in your code. A: Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter. I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this... C# var bldr = new SqlBuilder( myCommand ); bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId); //or bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName); myCommand.CommandText = bldr.ToString(); Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here... using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; public class SqlBuilder { private StringBuilder _rq; private SqlCommand _cmd; private int _seq; public SqlBuilder(SqlCommand cmd) { _rq = new StringBuilder(); _cmd = cmd; _seq = 0; } public SqlBuilder Append(String str) { _rq.Append(str); return this; } public SqlBuilder Value(Object value) { string paramName = "@SqlBuilderParam" + _seq++; _rq.Append(paramName); _cmd.Parameters.AddWithValue(paramName, value); return this; } public SqlBuilder FuzzyValue(Object value) { string paramName = "@SqlBuilderParam" + _seq++; _rq.Append("'%' + " + paramName + " + '%'"); _cmd.Parameters.AddWithValue(paramName, value); return this; } public override string ToString() { return _rq.ToString(); } } A: Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface such as a desktop program or web site. In your example, a user can directly run SQL code on your database by crafting statements in txtSalary. For example, if they were to write 0 OR 1=1, the executed SQL would be SELECT empSalary from employee where salary = 0 or 1=1 whereby all empSalaries would be returned. Further, a user could perform far worse commands against your database, including deleting it If they wrote 0; Drop Table employee: SELECT empSalary from employee where salary = 0; Drop Table employee The table employee would then be deleted. In your case, it looks like you're using .NET. Using parameters is as easy as: string sql = "SELECT empSalary from employee where salary = @salary"; using (SqlConnection connection = new SqlConnection(/* connection info */)) using (SqlCommand command = new SqlCommand(sql, connection)) { var salaryParam = new SqlParameter("salary", SqlDbType.Money); salaryParam.Value = txtMoney.Text; command.Parameters.Add(salaryParam); var results = command.ExecuteReader(); } Dim sql As String = "SELECT empSalary from employee where salary = @salary" Using connection As New SqlConnection("connectionString") Using command As New SqlCommand(sql, connection) Dim salaryParam = New SqlParameter("salary", SqlDbType.Money) salaryParam.Value = txtMoney.Text command.Parameters.Add(salaryParam) Dim results = command.ExecuteReader() End Using End Using Edit 2016-4-25: As per George Stocker's comment, I changed the sample code to not use AddWithValue. Also, it is generally recommended that you wrap IDisposables in using statements. A: In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ. More information about query plan caching
{ "language": "en", "url": "https://stackoverflow.com/questions/7505808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: IE9 automatically entering Compatibility View on a certain page I'm currently managing an e-commerce website that I did not develop. The developer chose to make it so that when you're viewing an item, clicking the "Add to Cart" button uses jQuery's "post" method to post the item's ID and the specified quantity to "/items/ajax_add_to_cart" via Ajax. I got a report from the website's owner that two or three customers said that they were adding items to their shopping cart but that their shopping cart appeared to be empty. I investigated and found the following entries in the Apache access log (IP address and URLs changed): 127.0.0.1 - - [19/Sep/2011:12:49:50 -0400] "GET /items/view/1234 HTTP/1.1" 200 12117 "http://www.example.com/items/search/[keyword]" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; WOW64; Trident/5.0)" 127.0.0.1 - - [19/Sep/2011:12:50:15 -0400] "POST /items/ajax_add_to_cart HTTP/1.1" 200 15 "http://www.example.com/items/view/1234" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/5.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; .NET4.0C; BRI/1)" 127.0.0.1 - - [19/Sep/2011:12:50:16 -0400] "GET /items/view_cart HTTP/1.1" 200 10305 "http://www.example.com/items/view/1234" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; WOW64; Trident/5.0)" Notice that when the "/items/ajax_add_to_cart" page is accessed, the user agent string implies that Internet Explorer 9 automatically went into Compatibility View. That explains why the cart ends up being empty. I'm not able to replicate this at all, though. Any ideas on why this is happening? I will probably add the <meta http-equiv="X-UA-Compatible" content="IE=Edge"/> tag to fix it, but I'd like to be able to reproduce the problem first just to be absolutely certain of what's going on. A: I have recently been asked to rescue two sites where IE9 has automatically gone into Compatibility View. In both instances the issue was a single line of CSS. Almost unbelievable. The CSS in both cases was valid with correct syntax. The first was a font declaration, the second a font-family declaration. Both contained a font stack. Removing the line fixed the problem. So, ths may well not be the answer you're looking for, but I'd say check the CSS!
{ "language": "en", "url": "https://stackoverflow.com/questions/7505809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: StructureMap - Ability to replace an assembly at runtime Example: Console application: class Program { static void Main(string[] args) { var calculator = ObjectFactory.GetInstance<ICalculator>(); for (var i = 0; i < 10; i++) { Console.WriteLine(calculator.Calculate(10, 5)); Console.ReadLine(); } Console.ReadLine(); } } Assembly "Interface": public interface ICalculator { int Calculate(int a, int b); } Assembly "Implemenation": internal class Calculator : ICalculator { public int Calculate(int a, int b) { return a + b; } } Assembly "Implemenation", this assembly shall replace the assembly above at runtime: internal class Calculator : ICalculator { public int Calculate(int a, int b) { return a * b; } } Assembly "Resolver" For<ICalculator>().Use<Calculator>(); I want to replace the concrete implementation at runtime. This could be done by an UpdateService which just replace the old assembly "Implementation". The problem I have is that the assembly "Implementation" is locked. I can't replace it. What do I have to do to achieve this? Is the IoC container responsible for my requirement or do I have to build my own infrastructure? EDIT: In a web environment you can easily replace an assembly. I did this already with success. A: I'm afraid you can only load an additional assembly. From MSDN: There is no way to unload an individual assembly without unloading all of the application domains that contain it. Even if the assembly goes out of scope, the actual assembly file will remain loaded until all application domains that contain it are unloaded. A: I think this has what you're looking for: http://structuremap.net/structuremap/ChangingConfigurationAtRuntime.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7505812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSRS 2008 R2 - Add total line to chart I have created a line chart that displays the different types of messages sent over a month (Email, Print, Voice) which are displaying on the chart just fine.Is there an easy way to add another line which totals the values for the 3 series without changing the SQL? A: There are two way to do this in reporting services: 1. Directly in the chart Add a new series to your line chart. Set the expression for the value to be =Fields!Email.Value + Fields!Print.Value + Fields!Voice.Value 2. With a calculated field in the dataset Set the calculated field "AllMessages" to be the sum of Email, Print and Voice. Then add AllMessages to your chart. Youtube Walkthrough calculated field
{ "language": "en", "url": "https://stackoverflow.com/questions/7505815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Symfony: How to save data from sfWidgetFormDoctrineChoice with multiple checkboxes I have problem with save data from choices widget. Here is part of schema: Client: columns: id: type: integer primary: true autoincrement: true grupy: type: array options: collate: utf8_unicode_ci charset: utf8 relations: Grupy: type: many local: grupy foreign: id class: KlientGrupy KlientGrupy: options: collate: utf8_unicode_ci charset: utf8 columns: id: type: integer primary: true autoincrement: true item: type: string(255) relations: Klienci: type: many local: id foreign: grupy ClientForm class: class ClientForm extends BaseClientForm { public function configure() { $this->widgetSchema['grupy']->setOption('multiple', true); $this->widgetSchema['grupy']->setOption('expanded', true); $this->widgetSchema['grupy']->setOption('add_empty', false); $this->widgetSchema['grupy']->setAttribute('class', 'checkBoxLabel'); } } BaseClientForm class: $this->setWidgets(array( 'id' => new sfWidgetFormInputHidden(), 'grupy' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Grupy'), 'add_empty' => true)), )); When i save with one checkbox then all is ok, but when i try do it for more than one i get that problem: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens A: You can find answer in comment in my question
{ "language": "en", "url": "https://stackoverflow.com/questions/7505816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql nested query passing one value to nested query Hi I have a coupon system that uses one table (called "coupons") to store info about each type of available coupon that one could generate, and another table (generatedcoupons) to store info about each coupon generated. I'm having a hard time comparing info in each table. The schemas: table: coupons +----+------+--------------------+---------------+ | id| owner| expiration_date| limit_per_user| | 15| 34| 2011-09-18 00:00:00| 2| +----+------+--------------------+---------------+ table: generatedcoupons +----+----------+------+--------------------+------+--------+ | id| coupon_id| owner| date| used| user_id| | 1| 15| 34| 2011-09-17 00:00:00| false| 233| +----+----------+------+--------------------+------+--------+ I'm trying to run queries to display coupon from the point of view of a user (i.e. all queries will have where user_id='$userid'. I can't figure out how to display all coupons where the limit_per_user has not been met... here's what I've got that doesn't work: select * from coupons where owner=34 and (count(SELECT * from generatedcoupons where user_id=233 and coupon_id=coupons.id)<limit_per_user) A: For MySQL, joining is usually faster and more reliable than subqueries, but makes you think a bit harder. In this case, you need to limit based on the number of joined rows, which requires a post-grouping calculation; fortunately, that's precisely what the HAVING clause is for: select coupons.* from coupons left join generatedcoupons on user_id = 233 and coupon_id = coupons.id where coupons.owner = 34 group by coupons.id having count(generatedcoupons.id) < limit_per_user A: select * from coupons as c left join generatedcoupons as g on g.user_id = 233 and g.coupon_id = c.id where c.owner=34 group by c.id having count(g.id) < c.limit_per_user
{ "language": "en", "url": "https://stackoverflow.com/questions/7505818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get Information from XML file I am trying to extract the text value and size value in the row tag from this xml. <items> <item> <table> <row text="foo" size="4"/> </table> </item> </items> I was able to get the values for this xml: <items> <item> <textbox text="foo"> </item> </items> with this code. NodeList textbox = element.getElementsByTagName("textbox"); line = (Element) textbox.item(0); String textbox_text = line.getAttribute("text"); can someone tell me how should I go about this? A: NodeList items = element.getElementsByTagName("items"); for(int i=0 i<items.getLength(); i++) { NodeList item = items.item(i).getElementsByTagName("item"); for(int j=0 j<item.getLength(); j++) { NodeList table = item.item(j).getElementsByTagName("table"); for(int k=0 i<table.getLength(); k++) { NodeList rows = table.item(k).getElementsByTagName("rows"); for(int h=0 i<table.getLength(); h++) { rows.item(h).getAtribbute("text"); rows.item(h).getAtribbute("size"); } } } } something like that A: I suppose, NodeList textbox = element.getElementsByTagName("row"); line = (Element) textbox.item(0); String textbox_text = line.getAttribute("text"); String textbox_size = line.getAttribute("size"); If you want to use textbox_size as a number, you might want to cast it as an int. If this code fails, it could well be due to the seemingly random tag making this XML invalid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle/SQL - Returning semi-unique records what I'm trying to do is go through a table and return semi-unique results based on a certain field. So for example with this data field1 segment field2 field3 field4 etc ----------------------------------------------- xxxx S1 xxx xxx xxx xxx xxxx S4 xxx xxx xxx xxx xxxx S1 xxx xxx xxx xxx xxxx S2 xxx xxx xxx xxx xxxx S2 xxx xxx xxx xxx xxxx S1 xxx xxx xxx xxx xxxx S3 xxx xxx xxx xxx What I want to do is return 1 records of every segment type. The other data should come from the selected record, but which record that is doesn't matter as long as I get 1 unique record for each segment type. field1 segment field2 field3 field4 etc ----------------------------------------------- xxxx S1 xxx xxx xxx xxx xxxx S4 xxx xxx xxx xxx xxxx S2 xxx xxx xxx xxx xxxx S3 xxx xxx xxx xxx Hopefully that makes sense. Also this will run against Oracle so whatever the most efficient way to do this would be great (source table will have something like 10 mil records and 30 distinct segments) A: You could do something like SELECT segment, field1, field2, field3, field4 FROM (SELECT segment, field1, field2, field3, field4, row_number() over (partition by segment order by rownum) rnk FROM table_name) WHERE rnk = 1 This will pick an arbitrary row for each SEGMENT. When, in the future, someone decides that they do care what row is picked, you can adjust the ORDER BY in the analytic function. A: I know this technique works when you only want to return the segment column for example. SELECT DISTINCT segment FROM YOUR_TABLE_NAME But, when you try and query as so: SELECT DISTINCT SEGMENT, FIELD2, FIELD3 FROM YOUR_TABLE_NAME WHERE BLAH = BLAH This will return more than one row for each segment with different info in it. This problem seems kinda similar to the problem found here. Please comment if i am not understanding your problem correctly =) A: If you don't want to type all the field names: SELECT * FROM table_name t0 WHERE NOT EXISTS ( SELECT * FROM table_name t1 WHERE t1.segment = t0.segment AND t1.ROWNUM < t0.ROWNUM ; I don't know exactly how exactly the tuple-id/ rownumber / object-id is called in oracle, but I'm sure it exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passwords and svn Hi I am accessing a repository through a URL of type svn+ssh:// Reading the following quote from SVN and SSH from Adobe I am a little confused "Before you configure Subversion or Dreamweaver for SVN+SSH, create an RSA key pair and configure the public key on the server. This public/private key pair is used to authenticate with the server, instead of storing and passing your password in plain text." So if I just acces a repository by svn+ssh:// pe. from command line, my password is send in clear text ? I thought part of ssh was to encrypt the password, no ? Maybe I was unclear, I have not generated any keypairs so use my password every time, does that change anything or is the quote written in confusing way ? Thank you. A: Part of ssh is to encrypt everything, not just your password. So, your password would not be going over the wire in plain text. A: SSH never sends passwords in plain text. However, non-SSH protocols such as svn:// may send the password in plain text. Adobe is recommending that users use SSH. Adobe also recommends that if SSH is used, then RSA key pairs are also used. Key pairs are easier because you don't have to keep typing your password for every operation (when used with an SSH agent). A: There is no password at all in this case. All authentication happens based on key pair. One key is on your client machine, another one lies on the server. All traffic is also encrypted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework throws "Collection was modified" when using observable collection I have a class Employee, and class Company, which contains a (observable) list of employees. The observable list is derived from List<>, and basically looks like this: public class ObservableList<T> : List<T> { // declaration of delegates and events here new public virtual void Add(T item) { CollectionChangingEventArgs<T> e = new CollectionChangingEventArgs<T>(new T[] { item }, ObservableListChangeAction.Adding); OnAdding(e); if (e.CancelAction) return; base.Add(item); CollectionChangedEventArgs<T> ed = new CollectionChangedEventArgs<T>(new T[] { item }, ObservableListChangeAction.Added); OnAdded(ed); } } The events are wired in Company constructor. So the whole thing looks approximately like this: public class Employee { // stuff here } public class Company { // stuff ObservableList<Employee> employees = new ObservableList<Employee>(); public ObservableList<Employee> Employees { get { return this.employees; } } public Company() { Employees.Adding += new ObservableList<Employee>.CollectionChangingEventHandler(Employees_Adding); } void Employees_Adding(object sender, CollectionChangingEventArgs<Employee> e) { // do some checks.. none alter the collection *edit* // I have a line that does this: **employee.Employer = this;** //So if the employer was saved prior to this point, it errors out. } } Now, if I do this: Company c = new Company(); Employee e = new Employee(); c.Employees.Adding(e); c.Save(); it works fine. If, however, I save employee first, like this: Company c = new Company(); Employee e = new Employee(); e.Save(); c.Employees.Adding(e); c.Save(); then EF throws an exception: Collection was modified; enumeration operation may not execute. Save() method comes from a base class, basically does this: this.dbContext.Set<T>().Add(instance); dbContext.SaveChanges(); This is a stack trace: at System.Collections.Generic.List1.Enumerator.MoveNextRare() at System.Data.Objects.ObjectStateManager.PerformAdd(IList1 entries) at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force) at System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity) at System.Data.Entity.DbSet`1.Add(TEntity entity) If I change ObservableList to List<> - it works. If I don't hook up events - it works. So basically EF doesn't like the events for some reason. When I'm saving the Company, they're not fired, btw. I am confused.. Any idea what could be causing this ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }