Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Within a php/mysql system we have a number of configuration values (approx 200) - these are mostly booleans or ints and store things such as the number of results per page and whether pages are 2 or 3 columns. This is all stored in a single mysql table and we use a single function to return these values as they are requested, on certain pages loads there can probably be up to around 100 requests to this config table. With the number of sites using this system this means potentially thousands of requests each second to retrieve these values. The question is whether this method makes sense or whether it would be preferable to perform a single request per page and store all the configs in an array and retrieve from here each time instead.
Use a cache such as memcache, APC, or any other. Load the settings once, cache it, and share it through your sessions with a singleton object. Even if the query cache is saved, it's a waste of time and resources to query the database over and over. Rather, on any request that modifies the values, invalidate the cache that is in memory so it is reloaded immediately the next time someone requests a value from it.
If you enable `MySQL` query cache, the query that selects your values will be cached in memory, and `MySQL` will give an instant answer from memory unless the query or data in the underlying tables are changed. This is excellent both for performance and for manageability. The query results may be reused between the sessions: that means, if you have `1000` sessions, you don't need to keep `1000` copies of your data.
store in array or use multiple db queries
[ "", "php", "mysql", "" ]
I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code: ``` function IsValidAge(value) { if (value.length == 0) { return false; } var intValue = parseInt(value); if (intValue == Number.NaN) { return false; } if (intValue <= 0) { return false; } return true; } ``` The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer? Thank you
**UPDATE** I have fixed the code that had an error and added a var called **key** to store the key pressed code using **keyCode** and **which**, that depend of the browser. ``` var key = e.which || e.keyCode; ``` Thanks Donald.McLean :) --- If you want to check if you are writing numbers while typing (and avoid writing other characters into your input field), you can use this simple function and you can define the elements allowed (this include whatever you want to filter). In this way you can choose not only integers but for example a certain group of characters. The example is based in jQuery to attach it to an input field. ``` $('#myInputField').keypress(function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval of values (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } }); ``` If you use other key than the defined, it won't appear into the field. And because Angular.js is getting strong these days. this is the directive you can create to do this in any field in your web app: ``` myApp.directive('integer', function() { return function (scope, element, attrs) { element.bind('keydown', function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } }); } }); ``` But what happens if you want to use `ng-repeat` and you need to apply this directive only in a certain number of fields. Well, you can transform the upper directive into one prepared to admit a **true** or **false** value in order to be able to decide which field will be affected by it. ``` myApp.directive('rsInteger', function() { return { restrict: 'A', link: function (scope, element, attrs) { if (attrs.rsInteger === 'true') { element.bind('keydown', function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } }); } } } }); ``` To use this new directive you just need to do it in a input type text like this, for example: ``` <input type="text" rs-integer="true"> ``` Hope it helps you.
``` var intRegex = /^\d+$/; if(intRegex.test(someNumber)) { alert('I am an int'); ... } ``` That will absolutely, positively fail if the user enters anything other than an nonnegative integer.
JavaScript - Test for an integer
[ "", "javascript", "" ]
I'm curious because I couldn't find out about this on MSDN. I've found the `Release()` function is present in various COM objects which I'm obviously supposed to use for deleting pointers. But I'm not sure what does it return exactly? I used to think it would return the number of references which still exist to the object remaining, therefore something like: ``` while( pointer->Release() > 0 ); ``` Would obviously release all references to that pointer? Or am I not seeing something? \*note I'm talking about this from the concept of the `IDirect3DTexture9::Release()` function
Your theory is true. COM memory management is based on reference counting. The `Release` method of `IUnknown` interface will decrement the reference count and return it. That function will not release *references*. It doesn't know who holds the reference. It just decrements the reference count until it reaches zero and then the object will be destructed. It's dangerous as others might still hold a reference to it that will become invalid after object's destruction. Thus, you should only call `Release` for each `AddRef` you had previously called.
In addition to what Mehrdad said, the return value of Release is intended for debugging purposes only. Production code should just ignore it. **Looping until Release() returns 0 is definitely a bug** - you should never release references you don't own.
Microsoft objects, the Release() functions return value?
[ "", "c++", "com", "pointers", "directx", "reference-counting", "" ]
Say i have the following: ``` public class Person{ public int ID {get; set;} public string Name {get; set;} } public class Phone{ public int ID {get; set;} public string PhoneNumber {get; set;} } public Class AddEditViewModel{ public Person MyPerson{get; set;} public List MyPhones{get; set;} } ``` I want to create a create/edit action in my MVC app - the page inherits from ``` ViewPage<AddEditViewModel> ``` and i want to be able to dynamically add the fields for the end-user to add a "phone" (anywhere between 0 - 5 phones). How would i pass that data to the Create/Edit method in my controller. I have tried the following, but nothing seems to get the phone numbers. ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(AddEditViewModel data){} ``` with this i can call data.MyPerson.Name and get the value but data.MyPhones == null My question would be: how would one set up the view and controller to be able to submit a single add/edit page that creates a single person object with multiple phone objects given the code above?
If I understand your question correctly you are asking about binding to a list of phone numbers. Phil Haack has a post of how to do [model binding to a list](http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx) Hope this helps.
You can create dynamic control in MVC view and bind with your model. for Example, You can use list collection in your view model class or model class and can create dynamic control in view, it will be automatically bind with your model properties.
Dynamic Controls in a Strongly Typed View (ASP.NET MVC)
[ "", "c#", "asp.net-mvc", "model-view-controller", "" ]
I would like to update a form's `textbox` in winforms with data that is being processed from a class file. ### Example: ``` Class.RunProcess(); ``` Inside of RunProcess I would like to fire an event that will update the textbox with the text that I pass in on the win form. I know you can do this with events so I don't have to make the `textbox` public or pass it into the many methods I have, I am just not quite sure how to start. **Edit**: Maybe I am just not clear. I have a windows form with a text box on it. I have a button that runs a process. The process is in a class file outside of the form class. Inside this process method I would like to be able to update the text box on the main form without having to pass the TextBox as a parameter to all the methods that I will have (I currently have 6 and will be more). I thought I could subscribe to an event that would allow me to display a message in the text box while the processes ran in my class.
It's probably time to consider: 1. Databinding your textbox to your class 2. Model/View/Presenter (MVP) For #1 (Databinding), you can use the INotifyPropertyChanged interface on your class and raise the event for changed properties. ``` public class BusinessModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int _quantity; public int Quantity { get { return _quantity; } set { _quantity = value; this.OnPropertyChanged("Quantity"); } } void OnPropertyChanged(string PropertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } } } ``` And in your form, youcan bind the .Text property of the textBox to the object in several ways. Through the UI or in code. Links: * [Bind Better with INotifyPropertyChanged](http://www.codeproject.com/KB/cs/BindBetterINotifyProperty.aspx) * [How to: Implement the INotifyPropertyChanged Interface](http://msdn.microsoft.com/en-us/library/ms229614.aspx) Now, if you need to add to text that already exists such as in your example, you can either track the full text in the class or raise events from your class and respond in the form code. Tracking it in the class would be better - you really don't want any logic in the form at all, which brings us back to binding and/or some form of MVP/MVC.
If you're wanting Class.RunProcess to run when an event from an external class is fired then you can do it like this ``` public delegate void MyDelegate(); public class MyClass { public event MyDelegate Myevent; public void DoSomething() { this.Myevent(); } } public static class Class { public static void RunProcess() { txtData.Text += "Message"; } } public partial class Form1 : Form { public Form1() { InitializeComponent(); MyClass myClass = new MyClass(); myClass.Myevent += Class.RunProcess; } } ```
How can I update a TextBox from a class using events?
[ "", "c#", "winforms", "events", "" ]
For the following code ``` var validate = from P in this.DataContext.Persons where P.UserName.Equals(login) && P.Password.Equals(password) select new { P.FirstName, P.LastName, P.EmailAddress }; ``` If record exists i want to get the first name and return it. How can i get the firstName from var validate?
`validate` here is going to be a *set* (`IQueryable<T>`) of data. You may need to use `FirstOrDefault()`, for example: ``` var record = validate.FirstOrDefault(); if(record != null) { string firstName = record.FirstName; } ```
``` Console.WriteLine(validate.FirstOrDefault().FirstName); ``` Otherwise you'll have to loop through the set since that what your query is returning Likely a set of one but it's still a set.
Getting value from VAR
[ "", "c#", "linq", "linq-to-sql", "" ]
I want to know what are some guidelines for commenting? I am coding in Java for class. I want to have readable code. In another question I was told "how" comments should be reserved for difficult sections of code. I was told that my code comments added no knew information. Comments are not only for readers. They are also reminders to the writer of their original intent and to help match grouping symbols. I am new to Java and Stackoverflow. Why am I getting greifed? I thought this website was designed to allow programmers to help each other. I feel like a target because I have a question with a -3 vote. Are we here to help new programmers or here to puff up our chests with pride at others expense?
Different people have different styles, so to some extent whatever you read here will be just someone's suggestions. There are no cold, hard rules for commenting. The most important thing you should know about commenting in Java is Javadocing. It's a special type of comment that can be parsed out and used in IDEs (like Eclipse and Netbeans), to help make the coding process easier. Javadoc comments start with a /\*\* and end with a \*/ It's just like a regular multi-line comment but with two asterisks in the first one. You put Javadoc comments at the beginning of classes, methods, or instance variables to describe what they do. There are standard ways to format data in the comment, which are tags. Some common tags are @author and @version. You can see some of Sun's suggestions for writing Javadoc comments here: <http://java.sun.com/j2se/javadoc/writingdoccomments/> What I like to do after that is use single-line comments ( the double slash // ) to describe my logic. If I need more than one line, I'll just use multiple single-line comments. The advantage of this technique is that if you need to later comment out large swaths of text, you can use the regular multi-line comment /\* \*/ without worrying about the nested comment problem. I hope that helps you get a rough idea of how to use comments in java. My advice is partly a product of the teaching assistant job I have for a university's Intro Java class and partly from working in industry. Others with different background may have more suggestions.
I'd follow the Stack Overflow guidelines mentioned in the following posts: * [When Not to Comment Code](https://stackoverflow.com/questions/163600/when-not-to-comment-code) * [Function/Class Comment formatting Conventions](https://stackoverflow.com/questions/991820/function-class-comment-formatting-conventions) * [What is your personal approach / take on Commenting?](https://stackoverflow.com/questions/499890/what-is-your-personal-approach-take-on-commenting)
Commenting Conventions
[ "", "java", "comments", "" ]
I'm trying to write an own **layout manager**. Components must be placed and sized **relative** to each other. This means: when the user drags or resizes an component, some other components (but **not** the one altered manually by user) have to be altered. Swing tells the layout manager to layout the components every time when some of them is moved/resized. This is a problem hence the layout manager **itself** moves/resizes components: It fails, the method *layoutContainer(Container parent)* is called multiple times. An **example** of the whole thing (simplified, in fact my layout manager does more complex stuff): * `[-component1-][-component2-------][-component3-]` * user resizes component2 to be smaller, my layout manager would adjust other components so that all of them would take same space as before: `[-component1-][-component2-][-component3-------]` * here, the actions **should stop**, but they go on: now the layout manager is invoked because of resizing component3 How could I achieve my intention (in an elegant way)? Thank you. **EDIT:** Removed threading-related information after suggestions by answerers.
This kind of feedback loop is not uncommon when dealing with events. There are several approaches you can use to break out of this loop and the one I suggest you try is to keep track of the calculated sizes of the components. Then, when you handle the resize event, compare the actual size to the calculated size, and just return without doing anything if they are equal. This is probably the most robust approach as it doesn't depend on the order or frequency of the events. As stated elsewhere you shouldn't need to touch anything related to threads from your layout manager.
This isn't a thread synchronization issue. You said that when *users* change the size or location of an object other objects must be altered. I'm guessing that you are listing for some kind of change event so that you can trigger a recalculation of the layout whenever the user changes an object. If so, I'm further guessing that your layout manager is triggering this event, causing it to be invoked again. Of course, this is only speculation without reviewing your code.
Swing: Problem distinguishing between user-induced and automatic components resizing (Writing a custom LayoutManager)
[ "", "java", "multithreading", "swing", "events", "synchronization", "" ]
I've got a php script that uses curl and everything is fine. It runs via a cron job. I come back later and each time it runs a new file with the output has been saved. How do I prevent these files from being created?
It's the cron daemon that makes that file. By default it saves the stdout into a file. Change the script to point its output to /dev/null instead: /etc/crontab: ``` 59 * * * * USER curl localhost/script.php > /dev/null 2>&1 ``` That would do the trick. /Zyber
If you're using wget to call your script in cron, you might need to set output to dev/null in the following manner: ``` 59 * * * * wget -O - -q http://yourdomain.com/path/to/script.php ``` The `-O` specifies where output is written and the following `-` specifies dev/null. `-q` tells wget to run in quiet mode, meaning it won't write messages to stdout. You can also suppress any output from cron, if it is creating the files, by changing the above line to the following: ``` 59 * * * * wget -O - -q http://yourdomain.com/path/to/script.php > /dev/null 2>&1 ```
php curl leave file in directory - How to clean up
[ "", "php", "curl", "" ]
I'm trying Eclipse (with JavaEE and Web Development plugins) as a JavaEE/GoogleAppEngine IDE. In HTML editor if I put a `<script ... src="..." />` in `<head>` I automatically get content assist for JavaScript in the referenced file. I was wondering if it was possible to obtain content assist for other JavaScript files (e.g. jQuery or homebrew js library) inside JavaScript editor.
I just figured out how to obtain js content assist in **Eclipse JavaScript editor** (without Aptana plugins): If the project type doesn't natively contain JavaScript Support: open Web (or JavaScript) perspective, right-click on the project and select *Web Development Support* > *Add JavaScript Support* (this won't hurt if JavaScript support is already present) then right-click *JavaScript Support* within the project and select *Properties*, in the JavaScript section go to JavaScript library and then select Source tab: here you can add folders and files to be scanned by content assist for the current project --- In **Aptana Studio** (as an eclipse plugin but I suppose the standalone version is almost the same): open any js or html file, show *References* window (or open Aptana perspective in eclipse) and drag-drop js files you want to add to JavaScript scope (it is possible to build and activate different scope profiles with different JavaScript files and resources: just click *add profile* in the window toolbar)
imo, [Aptana](http://www.aptana.com/) is the best eclipse plugin for js editing. It includes support for many of the major libraries like jQuery, yui, dojo, etc. [Spket](http://spket.com/), however is also good. Though mostly if you do firefox extension development (getting a little out of date though) The built in js editor is terrible. it claims there are errors all over the place even when there clearly are not.
Eclipse JavaScript Editor: content assist for js files, autocompletion
[ "", "javascript", "eclipse", "autocomplete", "eclipse-plugin", "content-assist", "" ]
I need help designing a query that will be used to return a website's search results. Users search by selecting items from a list of attributes. Each search result item returned must have ALL the attributes selected by the user. The challenge (for me at least!) is figuring out how to only return results that have ALL the attributes versus just ANY of them. The search result items (let's call them WIDGETs) are in the WIDGET table. Possible widget attributes are in the ATTRIBUTE table. A junction table (WIDGETATTRIBUTEJUNCTION) stores the 0,1..n actual attributes for each WIDGET. I can't figure out a query that, when supplied a list of widget attributes, will return rows that have every one of these attributes. I suspect I might use an ALL subquery and/or an INTERSECT but not sure how.
You could use something similar to the following, ``` SELECT WidgetID FROM Widget INNER JOIN WidgetAttributes WA ON WA.Key = SearchAttributes.Key AND WA.WidgetID = Widget.WidgetID GROUP BY WidgetID HAVING COUNT(Widget.WidgetID) > @SearchAttributesCount ``` The key being the GROUP BY HAVING statement which limits it to only include all Widget rows which match all attributes.
If only SQL supported arrays... There are a couple of ways you can go about this, my preferred method is to send a string (containing the attribute IDs) to SQL then split the string into a table. Something like: ``` create function dbo.fn_makeArray ( @value nvarchar(max) ) returns @table table([key] nvarchar(256)) begin declare @start int; declare @end int; select @start = 1, @end = charindex(',', @value); while (@start < len(@value) + 1) begin if (@end = 0) set @end = len(@value) + 1; insert into @table ([key]) values(substring(@value, @start, @end - @start)); set @start = @end + 1; set @end = charindex(',', @value, @start); end return; end ```
SQL Query for retrieving search results
[ "", "sql", "select", "" ]
I'm experimenting with [app-engine-patch](http://code.google.com/p/app-engine-patch/) (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?
Adding the Facebook directory from the PyFacebook install directory to the app-engine-patch application allows you to add 'facebook.djangofb.FacebookMiddleware', to the MIDDLEWARE\_CLASSES in settings.py. Then your view can use 'import facebook.djangofb as facebook' and '@facebook.require\_login().' I haven't gone end to end, but when I tried to display the view preceded by '@facebook.require\_login()', I was redirected to the Facebook login.
I run a system on for social networks and facebook on GAE with back-end in Python, front end in Javascript and Flash. I use mostly client side js libraries to pass data back to the server side datastore. This library for facebook to be exact: <http://code.google.com/p/facebookjsapi/> There is a reason for this. Most of what we are doing will be running on its own site, in iframes in different social networks and in widgets etc. But for the most part this has worked very well. It is good because we can swap out our backend at any time or even run it on multiple platforms as it is also using a python rest GAE library but any backend would do with this setup.
Facebook, Django, and Google App Engine
[ "", "python", "django", "google-app-engine", "facebook", "" ]
Is it possible to set a style's TargetType property in XAML to a Generic Class? ``` public class Selector<T> : Control { } ``` and then in xaml ``` <Style x:TargetType="Selector"> <Setter Property="MyProperty" Value="Green" /> </Style> ``` This wont work because Selector is missing a type argument.
You cannot bind to an open generic type like `List<T>`, you can however bind to a closed generic type like `List<Person>` by defining a placeholder type. **C#**: ``` class People : List<Person> {} ``` **XAML**: ``` <Style TargetType="{x:Type People}"> ... </Style> ``` **Update**: You either need to specify [`TargetType`](http://msdn.microsoft.com/en-us/library/system.windows.style.targettype.aspx) *or* the `x:Key` property for a Style, not both.
Generics have pretty limited support in XAML. That being said, Mike Hillberg has a pretty interesting post [here](http://blogs.msdn.com/mikehillberg/archive/2006/10/06/LimitedGenericsSupportInXaml.aspx) about custom markup extensions that may help.
Setting a style's TargetType property to a generic class
[ "", "c#", "wpf", "xaml", "targettype", "" ]
We're evaluating a couple of Python libraries for Graph manipulation. We tried 'networkx' (<http://networkx.lanl.gov/>) and 'igraph' (<http://igraph.sourceforge.net/>). While both are excellent modules, igraph is faster due to its nature - it's a Python wrapper over libigraph - a blistering fast graph C library (uses LAPACK etc). Now, the igraph library is GPL licensed. My question is: Can I import igraph and use it in my commercial Python script? (This is a general question, not just limited to igraph. Apologies if the answer is obvious - I'm a license-newb!) Thanks, Raj EDIT: More specifically, does simply importing a GPL Python module make my commercial code liable to be released to the public?
IANAL, but: > *Now, the igraph library is GPL licensed. My question is: Can I import igraph and use it in my commercial Python script?* **YES**. You can write commercial software and distribute it under the GPL. Nothing on GPL prevents commerce. It even explicity says that you can SELL your software at will, > *More specifically, does simply importing a GPL Python module make my commercial code liable to be released to the public?* NO. **You don't have to release anything**. You don't even have to distribute anything. If you ever distribute your program to someone, you must give (to this person only) the source code, and give full freedom to modify and distribute it under the same license. Distributing something under GPL or using GPL libraries in your code doesn't force you to create a website and put your program for everybody in the world.
IANAL, etc etc, but: The Free Software Foundation has consistently claimed that software linked to a library covered by GPL is a derived work, and thus needs to be covered by GPL itself (indeed, that's the main difference of the LGPL license). I don't know how the situation stands in court precedents in various jurisdiction, &c, but if you don't want to risk having to litigate on the issue [which would no doubt bring costs and bad PR even if it were to ultimately succeed], it may be more prudent to avoid linking to GPL libraries (including dynamic linking) if you don't want to distribute the sources to your code.
Question on importing a GPL'ed Python library in commercial code
[ "", "python", "licensing", "" ]
I have a nice function setup for formatting dates as per [Leading Zero Date Format C#](https://stackoverflow.com/questions/461098/leading-zero-date-format-c-asp-net) But it turns out in our farm we have some blades running on a UK locale and some on a US locale so depending on which it crashes. So what I'm after is how do I test the current server locale? Something like... ``` if(Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "GB"){ ... } else { ..otherstatement } ``` Ta
You should pass in the desired culture to all of your formatting functions (InvariantCulture, usually). Alternatively, you can *set* the culture on the page [like so](http://msdn.microsoft.com/en-us/library/bz9tc508.aspx). That code could also go in the Application BeginRequest override in your asax.cs file in order to affect all pages.
``` Date now = DateTime.Now; CultureInfo ci = Thread.CurrentThread.CurrentCulture; Console.WriteLine(now.ToString("d", ci)); ```
How do I detect the current culture of the executing thread?
[ "", "c#", "asp.net-2.0", "culture", "" ]
When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python? This might seem like an obvious question, but I'm new to web development frameworks so I must ask :)
It just needs to support Python 2.3 or later (but not 3.0, yet), preferably with `mod_wsgi` support (although it also works with [a bunch of other options](http://code.djangoproject.com/wiki/ServerArrangements), if required).
Technically, as other responders say, the host needs very little (hey, Django even runs with Google app engine for all the latter's limitations!-). But if you want a little bit more (as in, say, *support* for any issues you might encounter!), I suggest you read [this site](http://djangohosting.org/) as well -- it will take you but a short time, and it may prove to be really useful info.
Deploying Django
[ "", "python", "ruby-on-rails", "django", "" ]
Take a look at the map coordinates on this [page](http://stable.toolserver.org/geohack/geohack.php?pagename=Area_51&params=37_14_06_N_115_48_40_W_type:airport). This is linked in from Wikipedia and the coordinates are passed the query string. I'm not sure of the actual terms for this but How do I convert the coordinates? They look like this: **37° 14′ 6″ N, 115° 48′ 40″ W** I would like them to look like this: **37.235, -115.811111** , which is a format readable by Google maps, as seen in [this example](http://maps.google.com/maps?ll=37.235,-115.811111&spn=0.03,0.03&t=m&q=37.235,-115.811111). How do I do this in PHP, and what are the two different types of coordinates called?
The original format is in hours, minutes, seconds format. To convert to decimal, do: D = H + M/60 + s/3600 So in your example, 37,14,6 becomes 37 + 14/60 + 6/3600 = 37.235, as stated. If the latitude is N the result is positive, if S, negative. If the longitude is E the result is positive. If west the result is negative.
[Here](http://transition.fcc.gov/mb/audio/bickel/DDDMMSS-decimal.html) is the Javascript function that does what you are talking about. > This utility permits the user to convert latitude and longitude > between decimal degrees and degrees, minutes, and seconds. For > convenience, a link is included to the National Geodetic Survey's > NADCON program, which allows conversions between the NAD83 / WGS84 > coordinate system and the older NAD27 coordinate system. NAD27 > coordinates are presently used for broadcast authorizations and > applications. > > This utility requires that Javascript be enabled to perform the > calculations.
How do I convert these coordinates to coordinates readable by Google Maps?
[ "", "php", "google-maps", "coordinates", "" ]
I have 2 'libraries' which I need to include on the same page. Simple Machine Forums and Wordpress. However both have the function is\_admin() which conflicts with each other. ``` Fatal error: Cannot redeclare is_admin() (previously declared in /home/site.com/wordpress/wp-includes/query.php:100)in /home/site.com/smf/Sources/Security.php on line 82) ``` What would be the best way to get around this? As I dont want to have to modify all calls to one library to be is\_admin2() for example.
I believe you don't have too much choice but to rename the function or, wrap all functions around a class. That's the problem with PHP <= 5.\*: no namespaces, and developers often prefer to write a script full of loose functions, than to use an object oriented approach.
I would bite the bullet manually rename each function call for the smaller library (I'm guessing that would be the Forums one). Good luck.
Function name conflict in php from 2 different libraries
[ "", "php", "function", "" ]
My java program is packaged in a jar file and makes use of an external jar library, [bouncy castle](http://www.bouncycastle.org/). My code compiles fine, but running the jar leads to the following error: **Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes** I've googled for over an hour searching for an explanation and found very little of value. If anyone has seen this error before and could offer some help, I would be obliged.
The solution listed here might provide a pointer. > [Invalid signature file digest for Manifest main attributes](http://www.mail-archive.com/itext-questions@lists.sourceforge.net/msg34999.html) Bottom line : > It's probably best to keep the official jar as > is and just add it as a dependency in the manifest file for your > application jar file.
For those who got this error when trying to create a shaded [uber-jar](https://stackoverflow.com/a/11947093/1268003) with `maven-shade-plugin`, the solution is to exclude manifest signature files by adding the following lines to the plugin configuration: ``` <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> <!-- Additional configuration. --> </configuration> ```
"Invalid signature file" when attempting to run a .jar
[ "", "java", "jar", "executable-jar", "" ]
my boss wants me to code an URLrewriting for, let's say "<http://our.domain.com/SomeText>" -- that is, if the URL does NOT contain ".php" or ".html", it should be processed by a script like "<http://our.domain.com/process.php?string=SomeText>". Is this possible with a simple regex? I just cannot find the right expression to do this. I started by redirecting requests to some special subdir, but now it should work directly without any further subdir, so I somehow have to separate regular requests for exuisting pages to requests that don't contain ".php" or ".html"... Any advice or link for me? Best regards, Roman.
Using mod\_rewite you could do this to re-write .php and .html URLs like this: ``` RewriteEngine on RewriteRule !\.(php|html)$ process.php/$1 [NC] [QSA] ``` However you may also want to stop it from re-writing URLs to files which actually exist. (There may be other files lying around - images/css etc. which you don't want to be re-written) You could amend the above to add checks: ``` RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule !\.(php|html)$ process.php/$1 [NC] [QSA] ``` Adding this check may mean that you don't actually need check whether the extension is anything other than .php or .html, because you know that it will only be rewritten if the requested file does not exist, so you could amend the RewriteRule line to be this: ``` RewriteRule ^(.*)$ process.php/$1 [NC] [QSA] ``` This will mean any requested URL that does not exist as a file will be handled by process.php.
Something like this should do the trick ``` RewriteEngine on RewriteCond %{REQUEST_URI} !\.php RewriteCond %{REQUEST_URI} !\.html RewriteRule (.*) /process.php?string=$1 [QSA] ``` there are some caveats regarding if this will go in .htaccess or directly in the VirtualHost definition (to put or not a leading /). Additionally you should load mod\_rewrite. All this supposing you are actually using Apache and can use mod\_rewrite. What this does is that if the requested URI doesn't contain the strings .php and .html it then internally redirects the requests to the process.php file with what was written as a query string argument. If you have problems with this then use ``` RewriteLog "/tmp/rewrite.log" RewriteLogLevel 9 ``` and check how it is working. For this to work you have to control the server, as it has to be used in a main configuration file (no .htaccess possible).
RegEX for URLrewriting if NOT ".php" in the path
[ "", "php", "url-rewriting", "" ]
I've set up a test database to begin unit-testing an app that I've recently been added to. It is a 3-tier design (presentation layer, BOL and DAL) and this is my first time writing unit tests. I've decided to start at the BOL and I figure the best way is to swap out the ConnectionString (which has been passed along as a Shared String) with one that points to my new test database. However, I don't wish to change any production code. I simply wish to somehow redirect the app to the test database during unit tests. How might I go about accomplishing this?
What I usually do is create a configuration section that holds the functionality to determine which connection string to use. Here's a basic example: ``` static ConfigurationSettings { static String ConnectionString { get { var result = "TESTCONNECTIONSTRING"; if (ConfigurationManager.ConnectionStrings["SOMEKEY"] != null) result = ConfigurationManager.ConnectionStrings["SOMEKEY"]; return result; } } ``` This way, I don't have to worry about how to connect to the system, and you can also override this behavior in your tests to accomplish what you want by adding a setter. The reason why I don't go the multiple config file route, is that I can't use the config files when running in a test suite (such as the NUnit testrunner).
Does your connection string come from a config file? Can you set up a matching config in your unit tests?
How would you go about swapping a connection string to access a test database for unit testing?
[ "", "asp.net", "sql", "vb.net", "unit-testing", "n-tier-architecture", "" ]
Currently, the XACML specification defines a protocol for request / response but leaves it up to interpretation as to how it can be integrated into an enterprise application. I believe that the value of XACML won't be realized unless there is the creation of a new open source project that attempts to develop/standardize around a set of common APIs. For those who are familiar with XACML, I would love to understand their first reactions to creation of such a project, whether they would be willing to contribute and what they believe an XACML API would look like?
Maybe I don't understand the question, but doesn't the SAML profile for XACML do what you want? It defines SOAP formats for authzDecisionQuery and response records, which should be all you need for the WSDL. I built one of these around Sun's interpreter for DOD/DISA (its on forge.mil), and a much faster version (not relesed yet) around a fully compiled implementation that directly transforms XACML into Java code. The main goal was readability, not speed, but its about ten times as fast. IMO XACML works but is absolutely terrible as a language for people to look at. I'm more interested in finding a problem-specific language for expressing XACML's semantics so that people can understand them. Java beats XACML for this hands down, but Java's pretty clumsy as a domain-specific language. Perhaps Groovy? PS: As our first shot at this we tried Attempto Controlled English (ACE). We quickly dropped that idea when we found ACE has nothing viable for expressing deeply nested conditionals (no parentheses or braces). And I'm not sure English was the right idea for this anyway, inspite of strong NSA interest in english-based policy languages.
Doesn't Sun's XACML Implementation give you a solid API? <http://sunxacml.sourceforge.net/> (The development is back on track and the site should be updated soon. Hava a look at the sunxacml-devl mailing list.
Designing an XACML API
[ "", "java", "identity", "saml", "cardspace", "xacml", "" ]
I often find myself needing a quick ( in terms of code ), lightweight ( in term of runtime, dependencies) persistence solution for simply a bunch of objects, mainly between application restarts. Usually I resort to some Java serialisation hack, but I wonder if there's something better out there. Have you used something similar? --- To make it clear, a JPA-based solution is *not lightweight* in my book, and a JDBC-based one is *not quick*. --- **Update**: I favour configuration-less frameworks over those which require configuration. For instance the Java serialisation solution requires a `implements Serializable` and it works. A JPA solution, either with annotations or with mapping files would be too heavyweight. **Update 2**: Just to make it clear, I don't think Serialisation is a hack. It's actually a very powerful mechanism, just that I'm using it in a hackish way when doing persistence.
I prefer [XStream](https://x-stream.github.io/), a simple library to serialize objects to XML and back again. Only one Jar needed, fast and very easy to use.
Try [iBatis](http://ibatis.apache.org/). I've used it recently on a project where I wanted a JDBC abstraction w/o ORM/spring/container/etc. Easy to setup, only a couple of small jars, and the config is very flexible. It won't give you the change-the-db-at-a-moments-notice flexibility of hibernate, et. al. but it is fairly lightweight.
Quick'n'dirty persistence
[ "", "java", "persistence", "" ]
Real simple question really. I need to read a Unicode text file in a Java program. I am used to using plain ASCII text with a BufferedReader FileReader combo which is obviously not working :( I know that I can read a String in the 'traditional' way using a Buffered Reader and then convert it using something like: ``` temp = new String(temp.getBytes(), "UTF-16"); ``` But is there a way to wrap the Reader in a 'Converter'? EDIT: the file starts with FF FE
you wouldn't wrap the Reader, instead you would wrap the stream using an InputStreamReader. You could then wrap that with your BufferedReader that you currently use ``` BufferedReader in = new BufferedReader(new InputStreamReader(stream, encoding)); ```
Check <https://docs.oracle.com/javase/1.5.0/docs/api/java/io/InputStreamReader.html>. I would read source file with something like: ``` Reader in = new InputStreamReader(new FileInputStream("file"), "UTF-8")); ```
Read unicode text files with java
[ "", "java", "string", "unicode", "ascii", "" ]
I want to import a one column text file into one of my sql tables. The file is just a list of swear words. I've written the following TSQL to do this ``` BULK INSERT SwearWords FROM 'c:\swears.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) ``` However it errors with unexapected end of file. The table im importing to is just an identity field followed by a nvarchar field that I want to insert the text into. It works fine if I add in the text file "1," to the beginning of eveyr line, I assume this is because SQL if looking for 2 fields. Is there any way around this? Thanks
You need to use FORMATFILE for this. See [BULK INSERT](http://msdn.microsoft.com/en-us/library/aa225968.aspx). > FORMATFILE [ = 'format\_file\_path' ] > > Specifies the full path of a format > file. A format file describes the data > file that contains stored responses > created using the bcp utility on the > same table or view. The format file > should be used in cases in which: > > ``` > * The data file contains greater or fewer columns than the table or view. > > * The columns are in a different order. > > * The column delimiters vary. > > * There are other changes in the data format. Format files are usually created by using the bcp utility and modified with a text editor as needed. For more information, see bcp Utility. > ``` For more detailed information, see [Using Format Files](http://msdn.microsoft.com/en-us/library/aa173859(SQL.80).aspx).
This is described in books on line for BULK INSERT under the KEEPIDENTITY argument. Here is what is says > KEEPIDENTITY > Specifies that the values for an identity column are present in the file imported. If KEEPIDENTITY is not given, the identity values for this column in the data file imported are ignored, and SQL Server automatically assigns unique values based on the seed and increment values specified during table creation. If the data file does not contain values for the identity column in the table or view, use a format file to specify that the identity column in the table or view should be skipped when importing data; SQL Server automatically assigns unique values for the column So, either use a format file or supply a dummy value and make sure not to use the KEEPIDENTITY argument
SQL Server Bulk Insert
[ "", "sql", "sql-server", "bulkinsert", "" ]
How can you identify in a function whether it has been invoked by an anchor tag href? The event is null in this case, so `event.target` and `event.srcElement` won't work. ***Code*** *HTML* ``` <a href="SomeFunction();">Href works here</a> ``` *JavaScript* ``` function SomeFunction () { // I need to get the anchor element that invoked this function } ```
What about ``` <a href="SomeFunction(this);">Href works here</a> function SomeFunction(context) { var callingElement = context; } ```
Following what @alex suggested, can you add a script to run in the page load to change the hrefs to be what you want (adding the 'this' reference)? Take the following script for example, this will change the href value for anchor tags with id set to SomeID or class set to SomeClass: ``` function changeLinks() { var all_links = document.getElementsByTagName("a"); for (var i=0; i<all_links.length; i++){ if (all_links[i].id == 'SomeID' || all_links[i].className == 'SomeClass') { all_links[i].href = 'SomeFunction(this);'; } } } ``` Hope this helps... **Edit**: Following your comment, you can try this: ``` var clickedAnchor = null; function setClickedAnchor(obj) { clickedAnchor = obj; } function changeLinks() { var all_links = document.getElementsByTagName("a"); for (var i=0; i<all_links.length; i++){ if (all_links[i].id == 'SomeID' || all_links[i].className == 'SomeClass') { all_links[i].href = 'setClickedAnchor(this);' + all_links[i].href; } } } ```
Identifying the anchor tag when href is called
[ "", "javascript", "dom-events", "" ]
In my application I have different roles and offcourse multiple pages. How do I secure webpages that may not be accessed by certain roles? Imagine group 1 has access to webpage a.aspx, b.aspx and c.aspx but not to webpage d.aspx. How do i secure that when a user of group 1 types in d.aspx he cannot view the page?
You have to add in web.config, which Role can get which page. ``` <location path="yourPage.aspx"> <system.web> <authorization> <deny users="?"/> <allow roles="Super Admin"/> <deny users="Admin"/> </authorization> </system.web> </location> ```
This is a big topic but I think what you want to look into is the ASP.NET Membership Provider. I would start here: [Examining ASP.NET 2.0's Membership, Roles, and Profile](https://web.archive.org/web/20211020202857/http://www.4guysfromrolla.com/articles/120705-1.aspx). > There's one thing messageboard > websites, eCommerce websites, social > network websites, and portal websites > share in common: they all provide user > accounts. These websites, and many > others, allow (or require) visitors to > create an account in order to utilize > certain functionality. For example, a > messageboard website, like > ASPMessageboard.com, allows anonymous > and authenticated visitors to view and > search the posts in the various > forums. However, in order to be able > to post a new thread or reply to a > message a visitor must have an account > and must log into the site.
How to secure webpages in ASP.Net with roles?
[ "", "c#", ".net", "asp.net", "authentication", "" ]
I have a string and I want to validate that string so that it must not contain certain characters like '/' '\' '&' ';' etc... How can I validate all that at once?
You can solve this with regular expressions! ``` mystring = "hello" yourstring = "bad & string" validRegEx = /^[^\\\/&]*$/ alert(mystring.match(validRegEx)) alert(yourstring.match(validRegEx)) ``` matching against the regex returns the string if it is ok, or null if its invalid! Explanation: * JavaScript RegEx Literals are delimited like strings, but with slashes (`/`'s) instead of quotes (`"`'s). * The first and last characters of the `validRegEx` cause it to match against the whole string, instead of just part, the carat anchors it to the beginning, and the dollar sign to the end. * The part between the brackets (`[` and `]`) are a character class, which matches any character so long as it's in the class. The first character inside that, a carat, means that the class is negated, to match the characters not mentioned in the character class. If it had been omited, the class would match the characters it specifies. + The next two sequences, `\\` and `\/` are backslash escaped because the backslash by itself would be an escape sequence for something else, and the forward slash would confuse the parser into thinking that it had reached the end of the regex, (exactly similar to escaping quotes in strings). + The ampersand (`&`) has no special meaning and is unescaped. * The remaining character, the *kleene star*, (`*`) means that whatever preceeded it should be matched zero or more times, so that the character class will eat as many characters that are not forward or backward slashes or ampersands, including none if it cant find any. If you wanted to make sure the matched string was non-empty, you can replace it with a plus (`+`).
I would use regular expressions. See [this guide](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Regular_Expressions) from Mozillla.org. This [article](http://james.padolsey.com/javascript/regular-expressions-in-javascript/) does also give a good introduction to regular expressions in JavaScript.
Javascript String pattern Validation
[ "", "javascript", "regex", "validation", "" ]
I am looking for a way to branch (tee) the input read from an istream (cin, in my case) out to a log file (clog/ofstream/etc), while still using the input for processing. I have read about boost::tee\_device, and it is very similar to my requirements. Unfortunately, it is implemented as an ostream, and thus solves a similar problem from "the other side of the pipe". I attempted to write an istream (adaptor) class which forwards the input functions on to a wrapped input stream (cin), and also sends what was read to the log file. This works fine for basic types which call operator>>(...) directly, however, I have run into issues with some more advanced usage of the input stream, for example, for operator>>(std::string), and the std::string getline function. Is there any easier way to do this (possibly via rdbuf() manipulation)? Thanks! Edit: I could change my code all over the place to something like: cin >> value; clog << value; -- but that would be a significant and ugly change. I would also prefer to have an easy way to turn logging off. Thus, I would like a way to model this as an istream "filter" and then simply replace all references to cin with this istream "logger". Ideal Solution: ``` class log_istream : public std::istream { public: log_istream( std::istream & in , std::ostream & out ); /* ... istream forwarding functions ... */ private: std::istream & in_; std::ostream & out_; }; int main() { log_istream logger( std::cin , std::ofstream("logfile.out") ); logger >> value; // this implies infile >> value and logfile << value getline(logger,my_string); // this also implies logfile.writeline(value) // etc } ``` etc.
Final Answer: ``` #ifndef TEE_ISTREAM_H_ #define TEE_ISTREAM_H_ /*****************************************************************************/ #include <boost/iostreams/tee.hpp> #include <boost/iostreams/invert.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/tr1/memory.hpp> #include <iostream> /*****************************************************************************/ namespace bio = boost::iostreams; /*****************************************************************************/ class tee_source : public bio::source { public: tee_source( std::istream & in, const std::string & filename ) : in_(in), log_file_(filename, std::ios::app), tee_(bio::tee(log_file_), 1) { } std::streamsize read(char* s, std::streamsize n) { return tee_.read(in_,s,n); } private: std::istream & in_; bio::file log_file_; bio::inverse< bio::tee_filter< bio::file > > tee_; }; /*****************************************************************************/ typedef bio::filtering_istream tee_istream_t; typedef std::tr1::shared_ptr< tee_istream_t > tee_istream_ptr_t; /*****************************************************************************/ inline tee_istream_ptr_t make_tee_istream( std::istream & in, const std::string & filename ) { return tee_istream_ptr_t( new tee_istream_t( tee_source( in , filename ), 0 ) ); } /*****************************************************************************/ #endif ```
Using Boost.IOStreams, you could define an input filter that logs what it reads into clog. Something like: (warning: untested code ahead) ``` class LoggingInputFilter : public multichar_input_filter { public: template<typename Source> std::streamsize read(Source& Src, char* S, std::streamsize N) { streamsize result = read(Src, S, N); if (result == -1){ return result; } if (std::clog.write(S, result)){ return result; } return -1; } }; ``` Chain it with std::cin: ``` LoggingInputFilter cin_logger; filtering_stream logged_cin(cin_logger); logged_cin.push(std::cin); ``` and use logged\_cin instead of std::cin Edit: Or operate at the streabuf level, so that your code still uses std::cin: ``` LoggingInputFilter cin_logger; filtering_streambuf logged_cin(cin_logger); logged_cin.push(std::cin.rdbuf()); std::cin.rdbuf(logged_cin); ```
Tee-ing input (cin) out to a log file (or clog)
[ "", "c++", "io", "stream", "" ]
Say I have two lists or arrays of strings. For example: list 1: "a", "c", "b", "d", "f", "e" list 2: "a", "d", "e", "f", "h" List 1 and list 2 are of arbitrary lengths. List 1 may contain elements not in list 2, and visa versa. I'd like to know when items in list 1 are found in list 2, and more specifically I want to know when an item in list 1 is found in list 2 but is found in a different order than which it is found in list 2, relative to the items in list 2. (Hopefully the example below clarifies this statement). For example, "a" is found in both lists and is the first item in both lists. So, everything is okay so far. "c" and "b" are found in only the 1st list and so can be ignored. "h" is found in only the 2nd list and can also therefore be ignored. "d" is found in both the 1st and 2nd list. It is found after "a" (the first item) in the original list. Even though the position within the 1st list is different form the second list, it is is okay because its relative order is the same within the two lists (the second match in common between lists). In the example above "f" and "e" are in the 'wrong' order in list 1, because "e" comes becomes before "f" in the 2nd list. So, I would like to report that "e" and "f" are in the wrong order in the first list. How would I do this? The solution should be in C#. Thank you!
``` string[] list1 = {"a", "c", "b", "d", "f", "e"}; string[] list2 = {"a", "d", "e", "f", "h"}; int i = 0; var list1a = list1.Intersect(list2).Select(l=> new { item = l, order= i++}); int j = 0; var list2a = list2.Intersect(list1).Select(l=> new { item = l, order= j++}); var r = from l1 in list1a join l2 in list2a on l1.order equals l2.order where l1.item != l2.item select new {result=string.Format("position {1} is item [{0}] on list1 but its [{2}] in list2", l1.item, l1.order, l2.item )}; r.Dump(); ``` ## result position 2 is item [f] on list1 but its [e] in list2 position 3 is item [e] on list1 but its [f] in list2
How about ``` list1.Intersect(list2).SequenceEquals(list2.Intersect(list1)) ```
Compare two lists or arrays of arbitrary length in C#; order is important
[ "", "c#", "arrays", "list", "compare", "" ]
Is there a way to get a ResultSet you obtain from running a JDBC query to be lazily-loaded? I want each row to be loaded as I request it and not beforehand.
### Short answer: Use `Statement.setFetchSize(1)` before calling `executeQuery()`. ### Long answer: This depends *very* much on which JDBC driver you are using. You might want to take a look at [this page](http://webmoli.com/2009/02/01/jdbc-performance-tuning-with-optimal-fetch-size/), which describes the behavior of MySQL, Oracle, SQL Server, and DB2. Major take-aways: * Each database (i.e. each JDBC driver) has its own default behavior. * Some drivers will respect `setFetchSize()` without any caveats, whereas others require some "help". MySQL is an especially strange case. See [this article](http://benjchristensen.wordpress.com/2008/05/27/mysql-jdbc-memory-usage-on-large-resultset/). It sounds like if you call `setFetchSize(Integer.MIN_VALUE)`, then it will download the rows one at a time, but it's not perfectly clear. Another example: [here's the documentation](http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor) for the PostgreSQL behavior. If auto-commit is turned on, then the ResultSet will fetch all the rows at once, but if it's off, then you can use `setFetchSize()` as expected. One last thing to keep in mind: these JDBC driver settings only affect what happens on the client side. The server may still load the entire result set into memory, but you can control how the client *downloads* the results.
Could you not achieve this by setting the fetch size for your Statement to 1? If you only fetch 1 row at a time each row shouldn't be loaded until you called next() on the ResultSet. e.g. ``` Statement statement = connection.createStatement(); statement.setFetchSize(1); ResultSet resultSet = statement.executeQuery("SELECT ....."); while (resultSet.next()) { // process results. each call to next() should fetch the next row } ```
Java JDBC Lazy-Loaded ResultSet
[ "", "java", "jdbc", "lazy-loading", "resultset", "" ]
This question probably highlights a lack of understanding of networking principals on my part, rather than a programming issue. I'm doing a lookup on a hostname using ``` Dns.GetHostEntry ``` This returns an IPHostEntry to me, which has an AddressList property which is an array of IPAddress. I always thought there is a 1 to 1 mapping between hostname and IP, but I'm finding that in some cases I get back several IPAddress(es) for the same host. This is a surprise to me. Which part of domain name resolution do I not understand?
Any system can have multiple network interfaces and internet addresses, yet only have one name. The forward mapping from name to address will return all of the addresses mapped to a particular name. We used to do this with our file servers so that hosts wouldn't have to traverse a network boundary when accessing files and to spread the load out across the various NICs. The file servers would be homed on each of our various subnets, having multiple interface cards, each with a different subnet address, but the same name. The DNS servers on campus are still set up this way. Additionally, you may have a name that maps to more than one system, providing some level of load balancing via DNS.
The mappings between physical network interfaces, DNS names and IP addresses is practically arbitrary. However you should distinguish between network interfaces (typically Ethernet adapters, Wifi adapters, Bluetooth network devices etc.) and the DNS side of things, which only deals with names and IP addresses (not physical interfaces). Here are some facts that you can mix and match: * a single network card can have 1 or many IP addresses. * a single DNS name can be resolved to 1 or many IP addresses. * a single IP address can (and will usually) identify a single machine * mulitple DNS names can be mapped to a single IP address Consider hosting providers: They will have many DNS names pointing to the same - shared - server. That server might for reasons of reliablilty be equipped with multiple network cards, each with several IP addresses. For PCs you will usually get more than one IP address if you query by hostname, because nowadays you typically have at least two (wifi and ethernet) adapters with their individual (mostly single) IP address. In load-balancing scenarios however all sorts of clever mappings and redirections (virtual IP addresses and the like) can occur. Both DNS and IP protocols are very flexible, however this of course does not necessarily make them easier to understand.
Dns.GetHostEntry returns multiple IP addresses
[ "", "c#", "networking", "dns", "" ]
consider this simple and pointless code. ``` #include <iostream> struct A { template<int N> void test() { std::cout << N << std::endl; } }; int main() { A a; a.test<1>(); } ``` It is a very simple example of a function template. What if however, I wanted to replace `A::test` with an overloaded `operator()` to make it a functor? ``` #include <iostream> struct A { template<int N> void operator()() { std::cout << N << std::endl; } }; int main() { A a; a<1>(); // <-- error, how do I do this? } ``` Certainly if the `operator()` took parameters which were dependent on the template, the compiler could possibly deduce the template. But I just can't figure out the proper syntax to specify template parameters with a parameterless functor. **Is there a proper way to do this?** Obviously, this code would work since it bypasses the functor syntax: ``` a.operator()<1>(); ``` but that kinda defeats the purpose of it being a functor :-P.
There's not another "direct" way I know other than the: ``` a.operator()<1>(); ``` syntax. If you're open to changing the code, moving the template parameter to the class would work, or using a (boost|tr1)::bind to make a (boost|tr1)::function object.
You can only call ``` a.operator()<1>(); ``` but that would not be using a functor. Functors need a non template operator(), as they must be able to be called as *varname()* and that won't work with your code. To make it a real functor change your code a template class (functors are classes): ``` #include <iostream> template<int N> struct A { void operator()() { std::cout << N << std::endl; } }; int main() { A<1> a; a(); } ```
c++ functor and function templates
[ "", "c++", "templates", "functor", "" ]
According to the [MSDN Documentation for ThreadState](http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx), the Stopped state can be entered by one of two ways: the thread exiting, or the thread being aborted. Is there some mechanism for telling whether a thread has entered the Stopped state by exiting normally? Thanks!
A thread can reach the Stopped state in several ways: * It's main method can exit without any errors. * An uncaught exception on the thread can terminate it. * Another thread could call Thread.Abort(), which will cause a ThreadAbortException to be thrown on that thread. I don't know if you are looking to differentiate between all three states, but if all you are really interested in is whether the thread completed successfully, I would suggest using a shared data structure of some kind (a synchronized dictionary would work) that the main loop of a thread updates as it terminates. You can use the ThreadName property as the key in this shared dictionary. Other threads that are interested in termination state, could read from this dictionary to determine the final status of the thread. After looking a bit more at the [MSDN documentation](http://msdn.microsoft.com/en-us/library/d6122999.aspx), you should be able to differentiate an externally aborted thread using the `ThreadState` property. This should be set to `ThreadState.Aborted` when a thread responds to the Abort() call. However, unless you have control of the thread code that is run, I don't think that you can differentiate between a thread that just exited its main method, vs one that terminated with an exception. Keep in mind however, if you control the code that *starts* the thread, you can always substitute your own method that internally calls the code that runs the main thread logic and inject exception detection (as I described above) there.
Is the thread that you want to monitor your code? If so, you could wrap the whole thing in a class, and either raise an event when you finish or use a WaitHandle (I would use a ManualResetEvent) to signal completion. -- completely encapsulate the background logic. You can also use this encapsulation to capture an exception and then raise an event. Something like this: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace BackgroundWorker { public class BackgroundWorker { /// /// Raised when the task completes (you could enhance this event to return state in the event args) /// public event EventHandler TaskCompleted; /// /// Raised if an unhandled exception is thrown by the background worker /// public event EventHandler BackgroundError; private ThreadStart BackgroundTask; private readonly ManualResetEvent WaitEvent = new ManualResetEvent(false); /// /// ThreadStart is the delegate that you want to run on your background thread. /// /// public BackgroundWorker(ThreadStart backgroundTask) { this.BackgroundTask = backgroundTask; } private Thread BackgroundThread; /// /// Starts the background task /// public void Start() { this.BackgroundThread = new Thread(this.ThreadTask); this.BackgroundThread.Start(); } private void ThreadTask() { // the task that actually runs on the thread try { this.BackgroundTask(); // completed only fires on successful completion this.OnTaskCompleted(); } catch (Exception e) { this.OnError(e); } finally { // signal thread exit (unblock the wait method) this.WaitEvent.Set(); } } private void OnTaskCompleted() { if (this.TaskCompleted != null) this.TaskCompleted(this, EventArgs.Empty); } private void OnError(Exception e) { if (this.BackgroundError != null) this.BackgroundError(this, new BackgroundWorkerErrorEventArgs(e)); } /// /// Blocks until the task either completes or errrors out /// returns false if the wait timed out. /// /// Timeout in milliseconds, -1 for infinite /// public bool Wait(int timeout) { return this.WaitEvent.WaitOne(timeout); } } public class BackgroundWorkerErrorEventArgs : System.EventArgs { public BackgroundWorkerErrorEventArgs(Exception error) { this.Error = error; } public Exception Error; } } ``` Note: you need some code to keep Start from being called twice, and you might want to add a state property for passing state to your thread. Here's a console app that demonstrates the use of this class: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BackgroundWorker { class Program { static void Main(string[] args) { Console.WriteLine("Test 1"); BackgroundWorker worker = new BackgroundWorker(BackgroundWork); worker.TaskCompleted += new EventHandler(worker_TaskCompleted); worker.BackgroundError += new EventHandler(worker_BackgroundError); worker.Start(); worker.Wait(-1); Console.WriteLine("Test 2"); Console.WriteLine(); // error case worker = new BackgroundWorker(BackgroundWorkWithError); worker.TaskCompleted += new EventHandler(worker_TaskCompleted); worker.BackgroundError += new EventHandler(worker_BackgroundError); worker.Start(); worker.Wait(-1); Console.ReadLine(); } static void worker_BackgroundError(object sender, BackgroundWorkerErrorEventArgs e) { Console.WriteLine("Exception: " + e.Error.Message); } private static void BackgroundWorkWithError() { throw new Exception("Foo"); } static void worker_TaskCompleted(object sender, EventArgs e) { Console.WriteLine("Completed"); } private static void BackgroundWork() { Console.WriteLine("Hello!"); } } } ```
How to tell if a thread has exited successfully?
[ "", "c#", "multithreading", "thread-state", "" ]
I have the following piece of HTML: ``` <div><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit <strong id="s">esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</strong></p></div> ``` The width of the DIV is fixed at 600px using CSS. Now, I want to find the offset().left of the `<strong>` element. So I did: ``` alert( $("#s").offset().left ); ``` **However this does not seem to produce the right value, as I can clearly see the strong element is seen half way through the 600px width, but the offset value I get is only 8px.** How do I find the offset().left value of the inline strong element?
Here's what's happening: ![Diagram](https://i.stack.imgur.com/URuyF.png) Since the inline element spans multiple lines jQuery will give you the left-most position of that element, not the offset of the beginning of the element. To get around this, try this plugin: ``` jQuery.fn.inlineOffset = function() { var el = $('<i/>').css('display','inline').insertBefore(this[0]); var pos = el.offset(); el.remove(); return pos; }; ``` The plugin will create a temporary element and insert it just before the target element - it will then return the offset of that temporary element. Example usage: ``` alert( jQuery('strong').inlineOffset().left ); ```
The reason you are getting the result of 8px is because even though the element starts in half way through your container, since there's a line break its left edge is 8px in from the page. I have one of those feelings that there's probably a much better way to do it than this, but the first thing I could think of to work around this problem is to insert another element right before the `<strong>` and check its position: ``` $("<span><span>").insertBefore($('#s')).offset(); ```
Left offset of an inline element using jQuery
[ "", "javascript", "jquery", "offset", "" ]
I have a doubt in licensing. I am using C# application. Scenario: User gets the license for the application through mail in the form of file. He/She stores the license file on the Desktop. Later, he/she chooses the license and click register. Now the application is registered (Licensed). After some days, if user deletes the license file from Desktop. The application will stop working since there is no file. I want to store the license details somewhere in registry or file (secret path). But what if that user account doesn't have enough permission to read/write registry or file. Which is the good way? Do you guys know any other method? I am novice in this area. So please help me. Thanks in advance.
All application data should be stored in the %appdata% directory. Since you specified C#, here's the code to get the folder: ``` Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); ``` This will output to the following location: In XP: C:/Documents and Settings/*username*/Application Data/ In Vista: C:/Users/*username*/AppData/Roaming I'd recommend you create a folder in that directory for your application and copy there.
Microsoft has some suggestions for storage locations in the [Windows Vista: Application Certification and Compatibility document](http://blogs.msdn.com/amitava/archive/2007/07/16/certified-for-windows-vista-logo-test-case-faq-test-case-15.aspx). > So, if it [your program] is ever changing shared DATA (not CODE) then it [the data] should logically go in to ProgramData folder. If it is individual DATA then it can go to the user profile. We use a license file and store it in the ProgramData\CompanyName folder. But our licenses are on a per machine basis, not a per user. By default, this folder is hidden in Windows, but is not protected by UAC.
Storing license details
[ "", "c#", "licensing", "" ]
When I run the code below when $entry = miami.com, I get the following error message: ``` SELECT COUNT(*) FROM #&*+ WHERE `site` LIKE 'miami.com':You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 ``` It looks like I'm not correctly defining $table. Any ideas how I could do that? Thanks in advance, John ``` $result = mysql_query("SHOW TABLES FROM feather") or die(mysql_error()); while(list($table)= mysql_fetch_row($result)) { $sqlA = "SELECT COUNT(*) FROM $table WHERE `site` LIKE '$entry'"; $resA = mysql_query($sqlA) or die("$sqlA:".mysql_error()); list($isThere) = mysql_fetch_row($resA); if ($isThere) { $table_list[] = $table; } } ```
if it were me debugging that i would see what ``` print_r(mysql_fetch_row($result)); ``` outputs
I think you are using the [list-language construct](http://se.php.net/list) incorrectly: > **Description** > > ``` > void list ( mixed $varname [, mixed $... ] ) > ``` > > Like [array()](http://se.php.net/manual/en/function.array.php), this is not really a function, but a language construct. **list()** is used to > assign a list of variables in one operation. Example: ``` $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.\n"; ``` Now, what you are trying to do is to fetch dynamic table-names (it seems). You do not need to use the list-function, since you can [access the result as an array](http://se.php.net/manual/en/function.mysql-fetch-assoc.php) (you can define the appropriate indexes of the array that you are interested in and only assign them, but I think array access is much clearer): ``` while($row = mysql_fetch_assoc($result)) { $sqlA = "SELECT COUNT(*) FROM ${row['table']} WHERE `site` LIKE '$entry'"; [...] } ``` I am a bit curious though, do ALL the tables in your database *feather* have a column named *site*? Otherwise this query will fail, no matter how you format or refactor your code.
PHP - list() query not working
[ "", "php", "mysql", "" ]
What I am trying to do: I have hundreds of servers with very large log files spread out at dozens of different clients. I am creating nice python scripts to parse the logs in different ways and would like to aggregate the data I am collecting from all of the different servers. I would also like to keep the changing scripts centralized. The idea is to have a harness that can connect to each of the servers, scp the script to the servers, run the process with pexpect or something similar and either scp the resulting data back in separate files to be aggregated or (preferentially, I think) stream the data and aggregate it on the fly. I do not have keys set up (nor do I want to set them up) but I do have a database with connection information, logins, passwords and the like. My question: this seems like it is probably a solved problem and I am wondering if someone knows of something that does this kind of thing or if there is a solid and proven way of doing this...
Looks like [hadoop](http://hadoop.apache.org/core/) is your answer <http://www.michael-noll.com/wiki/Writing_An_Hadoop_MapReduce_Program_In_Python> or Pyro is also good but I am not sure if you can automatically distribute scripts. <http://pyro.sourceforge.net/features.html>
Parallel Python provides some functionality for distributed computing and communication: <http://www.parallelpython.com/>
What is the best approach for creating an agent framework in python for flexible script distribution and data collection
[ "", "python", "" ]
I have a tiny *(rikiki)* problem in SWT ... I am making a small class extending **org.eclipse.swt.widgets.Composite** and which is supposed to be nested in an RCP app ... In this small class I have widgets which are supposed to react to mouse or keyboard event **BUT** I need to use modifier keys (*Shift/Ctrl/Alt/...*) to alter my coponents behaviours when I click them or send them keyboard event ... The probleme is that I cannot just listen for *mod-key* striking because my user can strike it out from my component and then click it... I cannot use a display filter to avoid disturbing the shell that nests my component.(*but may be it will be my last solution in case there is no other solution*) I cannot make a transparent component that reads and dispatch events to all of my components because it would, at the most, be as large as my component and wont get *mod-key* strikes from the shell out my component (or even out from the shell) ... Do anyone have any idea?
More or less it is like ``` myComponent.add<Any>Listener(new <Appropriate>Listener(){ @Override public void <AppropriateMethod>(like KeyPress)>(<Appropriate>Event e) { int stateMask=e.stateMask; if((stateMask & SWT.ALT)==SWT.ALT){ <Do_appropriate_actions>; } if((stateMask & SWT.CTRL)==SWT.CTRL){ <Do_another_appropriate_actions>; } if((stateMask & SWT.SHIFT)==SWT.SHIFT){ <Do_an_even_more_appropriate_actions_cause_you_are_kind_of_a_code_roxxor_!>; } }; }; ``` Hope it helps ...
Try something along these lines to capture all keys and save them for later: ``` Display.getDefault().addFilter( SWT.KeyDown, new Listener() { public void handleEvent( Event passedEvent ) { //Listen for and store as static var last pressed keycode System.out.println( "Key Event: " + passedEvent ); } } ); ```
Modifier Key state
[ "", "java", "keyboard", "swt", "modifier", "" ]
How can I Handle MDIParent Form events in childs forms? for example in Parent Form I Have a option "search on child grid" and when that button got clicked, in the child form one row on grid get focused. Im using C# 3.5 Windows Forms Application Thanks in Advance
I see two different way that I would choose between for this problem. If you could think of hosting the command in a [`MenuStrip`](http://msdn.microsoft.com/en-us/library/system.windows.forms.menustrip.aspx) instead, and it is the same child form that lives in several instances in the MDI application, you could add the command(s) to a `MenuStrip` control in the child form instead. These menu commands will be automatically merged with the commands in the parent form, but any click events will be carried out in the active child form. You can control where and how menu commands from the child form merges with the commands in the parent form through the [`MergeAction`](http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.mergeaction.aspx) and [`MergeIndex`](http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.mergeindex.aspx) properties. If using this approach you should probably set the `Visible` property of the `MenuStrip` in the child form to `false` to prevent it from taking up unnecessary space on the form. The second option that I would suggest is to create an interface for defining the search functionality, implement that interface in the child forms that support it, and use the [`MdiChildActivate`](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.mdichildactivate.aspx) event of the MDI parent form to enable or disable the search function based on whether the current child supports it or not. Simplified code sample of the second approach: ``` interface IGridSearch { void PerformSearch(string criteria); } public partial class MdiChildUI : Form, IGridSearch { public MdiChildUI() { InitializeComponent(); } public void PerformSearch(string criteria) { // peform the search } } public partial class MdiParentUI : Form { public MdiParentUI() { InitializeComponent(); } private void MdiParentUI_MdiChildActivate(object sender, EventArgs e) { SetControlStates(); } private void SetControlStates() { _searchCommand.Enabled = (this.ActiveMdiChild is IGridSearch); } private void _searchCommand_Click(object sender, EventArgs e) { IGridSearch child = (this.ActiveMdiChild as IGridSearch); if (child != null) { child.PerformSearch("whatever to search for"); } else { MessageBox.Show("Can't search in the active form"); } } } ```
It's not too complicated: ``` public partial class Form1 : Form { // other stuff... // e.g. some button's click event handler private void addChild_Click(object sender, EventArgs e) { Form2 child = new Form2(); child.MdiParent = this; this.SomeEvent += child.SomeMethod(); // other init stuff... } } ``` Just make sure the signature of the handler method on the child Forms matches the signature of the event handler delegate of the parent. One thing to note is if you want only the active child form to respond to the event. In that case you can create a helper [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx) like this ``` public static bool IsActiveMDIChild(this Form child) { Form mdiParent = Form.ActiveForm; Form activeChild = mdiParent.ActiveMdiChild; return child == activeChild; } ``` Then add code like this to the SomeMethod() handler: ``` public bool SomeMethod(*/ signature here /*) { if(!this.IsActiveMDIChild()) return; //do stuff normally, we're in the active child form } ```
Events in MDIParents Forms and Childs
[ "", "c#", ".net", "winforms", "event-handling", "" ]
I have a WPF xaml file describing a section of a GUI and I'd like the enabling/disabling of a particular control to be dependent on two others. The code looks something like this at the moment: ``` <ComboBox Name="MyComboBox" IsEnabled="{Binding ElementName=SomeCheckBox, Path=IsChecked}"/> ``` But I'd like it to be dependant on another checkbox as well so something like: ``` <ComboBox Name="MyComboBox" IsEnabled="{Binding ElementName=SomeCheckBox&AnotherCheckbox, Path=IsChecked}"/> ``` What's the best way to go about that? I can't help feeling I'm missing something obvious or going about this the wrong way?
I believe you may have to use a MultiBinding with a MultiValueConverter. See here: <http://www.developingfor.net/wpf/multibinding-in-wpf.html> Here is a directly related example: <http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5b9cd042-cacb-4aaa-9e17-2d615c44ee22>
You can use a [`MultiBinding`](http://msdn.microsoft.com/en-us/library/system.windows.data.multibinding(v=vs.110).aspx) with a converter which implements [`IMultiValueConverter`](http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter(v=vs.110).aspx). Just to give an answer you can (almost) copy&paste: Static resource needed: ``` <converterNamespace:BooleanAndConverter x:Key="booleanAndConverter" /> ``` The ComboBox: ``` <ComboBox Name="MyComboBox"> <ComboBox.IsEnabled> <MultiBinding Converter="{StaticResource booleanAndConverter}"> <Binding ElementName="SomeCheckBox" Path="IsChecked" /> <Binding ElementName="AnotherCheckbox" Path="IsChecked" /> </MultiBinding> </ComboBox.IsEnabled> </ComboBox> ``` The code for the converter: ``` namespace ConverterNamespace { public class BooleanAndConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { foreach (object value in values) { if ((value is bool) && (bool)value == false) { return false; } } return true; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException("BooleanAndConverter is a OneWay converter."); } } } ```
C# WPF IsEnabled using multiple bindings?
[ "", "c#", "wpf", "binding", "combobox", "isenabled", "" ]
``` _TCHAR* strGroupName = NULL; const _TCHAR* strTempName = NULL; //Assign some value to strTempName strGroupName = _tcschr(strTempName, 92) //C2440 ``` I get an error at the above line while compiling this code in VS2008. In VC6 it compiles fine. > Error C2440: '=' : cannot convert from > 'const wchar\_t \*' to '\_TCHAR \*' What seems to be the problem and how do I fix it?
Try casting it as ``` strGroupName = (_TCHAR*)_tcschr(strTempName, 92); ``` Seems to me that VS2008 got a little more strict on type casts, and won't automatically do them in some cases.
``` strGroupName = const_cast<_TCHAR*>( _tcschr(strTempName, 92)); ``` This is because the variant of the function you're using has a const \_TCHAR\* as input and returns a const \_TCHAR\*. Another variant would be to have strTempName declared as \_TCHAR\*, and not as const \_TCHAR\*. In this case, the variant function having a \_TCHAR\* parameter and returning a \_TCHAR\* value is used.
Cannot convert from 'const wchar_t *' to '_TCHAR *'
[ "", "c++", "visual-studio-2008", "porting", "visual-c++-6", "" ]
**Problem:** I have two arrays that can possibly be different lengths. I need to iterate through both arrays and find similarities, additions, and deletions. What's the fastest and most efficient way to accomplish this in C#? *Edit:* The arrays are pre-sorted and they can contain anywhere between 50-100 items. Also, there aren't any constraints on speed and/or memory usage (however, no one likes a memory hog;) --- **For example:** ``` String[] Foo_Old = {"test1", "test2", "test3"}; String[] Foo_New = {"test1", "test2", "test4", "test5"}; ``` AND ``` String[] Bar_Old = {"test1", "test2", "test4"}; String[] Bar_New = {"test1", "test3"}; ``` --- **Differences:** *(with respect to the Foo\_New array)* ``` [Same] "test1" [Same] "test2" [Removed] "test3" [Added] "test4" [Added] "test5" ``` *(with respect to the Bar\_New array)* ``` [Same] "test1" [Removed] "test2" [Removed] "test4" [Added] "test3" ```
You can use [Except](http://msdn.microsoft.com/en-us/library/bb919392.aspx) and [Intersect](http://msdn.microsoft.com/en-us/library/bb919779.aspx) ... ``` var Foo_Old = new[] { "test1", "test2", "test3" }; var Foo_New = new[] { "test1", "test2", "test4", "test5" }; var diff = Foo_New.Except( Foo_Old ); var inter = Foo_New.Intersect( Foo_Old ); var rem = Foo_Old.Except(Foo_New); foreach (var s in diff) { Console.WriteLine("Added " + s); } foreach (var s in inter) { Console.WriteLine("Same " + s); } foreach (var s in rem) { Console.WriteLine("Removed " + s); } ```
I went ahead and hand-coded one and use the example in the accepted answer, and the hand-coded one performs a little better. I handled outputting my strings a little differently. Other factors to consider include whether the Except make a sorted copy of the array (since it cannot assume it's sorted) or whether it makes some kind of hash or a linear search (it's actually restricted to IEnumerable - for very large arrays which are already sorted, this could be a problem). You could change mine to compare IEnumerable (which is more general) instead of IComparable[]. ``` static void ArrayCompare(IComparable[] Old, IComparable[] New) { int lpOld = 0; int lpNew = 0; int OldLength = Old.Length; int NewLength = New.Length; while (lpOld < OldLength || lpNew < NewLength) { int compare; if (lpOld >= OldLength) compare = 1; else if (lpNew >= NewLength) compare = -1; else compare = Old[lpOld].CompareTo(New[lpNew]); if (compare < 0) { Debug.WriteLine(string.Format("[Removed] {0}", Old[lpOld].ToString())); lpOld++; } else if (compare > 0) { Debug.WriteLine(string.Format("[Added] {0}", New[lpNew].ToString())); lpNew++; } else { Debug.WriteLine(string.Format("[Same] {0}", Old[lpOld].ToString())); lpOld++; lpNew++; } } } static void ArrayCompare2(IComparable[] Old, IComparable[] New) { var diff = New.Except( Old ); var inter = New.Intersect( Old ); var rem = Old.Except(New); foreach (var s in diff) { Debug.WriteLine("Added " + s); } foreach (var s in inter) { Debug.WriteLine("Same " + s); } foreach (var s in rem) { Debug.WriteLine("Removed " + s); } } static void Main(string[] args) { String[] Foo_Old = {"test1", "test2", "test3"}; String[] Foo_New = {"test1", "test2", "test4", "test5"}; String[] Bar_Old = {"test1", "test2", "test4"}; String[] Bar_New = {"test1", "test3"}; Stopwatch w1 = new Stopwatch(); w1.Start(); for (int lp = 0; lp < 10000; lp++) { ArrayCompare(Foo_Old, Foo_New); ArrayCompare(Bar_Old, Bar_New); } w1.Stop(); Stopwatch w2 = new Stopwatch(); w2.Start(); for (int lp = 0; lp < 10000; lp++) { ArrayCompare2(Foo_Old, Foo_New); ArrayCompare2(Bar_Old, Bar_New); } w2.Stop(); Debug.WriteLine(w1.Elapsed.ToString()); Debug.WriteLine(w2.Elapsed.ToString()); } ```
Compare Two Arrays Of Different Lengths and Show Differences
[ "", "c#", "arrays", "" ]
I need to transfer data from a PHP script on my local server to a remote API (also written in PHP) on my hosting server. It is basically a primitive version control system, and I use both HTTP GET and HTTP POST to transfer files and strings. I would like the connection encrypted, but my (shared) web host tells me I can't use SSL because I can't get a dedicated IP address--and even if I could, I don't want to spend any more money on it. My question is: Is there a better way to do this? Some possibilities I have considered are using the mcrypt extension in PHP to encrypt data at one end and decrypt at the other. I also thought of TLS, which--as I understand--can be used to create a secure connection without certificates? EDIT: Please see [this question](https://stackoverflow.com/questions/1036872/encrypted-and-signed-mime-messages-using-rfc-1847) as a follow up regarding OpenPGP, GnuPG and transfer using MIME.
What is the problem with just using a simple symmetric encryption (for example with the help of mcrypt) or something with a public/private key if you really need the signing and all? Another possible solution could be to use installed system tools and put all your files in a password protected zip file. (php function call "system()")
You can create a self signed certificate to use for SSL. There's no reason for you to be paying someone like verisign for a certificate if you are the only one who has to trust the certificate. You also might want to consider the following. A shared hosting service such as Dreamhost (which is what I use) will cost you $10 a month for hosting, $4 a month for the static IP, and $15 a year (1.25 a month) for a real SSL cert. So that's only about $15 a month for a shared hosting account with a real certificate signed by a real CA. I don't know who you are currently with, or what they are charging you, but if you are in anyway serious about this project, $15 a month isn't that much money to put towards it.
Transfering encrypted data server to server, between 2 PHP scripts
[ "", "php", "http", "encryption", "ssl", "mcrypt", "" ]
this query give me 'Incorrect syntax near the keyword 'select'.' look please below bold character area. ``` declare @date1 smalldatetime, @date2 smalldatetime, @page nvarchar(100) ,@sum int select @date1='2009-06-06',@date2='2009-06-13',@page='Tüm Sayfalar' set @sum = select Sum(t.[VISITINGCOUNT]) from ( select count(page) as [VISITINGCOUNT], cast(DATENAME ( year ,DATE)+'-'+DATENAME (month ,DATE)+ '-'+DATENAME (day ,DATE) as smalldatetime) as [DATE] from scr_StatisticaLog where Date between @date1 and @date2 and (Page=@page or @page='Tüm Sayfalar') and ProcessType='PageView' GROUP BY cast(DATENAME ( year ,DATE)+ '-'+DATENAME (month ,DATE)+ '-'+DATENAME (day ,DATE) as smalldatetime)) as t select 100*(t.[VISITINGCOUNT]/@sum),t.[DATE] from ( select count(page) as [VISITINGCOUNT], cast(DATENAME ( year ,DATE)+'-'+DATENAME (month ,DATE)+ '-'+DATENAME (day ,DATE) as smalldatetime) as [DATE] from scr_StatisticaLog where Date between @date1 and @date2 and (Page=@page or @page='Tüm Sayfalar') and ProcessType='PageView' GROUP BY cast(DATENAME ( year ,DATE)+ '-'+DATENAME (month ,DATE)+ '-'+DATENAME (day ,DATE) as smalldatetime)) as t ```
I don't believe you can have `SET @var = SELECT ...` Try the following instead: ``` SELECT @sum = Sum(t.[VISITINGCOUNT]) from ... ``` I would also like to say that seeing as all you are doing is SUM-ing a single column in your sub-query there is no point in doing the group by, or returning the second column. You are basically counting the number of records in various groups, then adding all the groups together. Far quicker just to count the total number of pages in total if that is all you need. The following would be much simpler: ``` SELECT @sum = COUNT(page) FROM scr_StatisticaLog WHERE Date BETWEEN @date1 AND @date2 AND (Page=@page OR @page='Tüm Sayfalar') AND ProcessType='PageView' ```
Try changing ``` set @sum = select Sum(t.[VISITINGCOUNT]) from ``` to ``` select @sum = Sum(t.[VISITINGCOUNT]) from ``` Haven't tested it works though, just that it parses correctly without errors.
How to improve 'Incorrect syntax near the keyword 'select'.'
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
[update: I am using MySQL 4.1.25 ] I think this must be a simple thing to do, but I'm a SQL noob and need some help. I have a lookup table that is something like: ## lookup\_table key1, value1 key2, value2 key3, value3 ... keyN, valueN Then I have another table that has a random list of the keys (with repeats) in one column and I need to add the associated values in the corresponding column. For example, the second table might be: ## second\_table key3, ? key1, ? key1, ? key40, ? I need to replace the ?s in `second_table` with the values from `lookup_table` as follows: ## second\_table (updated) key3, value3 key1, value1 key1, value1 key40, value40 This seems like something that a simple SQL query should address. Any suggestions?
I much prefer the following syntax when updating with a join (instead of doing a subquery). It allows you to see results before you update them and know the query's right. ``` select st.key, lt.value --update st set value = lt.value from second_table st inner join lookup_table lt on st.key = lt.key ``` Note that when you're ready to update, select everything from `update` on down. **Update**: Thanks to tekBlues, I've found out that the above works on SQL Server and Oracle, at the very least. MySQL has a bit different syntax: ``` update second_table st inner join lookup_table lt on st.key = lt.key set st.value = lt.value ``` Those are the big RDBMS's, so hopefully one of those is helpful.
Along with the other answers, you could also accomplish this with a join... ``` UPDATE second_table SET value = L.value FROM second_table S join lookup_table L on S.key = L.key ```
SQL query: how do I change a value according to a lookup table?
[ "", "sql", "" ]
I am working on a project which generates an assembly. I just noticed that an additional assembly \*.XmlSerializers.dll is being generated. Why this file is auto generated and what it is used for?
In [.NET](http://en.wikipedia.org/wiki/.NET_Framework) implementation, the XmlSerializer generates a temporary assembly for serializing/deserializing your classes (for performance reasons). It can either be generated on the fly (but it takes time on every execution), or it can be pregenerated during compilation and saved in this assembly you are asking about. You can change this behaviour in project options (tab *Compile* -> *Advanced Compile Options* -> *Generate serialization assemblies*, *Auto* or *On*, respectively). The corresponding element in the project file is *GenerateSerializationAssemblies*, for example, `<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>`.
FYI. The exact steps to stop the XmlSerializers.dll from being auto-generated are: 1. In VS, right-click your project file and select "Properties" 2. Click the "Build" tab 3. Change the "Generate serialization assembly" dropdown from "Auto" to "Off" 4. Rebuild and it will be gone
What is MyAssembly.XmlSerializers.dll generated for?
[ "", "c#", "visual-studio-2008", "xml-serialization", "" ]
How can I do simple thing like manipulate image programmatically ? ( with C++ I guess .. ) jpgs/png/gif .....
check out BOOST , it has a simple Image Processing Library called GIL. It also has extensions to import common formats. <http://www.boost.org/doc/libs/1_39_0/libs/gil/doc/index.html>
Using .NET you have two options: 1. GDI+ from System.Drawing namespace (Bitmap class) 2. WPF engine wich can do a lot of things If you want low level processing you can use unsafe code and pointers. A Bitmap or Image is just a big array of bytes. You need to learn: * what is a stride (extra padding bytes after each row of pixels) * how to compute the next row or a specific pixel location using width, height, stride * the image formats RGB, ARGB, white&black * basic image processing functions (luminosity, midtone, contrast, color detection, edge detection, matrix convulsion) * 3D vectorial representation of a RGB color
How to get into image manipulation programming?
[ "", "c++", "image-processing", "image-manipulation", "" ]
I am trying to enable communication between Javascript and Flash via ExternalInterface across domains. The Javascript works great when it is located on the same domain as the SWF. But in one case, the HTML resides on domain A, the javascript and the flash both reside on domain B. I have done all of the following: * The embed tag has `allowScriptAccess="always"` (and the object has that as a param) * My SWF file's actionscipt has `Security.allowDomain("*")` * My SWF also calls `Security.allowInsecureDomain("*")` * Both domain A and domain B have a `/crossdomain.xml` file which has `allow-access-from domain="*"` The SWF is able to call javascript on the page, but when I use Javascript to call functions exposed by ExternalInterface, I get > Error calling method on NPObject! [plugin exception: Error in Actionscript. Use a try/catch block to find error.] This is ActionScript 2 so `ExternalInterface.marshallExceptions` is not available.
You should only need two things for this to work: 1) `allowscriptaccess=always` will allow your swf to send stuff out to the page 2) `System.security.allowDomain("yourhtmldomain.com");` Note that it's `System.security.allowDomain()` in AS2 - it's not the same as AS3 or what you have written above. number 2 above allows the html page on domainA to call things in the swf on domainB. The domain your js is hosted on won't matter here, since the browser embeds it on domainA, the script is executed in domainA. crossdomain.xml is mainly only for loading remote files, which you aren't doing, so you can remove that if you like. (and you probably don't want to have a crossdomain.xml file with `allow="*"` sitting on your main domain, that's very bad practice)
Since you are loading multiple swfs, you may need to include the security settings in each of those swfs on domain B that are loaded. You may also need a loader context with the appropriate security settings. ``` import flash.system.LoaderContext; import flash.system.ApplicationDomain; import flash.system.Security; import flash.system.SecurityDomain; import flash.net.URLRequest; import flash.net.URLLoader; var context:LoaderContext = new LoaderContext(true, ApplicationDomain.currentDomain, (Security.sandboxType == Security.REMOTE) ? SecurityDomain.currentDomain : null); var l:Loader = new Loader(); l.load(new URLRequest("http://example.com/myswf.swf"), context); ```
Cross Domain ExternalInterface "Error calling method on NPObject"
[ "", "javascript", "flash", "actionscript-2", "externalinterface", "" ]
I'm writing a query to do some stuff. But its not working the way I want it to: ``` select CORR_ID from TABLE1 where CORR_ID not in (select id from TABLE2) ``` The problem is, TABLE2.id is a long, while TABLE1.CORR\_ID is a string. So how can I make it work? PS: I'm using IBM UDB.
Okay, I found a method: ``` select CORR_ID from TABLE1 where CORR_ID not in (select CAST( CAST(id AS CHAR(50)) AS VARCHAR(50) ) from TABLE2) ``` This is pretty intriguing: You can't cast a BIGINT to VARCHAR, but: * you can cast a BIGINT to CHAR * and you can cast a CHAR TO VARCHAR this is ridiculous!
DB2 allows a VARCHAR and CHAR column to be compared without additional casting, so all you really need to do is cast the number. SELECT corr\_id FROM table1 WHERE corr\_id NOT IN (SELECT CHAR( id ) FROM table2 )
Datatype conversion in IBM DB2: BIGINT to VARCHAR
[ "", "sql", "db2", "udb", "" ]
> **Possible Duplicate:** > [What does the @ symbol before a variable name mean in C#?](https://stackoverflow.com/questions/429529/what-does-the-symbol-before-a-variable-name-mean-in-c) > > ### Duplicate: > > [What does the @ symbol before a variable name mean in C#?](https://stackoverflow.com/questions/429529/what-does-the-symbol-before-a-variable-name-mean-in-c) Sometimes I see some C# code where a method-parameter is prefixed with an @, like this: ``` public static void SomeStaticMethod( SomeType @parameterName ) { } ``` What is the meaning of this ? Does it has some significant special meaning ? I am creating an EventListener in NHibernate, and when I let VS.NET generate the interface methods, it generates the OnPostLoad method like this: ``` public class PostLoadEventListener : IPostLoadEventListener { public void OnPostLoad( PostLoadEvent @event ) { } } ``` Why is this ?
Try and make a variable named **class** and see what happens -- You'll notice you get an error. This lets you used reserved words as variable names. Unrelated, you'll also notice strings prefixed with @ as well -- This isn't the same thing... ``` string says = @"He said ""This literal string lets me use \ normally and even line breaks""."; ``` This allows you to use 'literal' value of the string, meaning you can have new lines or characters without escapes, etc...
The @ prefix allows you to use reserved words like class, interface, events, etc as variable names in C#. So you can do ``` int @int = 1 ```
C# prefixing parameter names with @
[ "", "c#", "" ]
I want to start a timer when the user clicks on a object, and stop it when the user releases the click. All using javascript/jquery.
The following should get you started ``` var start_time; function start() { start_time = new Date(); } function end() { var now = new Date(); alert(now-start_time); } $('#element_id').mousedown(start); $('#element_id').mouseup(end); ``` the mousedown event will run the start function which sets the start time. the mouseup event will substract the start time from the current time. The result is in milliseconds
`$("#element").mousedown();` will let you record when the user clicks, and similarly `$("#element").mouseup();`will let you record when the button is released. ``` var start = 0; $("#element").mousedown(function() { start = new Date(); }); $("#element").mouseup(function() { var cur = new Date(); alert(cur-start); } ```
How can I measure the time between click and release in javascript?
[ "", "javascript", "jquery", "" ]
I have some simple SVG artwork (icon and glyph kind of things) which I want to display in an OpenGL app (developing in C++ on Debian, using Qt). The obvious solution is to use the ImageMagick libs to [convert](https://stackoverflow.com/questions/1019462/how-to-convert-svg-files-to-other-image-formats) the SVGs to raster images and texture map them onto some suitable polygons (or just use good old glDrawPixels). However, I'm wondering if there's anything out there which will translate the SVG directly to a sequence of OpenGL calls and render it using OpenGL's lines, polygons and the like. Anyone know of anything which can do this ?
Qt can do this. [QSvgRenderer](https://doc.qt.io/qt-5/qsvgrenderer.html) can take an SVG and paint it over a `QGLWidget` Its possibly you'll need to fiddle around with the `paintEvent()` abit if you want to draw anything else on the QGLWidget other than the SVG.
[SVGL](http://sourceforge.net/projects/svgl) appears to address this but has been dormant for several years. Still you might be able to find some code of value there.
Displaying SVG in OpenGL without intermediate raster
[ "", "c++", "opengl", "graphics", "svg", "" ]
I'm looking at the example for the "click" event in the jQuery documentation [here](http://docs.jquery.com/Events/click#fn). I can refactor the two anonymous functions as follows and it still works: ``` $(document).ready(function(){ $("p").hover(hilite, remove_hilite); }); function hilite() { $(this).addClass("hilite"); } function remove_hilite() { $(this).removeClass("hilite"); } ``` However, what if I want to pass an argument to `hilite`? My first guess was that I should use an anonymous function like [this](http://docs.jquery.com/How_jQuery_Works#Right). However, this does not seem to work, even when I'm using it without arguments: ``` $("p").hover( function() { hilite(); } , function() { remove_hilite(); } ); ``` I also tried refactoring as follows, but this did not work either: ``` $(document).ready(function(){ $("p").hover(hilite2, remove_hilite); }); function hilite2(){ return hilite(); } ``` What is the proper way to do this? I feel like I have a big conceptual misunderstanding. In particular, I am unclear about how in my first refactoring, the `this` object is passed to the `hilite` function.
You can encapsulate your hover function call into another function that accepts the 'className' parameter: ``` $.fn.hoverClass = function(className){ return this.hover(function(){ $(this).addClass(className); }, function(){ $(this).removeClass(className); }); } ``` Then you can use it simply by this: ``` $('p').hoverClass('hilite'); ```
I think that what you want is a **partial function application**. ``` function partial(func /*, 0..n args */) { var args = Array.prototype.slice.call(arguments, 1); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(this, allArguments); }; } ``` With the above function, you can now do the following: ``` $(document).ready(function(){ var f = partial(hilite, "arg1", "arg2" /*etc...*/); $("p").hover(f, remove_hilite); }); ``` *Reference: [How can I pre-set arguments in JavaScript function call? (Partial Function Application)](https://stackoverflow.com/questions/321113)*
jQuery newbie: how can I pass arguments to an event handler function?
[ "", "javascript", "jquery", "" ]
This seems like it should be really simple to do but I just can't figure it out. I want to allow Visual Studio to keep auto formatting my code as it is, except for this part: ``` public SomeClass : BaseClass { public SomeClass() : base() { } } ``` Why can't I have it look like this instead: ``` public SomeClass : BaseClass { public SomeClass() : base() { } } ``` I looked through Tools -> Options -> Text Editor -> C# -> New Lines and can't find it. Is there a way I can change it to allow auto formatting and my second example?
Are you sure that unchecking: Options -> Text Editor -> C# -> Formatting -> New Lines -> Place Open Brace on new line for types doesn't do what you want? and also uncheck Place open brace on newline for methods. (nvrmind.. I see what you are getting at... It is annoying)
AFAIK there is no way to prevent Visual Studio from doing this.
How to stop Visual Studio from auto formatting certain parts of code?
[ "", "c#", "visual-studio", "visual-studio-2008", "preferences", "" ]
I have a function that reads lines from a log file, converts these lines to a certain class and returns a STL list of instances of this class. How should I declare this function so that the whole list is NOT copied when attributing it to the caller? Without loss of generality, assume: ``` list<Request> requests = log_manipulator.getAsRequestList(); ``` How should I declare `getAsRequestList()`? Should I return a reference to a list or just return a list? This is a serious issue because in this particular assignment the lists will contain circa 1.5M elements, and thus a mistake like that can screw up memory usage.
Returning a reference is not advisable, and returning the list object would cause copying. Best would be to change the method's signature to *accept and populate* a list reference: ``` list<Request> requests; log_manipulator.getRequestListByRef(requests); ``` with `void getRequestListByRef(list<Request>&)` as the method's signature.
You have two easy options: ### A return parameter ``` void getAsRequestList(list<Request>& requests); ``` ... ``` list<Request> requests; log_manipulator.getAsRequestList(requests); ``` ### An [output iterator](http://www.sgi.com/tech/stl/OutputIterator.html) ``` template <class OutputIterator> void getAsRequestList(OutputIterator dest); ... list<Request> requests; log_manipulator.getAsRequestList( insert_iterator< list<Request> >(requests, requests.begin()) ); ``` --- ### See also: [How do I return hundreds of values from a C++ function?](https://stackoverflow.com/questions/583821/how-do-i-return-hundreds-of-values-from-a-c-function)
Returning STL lists as argument
[ "", "c++", "list", "stl", "" ]
I have a table in my database with 2 rows of employee data. ``` ........... ID | Name ........... 1 | Jon Doe 2 | Jane Doe ........... ``` I need this in my code, just like this, as **code**. I need to convert this into: ``` Employee e1 = new Employee(); e1.ID = 1; e1.Name = "Jon Doe"; Employee e2 = new Employee(); e2.ID = 2; e2.Name = "Jane Doe"; ``` Now it is code it can be saved into a database when the app runs for the first time, and thus save me from writing 1200 object instances into the database. Therefore, I just need some way, such as using XML) on the first run. This is an example, why I need it is because, I have a table that stores settings (width,height,label for grid) etc that need to be set to something first time the app runs. What way could I generate this, are there any tools available, or how would you go about it?
The normal way to do this outside of an ORM is to write an `EmployeeFactory` class with a static method named something like `.Create()` or `.FromDataRow()` that accepts a DataRow as an argument and returns a new Employee object. This way you don't have to "pollute" your employee class with the code to do that, and you can maintain separation of concerns in a nice, testable way.
**Edited** I appear to have misread your question. It looked like what you want is an orm mapper but really what you are looking for is something like [MyGeneration](http://www.mygenerationsoftware.com/portal/default.aspx) which you can point at a database and have it build you the objects you need. I leave the remainder of the original answer as an ORM is still useful in these situations. There are several available for .Net and if you are developing on .Net 3 or higher, than you have one built in call Linq. Getting started with Linq is beyond the scope of this answer so here is a [great blog post from Scott Guthrie](http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx) which walks you through it. Another Microsoft offering is available called EntityFramwork and more information about that can be found [here](http://msdn.microsoft.com/en-us/library/bb386876.aspx) [NHibernate](https://www.hibernate.org/343.html) is a free .Net port of the Hibernate framework which also gets the job done. ORM mappers make converting database data into classes very easy, but they come with trade offs. See the [wikipedia](http://en.wikipedia.org/wiki/Object-relational_mapping) entry for more info.
Convert database row into object
[ "", "c#", "sql-server", "database", "object", "" ]
I have looked at /System/Library, but I have not found the iostream library/module by ``` ack iostream ``` **Where are the standard libraries in OS/X?**
On OS X 10.10 Yosemite, they're located here: `/usr/include/c++`
Please make sure you have [XCode](http://developer.apple.com/tools/xcode/index.html) installed first. Without xcode you won't be able to develop C/C++ applications since xcode includes all linkable standard libraries and headers.
Unable to find the location of C++'s standard libraries in OS/X?
[ "", "c++", "macos", "" ]
When I try to compile an assembly in VS 2008, I got (occasionally, usually after 2-3 hours of work with the project) the following error ``` Metadata file '[name].dll' could not be opened -- 'Not enough storage is available to process this command. ``` Usually to get rid of that I need to restart Visual Studio The assembly I need to use in my project is BIG enough (> 70 Mb) and probably this is the reason of that bug, I've never seen some thing like this in my previous projects. Ok, if this is the reason my question is why this happens and what I need to do to stop it. I have enough of free memory on my drives and 2Gb RAM (only ~1.2 Gb are utilized when exception happens) I googled for the answers to the questions like this. Suggestions usually related to: > 1. to the number of user handlers that is limited in WinXP... > 2. to the physical limit of memory available per process I don't think either could explain my case For user handlers and other GUI resources - I don't think this could be a problem. The big 70Mb assembly is actually a GUI-less code that operates with sockets and implements parsers of a proprietary protocols. In my current project I have only 3 GUI forms, with total number of GUI controls < 100. I suppose my case is closer to the fact that in Windows XP the process address space is limited with 2 GB memory (and, taking into account memory segmentation, it is possible that I don't have a free segment large enough to allocate a memory). However, it is hard to believe that segmentation could be so big after just 2-3 hours of working with the project in Visual Studio. Task Manager shows that VS consumes about 400-500 Mb (OM + VM). During compilation, VS need to load only meta-data. Well, there are a lot of classes and interfaces in that library, but still I would expect that 1-2 Mb is more then enough to allocate **metadata** that is used by compiler to find all public classes and interfaces (though it is only my suggestion, I don't know what exactly happens inside `CLR` when it loads assembly metadata). In addition, I would say that entire assembly size is so big only because it is `C++ CLI` library that has other um-managed libraries statically linked into one `DLL`. I estimated (using Reflector) that .NET (managed) code is approx 5-10% of this assembly. Any ideas how to define the real reason of that bug? Are there any restrictions or recommendations as to .NET assembly size? (*Yes I know that it worth thinking of refactoring and splitting a big assembly into several smaller pieces, but it is a 3rd party component, and I can't rebuilt it*)
In my case the following fix helped: [http://confluence.jetbrains.net/display/ReSharper/OutOfMemoryException+Fix](https://web.archive.org/web/20130203074733/http://confluence.jetbrains.com/display/ReSharper/OutOfMemoryException+Fix)
The error is misleading. It really should say "A large enough contiguous space in virtual memory could not be found to perform the operation". Over time allocations and deallocations of virtual memory space leads to it becoming fragmented. This can lead to situations where a large allocation cannot be filled despite there being a plenty total space available. I think this what your "segmentation" is refering to. Without knowing all the details of everything else that needs to load and other activity which occupies the 2-3 hour period its difficult to say whether this really is the cause. However I would not put it into the category of unlikely, in fact it is the most likely cause.
Not enough storage is available to process this command in VisualStudio 2008
[ "", "c#", "visual-studio", "visual-studio-2008", "memory-leaks", "metadata", "" ]
In Python 2: ``` raw_input() ``` In Python 3, I get an error: > NameError: name 'raw\_input' is not defined
Starting with Python 3, `raw_input()` was renamed to `input()`. From [What’s New In Python 3.0, Builtins section](https://docs.python.org/3/whatsnew/3.0.html#builtins) second item.
This works in Python 3.x and 2.x: ``` # Fix Python 2.x. try: input = raw_input except NameError: pass print("Hi " + input("Say something: ")) ```
How do I use raw_input in Python 3?
[ "", "python", "python-3.x", "" ]
Is it possible to detect, using JavaScript, when the user changes the zoom in a page? I simply want to catch a "zoom" event and respond to it (similar to window.onresize event). Thanks.
There's no way to actively detect if there's a zoom. I found a good entry here on how you can attempt to implement it. > I’ve found two ways of detecting the > zoom level. One way to detect zoom > level changes relies on the fact that > percentage values are not zoomed. A > percentage value is relative to the > viewport width, and thus unaffected by > page zoom. If you insert two elements, > one with a position in percentages, > and one with the same position in > pixels, they’ll move apart when the > page is zoomed. Find the ratio between > the positions of both elements and > you’ve got the zoom level. See test > case. > <http://web.archive.org/web/20080723161031/http://novemberborn.net/javascript/page-zoom-ff3> You could also do it using the tools of the above post. The problem is you're more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other. There's no way to tell if the page is zoomed if they load your page while zoomed.
Lets define px\_ratio as below: px ratio = ratio of physical pixel to css px. if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS\_px ) must get bigger. but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain. # zooming: trigger windows.resize event --> and change px\_ratio but resizing: trigger windows.resize event --> doesn’t change px\_ratio ``` //for zoom detection px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth; $(window).resize(function(){isZooming();}); function isZooming(){ var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth; if(newPx_ratio != px_ratio){ px_ratio = newPx_ratio; console.log("zooming"); return true; }else{ console.log("just resizing"); return false; } } ``` The key point is difference between CSS PX and Physical Pixel. <https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e>
Catch browser's "zoom" event in JavaScript
[ "", "javascript", "events", "zooming", "" ]
I looked over this web and google and the solutions didn't work for me. I have a command on the ViewModel of a UserControl. Well, The usercontrol have a ItemsControl binded to a ObservableCollection. Inside the DataTemplate of the ItemsControl.ItemTemplate I have a button and I want to use the command. I can't bind the command because inside the DataTemplate, the datacontext is not the ViewModel but an item of the ObservableCollection. The question is: How can I bind the button to the command if a lost the parent datacontext? I think that this need to have an easy solution because I think that this is a common problem. Imagine this sceneario: You have a ListBox item with an observableCollection as the ItemsSource, so you are using a datatemplate inside the ListBox for every element in the collection. Well, you want to delete the selected item and you put a button in every row for that job. ¿How do you do that? In MVP, I can do this in the click event of the button: ``` Button but = e.Source as Button; if (but != null) Presenter.ActualNote = but.DataContext as Note; ``` In short. You send the datacontext of the row (the selected item) to the presenter. But, how can I do it in the mvvm way? Because I need to use a command but I can't assign the command to the button because the button does know nothing about the ViewModel (where the command exists). As you can see, the button has to exist inside the datatemplate, then the datacontext is not the ViewModel anymore.... There is why I need to access to the parent's DataContext, for access to the command. I hope that you understand my problem better. Thank you.
If you want a dirty, MVVM-breaking solution, then set the Tag="{Binding}" on the button and handle the Click event. In the event handler, call the command on your ViewModel.
Use the binding below for your button's command: ``` {Binding DataContext.CommandName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyUserControl}}} ``` This will tell it to find your UserControl and use its DataContext.
Using the parent's DataContext (WPF - Dynamic Menu Command Binding)
[ "", "c#", "wpf", "dynamic", "menu", "commandbinding", "" ]
In my application I have a method to check a variable is a number or not. This method is called more than once in my code. The method is called from the codebehind pages. Like this method I have more methods which i cannot place within a single class (like Staff). Where should I put this kind of methods?
In a utility class file.
In C# 3.0, I would probably make this an extension method on the string class. I would group all of my string extensions into a single static class to improve readability. ``` public static class StringExtensions { public static bool IsNumeric( this string source ) { if (string.IsNullOrEmpty( source )) { return false; } ... } public static bool IsMoney( this string source ) { ... } ... } ``` Usage: ``` if (amountLabel.Text.IsNumeric()) { ... } ```
C# Where to put general methods?
[ "", "c#", "methods", "" ]
I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal. I found this: [Set Process Priority In Windows - ActiveState](http://code.activestate.com/recipes/496767/) But I'm looking for a cross-platform solution.
Here's the solution I'm using to set my process to below-normal priority: **`lowpriority.py`** ``` def lowpriority(): """ Set the priority of the process to below-normal.""" import sys try: sys.getwindowsversion() except AttributeError: isWindows = False else: isWindows = True if isWindows: # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ import win32api,win32process,win32con pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS) else: import os os.nice(1) ``` Tested on Python 2.6 on Windows and Linux.
You can use [psutil](http://code.google.com/p/psutil/wiki/Documentation) module. On POSIX platforms: ``` >>> import psutil, os >>> p = psutil.Process(os.getpid()) >>> p.nice() 0 >>> p.nice(10) # set >>> p.nice() 10 ``` On Windows: ``` >>> p.nice(psutil.HIGH_PRIORITY_CLASS) ```
Change process priority in Python, cross-platform
[ "", "python", "" ]
When I try to run the update manager in Eclipse, I get the error "Cannot launch the Update UI. This installation has not been configured properly for Software Updates." Does anyone know how to fix this?
There are some bugs already entered about that message: * [bug 238910](https://bugs.eclipse.org/bugs/show_bug.cgi?id=238910): if your eclipse error log contains: !MESSAGE Error parsing profile /opt/eclipse/p2/org.eclipse.equinox.p2.engine/profileRegistry/SDKProfile.profile/1214752385704.profile. > the .profile was corrupted. > I simply deleted the corrupted .profile, restarted eclipse and everything seems > to be fine now * [bug 224658](https://bugs.eclipse.org/bugs/show_bug.cgi?id=224658) : when self-hosting, p2 update ui won't come up (self-hosting case (that is, Eclipse debugging another instance of Eclipse, as in a plugin development situation) Fixed in 3.4 * [bug 230245](https://bugs.eclipse.org/bugs/show_bug.cgi?id=230245): Failure to read unicode (in certain xml files): Fixed in 3.4 What version of eclipse are you running?
Try enabling *Classic Update* ``` Window -> Preferences -> General -> Capabilities -> Classic Update ``` If that entry isn't available to you: 1. Shutdown eclipse 2. Navigate to this file `[yourWORKSPACE]/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs` and try adding this line and restarting eclipse ``` UIActivities.org.eclipse.equinox.p2.ui.sdk.classicUpdate=true ```
Getting the message "Cannot start the update ui..." when trying to run the update UI in Eclipse
[ "", "java", "eclipse", "" ]
Allegedly you cannot just erase/remove an element in a container while iterating as iterator becomes invalid. What are the (safe) ways to remove the elements that meet a certain condition? please only stl, no boost or tr1. **EDIT** Is there a more elegant way if I want to erase a number of elements that meet a certain criteria, perhaps with using functor and for\_each or erase algorithm ?
``` bool IsOdd( int i ) { return (i&1)!=0; } int a[] = {1,2,3,4,5}; vector<int> v( a, a + 5 ); v.erase( remove_if( v.begin(), v.end(), bind1st( equal_to<int>(), 4 ) ), v.end() ); // v contains {1,2,3,5} v.erase( remove_if( v.begin(), v.end(), IsOdd ), v.end() ); // v contains {2} ```
You can as long as you don't invalidate your iterator after you've erased it: ``` MyContainer::iterator it = myContainer.begin(); while(it != myContainer.end()) { if (*it == matchingValue) { myContainer.erase(it++); } else { ++it; } } ```
Erase/Remove contents from the map (or any other STL container) while iterating it
[ "", "c++", "stl", "" ]
For some reason by css link in a **webforms** master page is getting mangled by ASP.NET. The page using the masterpage is located in /subdir1/subdir2/page.aspx Not sure why it is happening but here is a snippet of the code: ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="<%= MyNamespace.Helpers.UrlHelper.CssRoot %>Site.css" rel="stylesheet" type="text/css" /> <script src="<%= MyNamespace.Helpers.UrlHelper.JavascriptRoot %>jquery-1.3.2.min.js" type="text/javascript"></script> <asp:ContentPlaceHolder ID="cphHead" runat="server"> </asp:ContentPlaceHolder> </head> ``` The Html output that is being created is: ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head><title> Untitled Page </title><link href="../../%3C%25=%MyNamespace.Helpers.UrlHelper.CssRoot%20%25%3ESite.css" rel="stylesheet" type="text/css" /> <script src="/Javascript/jquery-1.3.2.min.js" type="text/javascript"></script> </head> ``` Why is this working for the script tag but mangling the link tag and not actually executing the code included. If I change the 'link' tag to be a 'script' tag (which is wrong but for testing purposes) it produces the proper html I would expect. Why is ASP.NET messing with my link tag for my Css but not the script tag for the javascript? Is there something special about the link tag to make ASP.NET think it needs to mangle it?
This is a separate answer based on approach and might be more what you are looking for. The reason I found for the string mangling is the HtmlLink object has internal handling of the href value during rendering. Using .NET Reflector I found an Overrides RenderAttributes method. This is the code for it: ``` Protected Overrides Sub RenderAttributes(ByVal writer as HtmlTextWriter) If Not String.IsNullOrEmpty(Me.Href) Then MyBase.Attributes.Item("href") = MyBase.ResolveClientUrl(Me.Href) End If MyBase.RenderAttributes(writer) End Sub ``` What I believe is happening is the RenderAttributes method is being called before your helper line is being parsed and is using ResolveClientUrl against the string "<%= MyNamespace.Helpers.UrlHelper.CssRoot %>Site.css". The solution of using "~/" URL strings isn't affected by this because ResolveClientUrl is able to understand that notation. I see two solutions for you at this point. 1) Use the Edit #2 approach of injecting the helper's URL string into the element during Page\_Load or Page\_PreRender, or 2) Create your own Overrriden version of the HtmlLink element that doesn't try to use ResolveClientUrl. #1 would definitely be the easier solution. Hope this helps shed some light on the issue.
Perhaps a solution would be to specify your `<link>` and `<script>` tags from your master page's codebehind. ``` private void ConstructLinkAndScriptTags() { string cssTag = "<link href='" + MyNamespace.Helpers.UrlHelper.CssRoot + "Site.css' rel='stylesheet' type='text/css' runat='server' />"; cph.Controls.Add(new LiteralControl(cssTag)); } ```
ASP.NET Webform css link getting mangled
[ "", "c#", "asp.net", "webforms", "" ]
I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels. The issue is that some mIRC users and some Bots write using [color codes](http://www.mirc.com/help/color.txt). Any idea on how i could strip those parts and leave only the clear ascii text message?
Regular expressions are your cleanest bet in my opinion. If you haven't used them before, [this](http://www.diveintopython.org/regular_expressions/index.html) is a good resource. For the full details on Python's regex library, go [here](http://docs.python.org/library/re.html). ``` import re regex = re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE) ``` The regex searches for ^C (which is \x03 in [ASCII](http://en.wikipedia.org/wiki/ASCII), you can confirm by doing chr(3) on the command line), and then optionally looks for one or two [0-9] characters, then optionally followed by a comma and then another one or two [0-9] characters. **(?: ... )** says to forget about storing what was found in the parenthesis (as we don't need to backreference it), **?** means to match 0 or 1 and **{n,m}** means to match n to m of the previous grouping. Finally, **\d** means to match [0-9]. The rest can be decoded using the links I refer to above. ``` >>> regex.sub("", "blabla \x035,12to be colored text and background\x03 blabla") 'blabla to be colored text and background blabla' ``` *chaos*' solution is similar, but may end up eating more than a max of two numbers and will also not remove any loose ^C characters that may be hanging about (such as the one that closes the colour command)
The second-rated and following suggestions are defective, as they look for digits after whatever character, but not after the color code character. I have improved and combined all posts, with the following consequences: * we *do* remove the reverse character * remove color codes *without* leaving digits in the text. Solution: `regex = re.compile("\x1f|\x02|\x12|\x0f|\x16|\x03(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE)`
How to strip color codes used by mIRC users?
[ "", "python", "irc", "" ]
I have a set of classes that all need to be acted on in some (individual) way. Ordinarily I'd just create a `DoSomethingInterface` with a single `doSomething()` method and have each class implement that method in a way that suits each class' needs. However, I cannot do that in this case as the class definitions are unmodifyable (auto-generated) So, I reckon I need to create a set of different classes that each take one of the autogenerated classes and performs the operation on them. So, say I have 2 autogenerated classes, `Class1` and `Class2`, I will first define a common `Operator` interface: ``` public interface Operator <TYPE>{ public void doSomething(TYPE type); } ``` and then implement one of these per class ``` public class Class1Operator implements Operator<Class1>{ public void doSomething(Class1 type){ ... ... } } ``` and ``` public class Class2Operator implements Operator<Class2>{ public void doSomething(Class2 type){ ... ... } } ``` Ok, so far so good. Now, given that I have an object of type `Class1`, is there any way of getting its operator without resorting to: ``` public Operator getOperator(Object obj){ if(obj instanceof Class1){ return new Class1Operator(); }else if(obj instanceof Class2{ return new Class2Operator(); } return null; } ``` Which kinda seems like bad practice to me... The only other way I can think of is by creating a map of operators to class names like so: ``` Map<Class, Operator> allOperators = new HashMap<Class, Operator>(); allOperators.put(Class1.class, new Class1Operator()); allOperators.put(Class2.class, new Class2Operator()); ``` and then return the operator using: ``` public Operator getOperator(Object obj){ return allOperators.get(obj); } ``` But this doesn't seem right (I'm not sure, are there any issues with keying an object off its class....) Any input as to whether either of these approaches is 'correct'? or is there a more elegant solution?? Thanks
What you've implemented (the map-by-class approach) is one of the alternatives to the GoF Visitor pattern I talk about when I teach patterns. It's efficient and extendable, even at runtime. Much better than the if/else if/else hardwired approach. The only issue with keying off the class is if the actual instances implement subtypes rather than the class type you mention; then the lookup map won't work. If you need subtypes to be recognized, I'd recommend Aaron's approach (walk up the superclass chain), but you may also want to look at implemented interfaces as well. If you just need "exact class match", keep your getOperator simple. Note that you have a bug in getOperator -- it should look as follows: ``` public Operator getOperator(Object obj){ return allOperators.get(obj.getClass()); } ``` One more thing... Hide your map inside another class and manage it as follows: ``` private Map<Class<?>, Operator<?>> map = new HashMap<Class<?>, Operator<?>>(); public <T> void register(Class<T> clazz, Operator<T> operator) { map.put(clazz, operator); } ``` This prevents anyone from registering an operator that won't work against the class it's keyed against. (You might want to use Operator as the parameter to allow an operator that's written against a superclass, but that's might not be needed)
One of the issues with building a map is that it will not support subclasses unless you register them specifically or extend your get function to look up super classes specifically. That is to say if B inherits from A and you've registered an operator with A.class. Fetching an operator with B.class will fail, unless you change your getOperator to something like: ``` public Operator getOperator(Object obj){ Class<?> current = obj.getClass(); Operator op; while((op = allOperators.get(current)) == null){ current = current.getSuperclass(); if(current == null){ /* * We've walked all the way up the inheritance hierarcy * and haven't found a handler. */ return null; } } return op; } ``` Once you've got a reasonable getOperator implementation, mapping classes to operators seems like a reasonable approach.
Java design issue - Adding functionality to fixed classes
[ "", "java", "class", "" ]
One aspect of javascript that it's hard to find information on is casing practices. By casing practices, I mean what casing style (ie. camel-case, pascal-case, etc) should be used for what elements (Constructors, private functions, public functions). The only rule I've heard was from a Douglas Crockford lecture on YUI theater, stating that constructors should be the only functions that start with an uppercase letter. Beyond that there doesn't seem to be many casing standards that people follow in javascript. Does anyone know any casing best practices for javascript, and why it's reasonable to use them? Also do you follow a casing style with your .js files?
I prefer PascalCase for constructors and camelCase for everything else. That's the style that JS standard library uses and well... every JS framework I've seen so far :) And I use all\_lowercase naming convention for all files served from web. There are *some* case-insensitive file systems out there.
The core language uses InitialCaps for constructors (e.g. Object, Date, Number, RegExp) and camelCase for methods and properties (e.g. something.toString(), quantity.valueOf(), regexp.ignoreCase). This convention is also followed in the DOM specifications and implementations (e.g. HTMLElement.setAttribute()). So it makes the most sense to adopt the same convention, or you finish up with a horrendous mishmash of styles like: ``` var number_of_fish_requested = document.getElementById("fish").value; var fish_count = parseInt(number_of_fish_requested, 10); ``` which just becomes utterly confusing, not only to type but, much more importantly, to read. (You spend more time reading code, trying to debug or modify it, than you ever do writing it in the first place.)
What is the best-practice casing style for javascript? Why?
[ "", "javascript", "variables", "function", "casing", "" ]
A third party library I'm utilizing provided the JavaDoc HTML and associated bin files in a zip file. How can I create a jar file from the JavaDoc HTML? Thanks.
A JAR file is nothing but a ZIP file with an (optional) manifest file inside. Basically, rename the file to .JAR and that's it.
Quick answer: You can take all the files in a ZIP and put it .jar extension
Jar from HTML
[ "", "java", "jar", "javadoc", "" ]
I have a URL with some GET parameters as follows: ``` www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ``` I need to get the whole value of `c`. I tried to read the URL, but I got only `m2`. How do I do this using JavaScript?
JavaScript *itself* has nothing built in for handling query string parameters. Code running in a ([modern](https://caniuse.com/url)) browser can use the [`URL` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) (a [Web API](https://developer.mozilla.org/en-US/docs/Web/API)). `URL` is also implemented by [Node.js](https://nodejs.org/api/url.html#the-whatwg-url-api): ``` // You can get url_string from window.location.href if you want to work with // the URL of the current page var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; var url = new URL(url_string); var c = url.searchParams.get("c"); console.log(c); ``` --- For older browsers (including Internet Explorer), you can use [this polyfill](https://github.com/webcomponents/URL). You could also use one for [URLSearchParams](https://github.com/ungap/url-search-params) and extract the query string to pass to it with `window.location.search.substring(1)`. --- You could also use the code from the original version of this answer that predates `URL`. The above polyfill is robust and well tested and I strongly recommend it over this though. You could access `location.search`, which would give you from the `?` character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first. Then you can parse it with this: ``` function parse_query_string(query) { var vars = query.split("&"); var query_string = {}; for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); var key = decodeURIComponent(pair.shift()); var value = decodeURIComponent(pair.join("=")); // If first entry with this name if (typeof query_string[key] === "undefined") { query_string[key] = value; // If second entry with this name } else if (typeof query_string[key] === "string") { var arr = [query_string[key], value]; query_string[key] = arr; // If third or later entry with this name } else { query_string[key].push(value); } } return query_string; } var query_string = "a=1&b=3&c=m2-m3-m4-m5"; var parsed_qs = parse_query_string(query_string); console.log(parsed_qs.c); ``` You can get the query string from the URL of the current page with: ``` var query = window.location.search.substring(1); var qs = parse_query_string(query); ```
Most implementations I've seen miss out URL-decoding the names and the values. Here's a general utility function that also does proper URL-decoding: ``` function getQueryParams(qs) { qs = qs.split('+').join(' '); var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g; while (tokens = re.exec(qs)) { params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]); } return params; } //var query = getQueryParams(document.location.search); //alert(query.foo); ```
Get the values from the "GET" parameters (JavaScript)
[ "", "javascript", "url", "url-parameters", "" ]
I need a circular linked list, so I am wondering if `LinkedList` is a circular linked list?
No. It is a doubly linked list, but not a circular linked list. See [MSDN for details on this](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx). LinkedList<T> makes a good foundation for your own circular linked list, however. But it does have a definite First and Last property, and will not enumerate around these, which a proper circular linked list will.
A quick solution to using it in a circular fashion, whenever you want to move the "next" piece in the list: ``` current = current.Next ?? current.List.First; ``` Where current is `LinkedListNode<T>`.
Is the LinkedList in .NET a circular linked list?
[ "", "c#", ".net", "linked-list", "" ]
I'm having a `List<T>` and want get the values back in reverse order. What I don't want is to reverse the list itself. This seems like no problem at all since there's a `Reverse()` extension method for `IEnumerable<T>` which does exactly what I want. My problem is, that there's also a `Reverse()` method for `List<T>` which reverses the list itself and returns void. I know there are *plenty* of ways to traverse the list in reverse order but my question is: **How do I tell the compiler that I want to use the extension method with the same name?** ``` var list = new List<int>(new [] {1, 2, 3}); DumpList(list.Reverse()); // error ```
The best way to explictly bind to a particular extension method is to call it using shared method syntax. In your case, you would do that like: ``` DumpList(Enumerable.Reverse(list)); ``` The problem with some of the other approaches mentioned here is that they won't always do what you want. For example, casting the list like so: ``` ((IEnumerable)list).Reverse() ``` could end up calling a completely different method depending on the namespaces you have imported, or what type the calling code is defined in. The only way to be 100% sure you bind to a particular extension method is to use the shared method syntax.
``` var list = new List<int>(new [] {1, 2, 3}); DumpList((list as IEnumerable<int>).Reverse()); ``` OR ``` IEnumerable<int> list = new List<int>(new [] {1, 2, 3}); DumpList(list.Reverse()); ```
Explicitly use extension method
[ "", "c#", "extension-methods", "" ]
Let's say I have: ``` public class Fruit { public static List<String> Suppliers { get; protected set; } static Fruit() { Suppliers = new List<String>(); Suppliers.Add("Company A"); } } public class Banana : Fruit { static Banana() { Suppliers.Add("Company B"); } } ``` If I just do this in the calling code: ``` foreach(String supplier in Banana.Suppliers) Console.WriteLine(supplier); ``` I get: * Company A Whereas if I do: ``` Banana b = new Banana(); foreach(String supplier in Banana.Suppliers) Console.WriteLine(supplier); ``` I get (the desired result): * Company A * Company B **Edit:** After reading the responses I understand that this won't work. What I want in my production code is a list of values that is common to the type of object and I want to dynamically add different values to that list of strings based on the subtype. (The context is LDAP - all entries have objectClass=top and all user-objects have objectClass=user,top,organizationPerson,person). Guess I have to use an interface or different lists in each subclass or something if no one has a better suggestion?
For one thing, accessing `Banana.Suppliers` is misleading. It will always yield the same result as accessing `Apple.Suppliers` etc - you've got a *single* collection of suppliers. Basically any time you access `Banana.Suppliers` the compiler emits a call to `Fruit.Suppliers`: that's why just calling `Banana.Suppliers` isn't triggering the static constructor which adds the banana supplier. The reason you only see the suppliers added in the static constructor for bananas after you've created a banana is that that forces the static constructor to run. You could do anything else that forced the static initializer to run, and you'd get the same results. One example would be calling a static method within `Banana` itself. Now, I strongly suspect that you've got a significant problem in that you'll be using the same suppliers for all types. Obviously this isn't your *real* code, and the best solution will depend on what you want your real code to do. Generics can give you effectively "per type" static variables using type arguments : `Foo<Banana>.StaticProperty` and `Foo<Apple>.StaticProperty` will really be different, assuming `StaticProperty` is declared in `Foo<T>`. EDIT: With regards to your edit, I would suggest avoiding using statics here. Possibly create a factory for each type (implementing an interface which may be generic). Note that you may well be able to avoid creating a separate factory *type* for each subtype, if you can create an appropriate instance with all the relevant items for each type. We'd really need to see more of an example to say for sure, but in general I find that the less static data you have, the more testable your design will be and the less you'll run into problems like this :)
The results you are seeing are caused by the way that static constructors work. The CLR does not actually execute the static constructor util the first instance is used, which is why you only get the desired results in your second example. See [MSDN](http://msdn.microsoft.com/en-us/library/k9x6w0hc%28VS.80%29.aspx) for more info.
How can I access a static property in a subclass when the property is located in a base class?
[ "", "c#", "inheritance", "" ]
I have a SQL table with a date field defined as char(8), or 20090609, and a time field defined as char(4), or 1230. I am moving this data into another table and I want to combine the two fields and put them in a smalldatetime field in the new table. My query is like this: ``` INSERT NewTable(eventdate) SELECT CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as smalldatetime) FROM OldTable ``` When I run this, I get an error: > The conversion of char data type to > smalldatetime data type resulted in an > out-of-range smalldatetime value. I've tried checking len(datecol) and len(timecol) to make sure that they are at least the correct number of characters. I have no idea how I can find the offending data, any suggestions? The database is SQL2000 and I'm using SMO 2008.
It is probably out of the range of acceptable smalldatetime values January 1, 1900, through June 6, 2079 **EDIT** On closer inspection I think the substring parameters for the second portion of the time may be incorrect (which may be the whole problem) updated below to reflect substring(timecol, 3, 2) **New Approach** this sql does assume that all dates are 8 characters in length, and all times are 4. ``` Select SubString(DateCol, 1, 4) as tehYear, Substring(DateCol, 5,2) as tehMonth, SubString(DateCol, 7,2) as tehDay, SubString(TimeCol, 1,2) as tehHour, Substring(TimeCOl, 3,4) as tehMinute, * from OldTable where (SubString(DateCol, 1,4) > 9999 or SubString(DateCol, 1,4) < 1753) OR (Substring(DateCol, 5,2) > 12 or Substring(DateCol, 5,2) < 1) OR (SubString(DateCol, 7,2) > 31 or SubString(DateCol, 7,2) < 1) OR (SubString(TimeCol, 1,2) > 23 or(SubString(TimeCol, 1,2) < 0) OR (Substring(TimeCOl, 3,4) > 59 or Substring(TimeCOl, 3,4) <0) ``` Try casting to datetime and seeing if there are any dates that fall outside of that range to identify your problem data. ``` SELECT CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as datetime) FROM OldTable Where CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as datetime) > Cast('06/06/2079' as datetime) or CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as datetime) < Cast('01/01/1900' as datetime) ```
Try this: ``` SELECT datecol, timecol FROM OldTable WHERE ISDATE(datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 2, 2)) = 0 ``` That will show you which rows cannot be converted successfully.
How can I find out which data won't cast?
[ "", "sql", "t-sql", "sql-server-2000", "" ]
I am trying to write a JavaScript function to get the current browser width. I found this one: ``` console.log(document.body.offsetWidth); ``` But its problem that it fail if the body has width 100%. Is there any other better function or a workaround?
# Update for 2017 My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on [line 37 of dimensions.js](https://github.com/jquery/jquery/blob/master/src/dimensions.js#L37). Here it is extracted and modified to work standalone: ``` function getWidth() { return Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth ); } function getHeight() { return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight ); } console.log('Width: ' + getWidth() ); console.log('Height: ' + getHeight() ); ``` --- # Original Answer Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you: ``` function getWidth() { if (self.innerWidth) { return self.innerWidth; } if (document.documentElement && document.documentElement.clientWidth) { return document.documentElement.clientWidth; } if (document.body) { return document.body.clientWidth; } } ``` and similarly for height: ``` function getHeight() { if (self.innerHeight) { return self.innerHeight; } if (document.documentElement && document.documentElement.clientHeight) { return document.documentElement.clientHeight; } if (document.body) { return document.body.clientHeight; } } ``` Call both of these in your scripts using `getWidth()` or `getHeight()`. If none of the browser's native properties are defined, it will return `undefined`.
It's a [pain in the ass](http://www.howtocreate.co.uk/tutorials/javascript/browserwindow). I recommend skipping the nonsense and using [jQuery](http://docs.jquery.com/CSS/width), which lets you just do `$(window).width()`.
How to get browser width using JavaScript code?
[ "", "javascript", "html", "css", "" ]
Does anyone have an example of an SSH library connection using Java.
The [Java Secure Channel (JSCH)](http://www.jcraft.com/jsch/) is a very popular library, used by maven, ant and eclipse. It is open source with a BSD style license.
Update: The GSOC project and the code there isn't active, but this is: <https://github.com/hierynomus/sshj> hierynomus took over as maintainer since early 2015. Here is the older, no longer maintained, Github link: <https://github.com/shikhar/sshj> --- There was a GSOC project: <http://code.google.com/p/commons-net-ssh/> Code quality seem to be better than JSch, which, while a complete and working implementation, lacks documentation. Project page spots an upcoming beta release, last commit to the repository was mid-august. Compare the APIs: <http://code.google.com/p/commons-net-ssh/> ``` SSHClient ssh = new SSHClient(); //ssh.useCompression(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); new SCPDownloadClient(ssh).copy("ten", "/tmp"); } finally { ssh.disconnect(); } ``` <http://www.jcraft.com/jsch/> ``` Session session = null; Channel channel = null; try { JSch jsch = new JSch(); session = jsch.getSession(username, host, 22); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(password); session.connect(); // exec 'scp -f rfile' remotely String command = "scp -f " + remoteFilename; channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); byte[] buf = new byte[1024]; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); while (true) { int c = checkAck(in); if (c != 'C') { break; } // read '0644 ' in.read(buf, 0, 5); long filesize = 0L; while (true) { if (in.read(buf, 0, 1) < 0) { // error break; } if (buf[0] == ' ') { break; } filesize = filesize * 10L + (long) (buf[0] - '0'); } String file = null; for (int i = 0;; i++) { in.read(buf, i, 1); if (buf[i] == (byte) 0x0a) { file = new String(buf, 0, i); break; } } // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); // read a content of lfile FileOutputStream fos = null; fos = new FileOutputStream(localFilename); int foo; while (true) { if (buf.length < filesize) { foo = buf.length; } else { foo = (int) filesize; } foo = in.read(buf, 0, foo); if (foo < 0) { // error break; } fos.write(buf, 0, foo); filesize -= foo; if (filesize == 0L) { break; } } fos.close(); fos = null; if (checkAck(in) != 0) { System.exit(0); } // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); channel.disconnect(); session.disconnect(); } } catch (JSchException jsche) { System.err.println(jsche.getLocalizedMessage()); } catch (IOException ioe) { System.err.println(ioe.getLocalizedMessage()); } finally { channel.disconnect(); session.disconnect(); } } ```
SSH library for Java
[ "", "java", "ssh", "ssh-tunnel", "" ]
I'm trying to move some JavaScript code from MicrosoftAjax to JQuery. I use the JavaScript equivalents in MicrosoftAjax of the popular .net methods, e.g. String.format(), String.startsWith(), etc. Are there equivalents to them in jQuery?
The [source code for ASP.NET AJAX is available](http://weblogs.asp.net/scottgu/archive/2007/01/30/asp-net-ajax-1-0-source-code-released.aspx) for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery. Here is the format function... ``` String.format = function() { var s = arguments[0]; for (var i = 0; i < arguments.length - 1; i++) { var reg = new RegExp("\\{" + i + "\\}", "gm"); s = s.replace(reg, arguments[i + 1]); } return s; } ``` And here are the endsWith and startsWith prototype functions... ``` String.prototype.endsWith = function (suffix) { return (this.substr(this.length - suffix.length) === suffix); } String.prototype.startsWith = function(prefix) { return (this.substr(0, prefix.length) === prefix); } ```
This is a faster/simpler (and prototypical) variation of the function that Josh posted: ``` String.prototype.format = String.prototype.f = function() { var s = this, i = arguments.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); } return s; }; ``` Usage: ``` 'Added {0} by {1} to your collection'.f(title, artist) 'Your balance is {0} USD'.f(77.7) ``` I use this so much that I aliased it to just `f`, but you can also use the more verbose `format`. e.g. `'Hello {0}!'.format(name)`
Equivalent of String.format in jQuery
[ "", "javascript", "jquery", "string.format", "" ]
Does Postgres automatically put indexes on Foreign Keys and Primary Keys? How can I tell? Is there a command that will return all indexes on a table?
PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships. When Pg creates an implicit index it will emit a `NOTICE`-level message that you can see in `psql` and/or the system logs, so you can see when it happens. Automatically created indexes are visible in `\d` output for a table, too. The [documentation on unique indexes](http://www.postgresql.org/docs/current/static/indexes-unique.html) says: > PostgreSQL automatically creates an index for each unique constraint and primary key constraint to enforce uniqueness. Thus, it is not necessary to create an index explicitly for primary key columns. and the documentation on [constraints](http://www.postgresql.org/docs/current/static/ddl-constraints.html) says: > Since a DELETE of a row from the referenced table or an UPDATE of a > referenced column will require a scan of the referencing table for > rows matching the old value, it is often a good idea to index the > referencing columns. Because this is not always needed, and there are > many choices available on how to index, declaration of a foreign key > constraint does not automatically create an index on the referencing > columns. Therefore you have to create indexes on foreign-keys yourself if you want them. Note that if you use primary-foreign-keys, like 2 FK's as a PK in a M-to-N table, you will have an index on the PK and probably don't need to create any extra indexes. While it's usually a good idea to create an index on (or including) your referencing-side foreign key columns, it isn't required. Each index you add slows DML operations down slightly, so you pay a performance cost on every `INSERT`, `UPDATE` or `DELETE`. If the index is rarely used it may not be worth having.
This query will **list missing indexes on foreign keys**, [original source](https://github.com/pgexperts/pgx_scripts/blob/master/indexes/fk_no_index.sql). *Edit*: Note that it will not check small tables (less then 9 MB) and some other cases. See final `WHERE` statement. ``` -- check for FKs where there is no matching index -- on the referencing side -- or a bad index WITH fk_actions ( code, action ) AS ( VALUES ( 'a', 'error' ), ( 'r', 'restrict' ), ( 'c', 'cascade' ), ( 'n', 'set null' ), ( 'd', 'set default' ) ), fk_list AS ( SELECT pg_constraint.oid as fkoid, conrelid, confrelid as parentid, conname, relname, nspname, fk_actions_update.action as update_action, fk_actions_delete.action as delete_action, conkey as key_cols FROM pg_constraint JOIN pg_class ON conrelid = pg_class.oid JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid JOIN fk_actions AS fk_actions_update ON confupdtype = fk_actions_update.code JOIN fk_actions AS fk_actions_delete ON confdeltype = fk_actions_delete.code WHERE contype = 'f' ), fk_attributes AS ( SELECT fkoid, conrelid, attname, attnum FROM fk_list JOIN pg_attribute ON conrelid = attrelid AND attnum = ANY( key_cols ) ORDER BY fkoid, attnum ), fk_cols_list AS ( SELECT fkoid, array_agg(attname) as cols_list FROM fk_attributes GROUP BY fkoid ), index_list AS ( SELECT indexrelid as indexid, pg_class.relname as indexname, indrelid, indkey, indpred is not null as has_predicate, pg_get_indexdef(indexrelid) as indexdef FROM pg_index JOIN pg_class ON indexrelid = pg_class.oid WHERE indisvalid ), fk_index_match AS ( SELECT fk_list.*, indexid, indexname, indkey::int[] as indexatts, has_predicate, indexdef, array_length(key_cols, 1) as fk_colcount, array_length(indkey,1) as index_colcount, round(pg_relation_size(conrelid)/(1024^2)::numeric) as table_mb, cols_list FROM fk_list JOIN fk_cols_list USING (fkoid) LEFT OUTER JOIN index_list ON conrelid = indrelid AND (indkey::int2[])[0:(array_length(key_cols,1) -1)] @> key_cols ), fk_perfect_match AS ( SELECT fkoid FROM fk_index_match WHERE (index_colcount - 1) <= fk_colcount AND NOT has_predicate AND indexdef LIKE '%USING btree%' ), fk_index_check AS ( SELECT 'no index' as issue, *, 1 as issue_sort FROM fk_index_match WHERE indexid IS NULL UNION ALL SELECT 'questionable index' as issue, *, 2 FROM fk_index_match WHERE indexid IS NOT NULL AND fkoid NOT IN ( SELECT fkoid FROM fk_perfect_match) ), parent_table_stats AS ( SELECT fkoid, tabstats.relname as parent_name, (n_tup_ins + n_tup_upd + n_tup_del + n_tup_hot_upd) as parent_writes, round(pg_relation_size(parentid)/(1024^2)::numeric) as parent_mb FROM pg_stat_user_tables AS tabstats JOIN fk_list ON relid = parentid ), fk_table_stats AS ( SELECT fkoid, (n_tup_ins + n_tup_upd + n_tup_del + n_tup_hot_upd) as writes, seq_scan as table_scans FROM pg_stat_user_tables AS tabstats JOIN fk_list ON relid = conrelid ) SELECT nspname as schema_name, relname as table_name, conname as fk_name, issue, table_mb, writes, table_scans, parent_name, parent_mb, parent_writes, cols_list, indexdef FROM fk_index_check JOIN parent_table_stats USING (fkoid) JOIN fk_table_stats USING (fkoid) WHERE table_mb > 9 AND ( writes > 1000 OR parent_writes > 1000 OR parent_mb > 10 ) ORDER BY issue_sort, table_mb DESC, table_name, fk_name; ```
Postgres and Indexes on Foreign Keys and Primary Keys
[ "", "sql", "postgresql", "foreign-keys", "" ]
I am building a form to accept a time value HH:MM, how can I filter the user input and show the colon in the text field? I guess I'm looking for some kind of filtered input box.
Thats commonly referred to as an [Input Mask](http://en.wikipedia.org/wiki/Input_mask), do some [googling](http://www.google.com/search?q=jquery+input+mask) on it. Edit: There appears to be an [input mask jquery plugin](http://www.webappers.com/2008/04/22/jquery-masked-input-plugin/)
Whilst the TimePickr plugin [recommended by Jonathon](https://stackoverflow.com/questions/1038754/time-input-field/1038789#1038789) is very nice to look at, if the user is doing any volume of data entry, it's going to drive them mad. I answered a similar question a while back explaining why: > [jQuery time picker (StackOverflow)](https://stackoverflow.com/questions/476822/jquery-time-picker/476937#476937) A [masked input box](https://stackoverflow.com/questions/1038754/time-input-field/1038797#1038797) and a bit of javascript validation may be a more optimal solution.
Time Input Field
[ "", "javascript", "jquery", "html", "" ]
I was thinking, would it be feasible to create a Cocoa app that is essentially just a an interface with a web view? Or is there some serious limitation when doing something like this? If it is "feasible", would that also mean that you could do the same for Windows applications?
It's certainly possible to create an application that's just a Cocoa window with a web view inside it, sure. Whether that can meaningfully be called a "Cocoa app" is debatable. Obviously things like the app menu would require some Cocoa glue code, so yes, there are limits to how much you could do in just HTML and JS. You'd also have to think carefully about how you would handle localization (duplicating the entire HTML and JS source for each language isn't going to be desirable), and there are lots of interface constructs that would be much harder to create than they would be using Cocoa, and/or wouldn't feel native to someone used to the OS X look and feel. And you'll be giving up some performance by using an interpreted language, which may or may not matter for your application. There are applications for OS X that are built that way, and they generally feel like bad ports; if your goal is to make something that feels like a real Mac application, it's probably not a good way to go.
iPhone OS has fantastic facilities for making web apps act as first class citizens on the device. You can have your web apps icon added to the springboard just like a Cocoa App, you can store data locally and lots of other really neat stuff... Check out [these examples](http://www.apple.com/webapps/) or the [ADC documentation](http://developer.apple.com/safari/library/codinghowtos/Mobile/GraphicsMediaAndVisualEffects/index.html).
Can you write Cocoa apps with HTML/CSS and Javascript?
[ "", "javascript", "cocoa", "webkit", "webview", "" ]
I have a string build up like varstring1\_varstring2\_id1\_id2 eg: move\_user\_12\_2 . I want to extract id1 and id2 out of the string. Since I'm a complete prototype beginner I'm having some troubles solving this. Thanks Stijn
You could probably just use the built-in [string.split()](http://www.w3schools.com/jsref/jsref_split.asp) operator ``` var s = "move_user_12_2".split('_'); var id1 = s[2], id2 = s[3]; ```
If by prototype you mean the prototype javascript framework, then what you need is the [string.split](http://www.pageresource.com/jscript/jstring2.htm) method. So, in your case, the code would be something like ``` var myString = 'move_user_12_2'; var stringParts = myString.split('_'); var id1 = stringParts[2]; var id2 = stringParts[3]; ```
splitting string up
[ "", "javascript", "string", "" ]
I am consuming service of random.org, (I want to get the numbers from random.org site using url). I am fetching data using ajax from my JavaScript. So how to make cross domain ajax call from my domain (and avoid permission error)? I want solution without help of server side code (sever proxy). Example code will be great help for me.
Lobby the owner of random.org to provide a [jsonp](http://en.wikipedia.org/wiki/JSON#JSONP) API - that's the only way to make this happen.
Just sent an email to random.org and received this reply > Thanks for your email. Yes, I am working on a JSONP interface. > > Best regards, > > Mads
Cross domain ajax request from javascript file without help of server side code
[ "", "javascript", "ajax", "" ]
i'm trying to migrate some data from two tables in an OLD database, to a NEW database. The problem is that I wish to generate new Primary Key's in the new database, for the first table that is getting imported. That's simple. But the 2nd table in the old database has a foreign key dependency on the first table. So when I want to migrate the old data from the second table, the foreign key's don't match any more. Are there any tricks/best practices involved to help me migrate the data? Serious Note: i cannot change the current schema of the new tables, which do not have any 'old id' column. Lets use the following table schema :- ``` Old Table1 New Table1 ParentId INT PK ParentId INT PK Name VARCHAR(50) Name VARCHAR(50) Old Table 2 New Table 2 ChildId INT PK ChildId INT PK ParentId INT FK ParentId INT FK Foo VARCHAR(50) Foo VARCHAR(50) ``` So the table schema's are identical. Thoughts? ### EDIT: For those that are asking, RDBMS is Sql Server 2008. I didn't specify the software because i was hoping i would get an agnostic answer with some generic T-Sql :P
I think you need to do this in 2 steps. You need to import the old tables and keep the old ids (and generate new ones). Then once they're in the new database and they have both new and old ids you can use the old Id's to get associate the new ids, then you drop the old ids. You can do this by importing into temporary (i.e. they will be thrown away) tables, then inserting into the permanent tables, leaving out the old ids. Or import directy into the new tables (with schema modified to also hold old ids), then drop the old id's when they're no longer necessary. **EDIT:** OK, I'm a bit clearer on what you're looking for thanks to comments here and on other answers. I knocked this up, I think it'll do what you want. Basically without cursors it steps through the parent table, row by row, and inserts the new partent row, and all the child rows for that parent row, keeping the new id's in sync. I tried it out and it should work, it doesn't need exclusive access to the tables and should be orders of magniture faster than a cursor. ``` declare @oldId as int declare @newId as int select @oldId = Min(ParentId) from OldTable1 while not @oldId is null begin Insert Into NewTable1 (Name) Select Name from OldTable1 where ParentId = @oldId Select @newId = SCOPE_IDENTITY() Insert Into NewTable2 (ParentId, Foo) Select @newId, Foo From OldTable2 Where ParentId = @oldId select @oldId = Min(ParentId) from OldTable1 where ParentId > @oldId end ``` Hope this helps,
Well, I guess you'll have to determine other criteria to create a map like oldPK => newPK (for example: `Name` field is equal? Then you can determine the new PK that matches the old PK and adjust the `ParentID` accordingly. You may also do a little trick: Add a new column to the original Table1 which stores the new PK value for a copied record. Then you can easily copy the values of Table2 pointing them to the value of the new column instead of the old PK. **EDIT**: I'm trying to provide some sample code of what I meant by my little trick. I'm not altering the original database structure, but I'm using a temporary table now. OK, you might try to following: 1) Create temporary table that holds the values of the old table, plus, it gets a new PK: ``` CREATE TABLE #tempTable1 ( newPKField INT, oldPKField INT, Name VARCHAR(50) ) ``` 2) Insert all the values from your old table into the temporary table calculating a new PK, copying the old PK: ``` INSERT INTO #tempTable1 SELECT newPKValueHere AS newPKField, ParentID as oldPKField, Name FROM Table1 ``` 3) Copy the values to the new table ``` INSERT INTO NewTable1 SELECT newPKField as ParentId, Name FROM #tempTable1 ``` 4) Copy the values from Table2 to NewTable2 ``` INSERT INTO NewTable2 SELECT ChildID, t.newPKField AS ParentId, Foo FROM Table2 INNER JOIN #tempTable1 t ON t.ParentId = parentId ``` This should do. Please note that this is only pseudo T-SQL Code - I have not tested this on a real database! However, it should come close to what you need.
Stuck trying to migrate two tables from one DB to another DB
[ "", "sql", "sql-server", "migration", "" ]
Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract. Is it because: 1. Interface exists to have multiple inheritance 2. It makes sense to have interface because object's CAN-DO feature should be placed in an interface rather base abstract class. Please clarify
Well, an abstract class can specify *some* implemetation, but usually not all of it. (Having said which, it's perfectly possible to provide an abstract class with no abstract members, but plenty of virtual ones which with "no-op" implementations). An interface provides *no* implementation, merely a contract. You could certainly argue that if multiple inheritance of classes were permitted, interfaces would be largely pointless. Personally I don't get hung up on the whole "is-a" vs "can-do" distinction for inheritance. It never gives me as good an intuition about what to do as just playing around with different ideas and seeing which ones feel the most flexible. (Then again, I'm very much a "favour composition over inheritance" guy...) EDIT: Just as the most convenient way of rebutting lbushkin's third point in his comment... you can override an abstract method with a non-virtual one (in terms of not being able to override it further) by sealing it: ``` public abstract class AbstractBase { public abstract void Foo(); } public class Derived : AbstractBase { public sealed override void Foo() {} } ``` Classes deriving from `Derived` cannot override `Foo` any further. I'm not in any way suggesting I want multiple inheritance of implementation - but if we *did* have it (along with its complexity) then an abstract class which *just* contained abstract methods would accomplish *almost* everything that an interface does. (There's the matter of explicit interface implementation, but that's all I can think of at the moment.)
It's not a trivial question, it's a very good question and one I always ask any candidates I interview. In a nutshell - an abstract base class defines a type hierarchy whereas an interface defines a contract. You can see it as *is a* vs *implements a*. i.e `Account` could be an abstract base account because you could have a `CheckingAccount`, a `SavingsAccount`, etc all which derive from the abstract base class `Account`. Abstract base classes may also contain non abstract methods, properties and fields just like any normal class. However interfaces **only** contain abstract methods and properties that **must** be implemented. c# let's you derive from one base class only - single inheritance just like java. However you can implement as many interfaces as you like - this is because an interface is just a contract which your class promises to implement. So if I had a class `SourceFile` then my class could choose to implement `ISourceControl` which says 'I faithfully promise to implement the methods and properties that `ISourceControl` requires' This is a big area and probably worthy of a better post than the one I've given however I'm short on time but I hope that helps!
Why do both the abstract class and interface exist in C#?
[ "", "c#", ".net", "oop", "" ]
Much like [this question](https://stackoverflow.com/questions/39916/programmaticly-building-htpasswd/) I want to generate an htpasswd file entry from PHP. However it needs to be the APR1 (Apache) style, as mentioned in the original answer (The answer did not show how to implement the APR1 style), to work with mod\_dav\_svn. I can't seem to find a working implementation that will create the password. I found this (I forget where now): ``` function crypt_apr1_md5($plainpasswd) { $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8); $len = strlen($plainpasswd); $text = $plainpasswd.'$apr1$'.$salt; $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd)); for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); } for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; } $bin = pack("H32", md5($text)); for($i = 0; $i < 1000; $i++) { $new = ($i & 1) ? $plainpasswd : $bin; if ($i % 3) $new .= $salt; if ($i % 7) $new .= $plainpasswd; $new .= ($i & 1) ? $bin : $plainpasswd; $bin = pack("H32", md5($new)); } for ($i = 0; $i < 5; $i++) { $k = $i + 6; $j = $i + 12; if ($j == 16) $j = 5; $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp; } $tmp = chr(0).chr(0).$bin[11].$tmp; $tmp = strtr(strrev(substr(base64_encode($tmp), 2)), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); return "$"."apr1"."$".$salt."$".$tmp; } ``` But it doesn't generate a working password. I think this might be something to do with the version of apache but am not sure. (I am running on CENTOS 5)
It turns out I made a mistake and this function does in fact create working APR1 htpasswd entries. They do look different to the ones Apache creates but they do work.
Look for existing components that do it on sites like phpclasses.org. One example: <http://www.phpclasses.org/browse/package/5066.html>.
How to programmatically build an APR1-MD5 using PHP
[ "", "php", "apache", "md5", "mod-dav-svn", "" ]
I am trying to get it so when the mouse moves over the div it fades the image inside ``` function clickimage($imageid){ $("#image_"+imageid).hover(function(){ $(this).fadeTo("slow", 1.0); },function(){ $(this).fadeTo("slow", 0.6); }); } <div id='images_$imageid'> <a href='?tg=photos&photo=$imageid' onmouseover=\"javascript:clickimage('$imageid')\"> <img src='users/$ptgid/images/$iimg' width='100' height='100'/> </a> </div> ```
You would want to set the binding when the document loads, not every time the mouse hovers over the image. Also, I would create a class so that you can initialize the hover on each item ``` $(document).ready(function() { $(".image-hover-class").hover(function(){ $(this).find('img').fadeTo("slow", 1.0); },function(){ $(this).find('img').fadeTo("slow", 0.6); }); }); ``` For the link, you would do something like this: ``` <a class="image-hover-class" href="?tg=photos&photo=$imageid" \> <img src='users/$ptgid/images/$iimg' width='100' height='100'/> </a> ``` If you want to do the hover on the `div`, you could do this instead (but I recommend doing the hover on the `<a>` tag): ``` $(document).ready(function() { $(".image-hover-class").hover(function(){ $(this).find('a img').fadeTo("slow", 1.0); },function(){ $(this).find('a img').fadeTo("slow", 0.6); }); }); ``` For the div, you would do something like this: ``` <div class="image-hover-class"> <a href="?tg=photos&photo=$imageid" \> <img src='users/$ptgid/images/$iimg' width='100' height='100'/> </a> </div> ```
i dont see in the image element id attribute. when you do it ``` $("#image_"+imageid) ``` its try to find this id, add id=image\_".$imageid." to img
Fading image inside a div
[ "", "javascript", "jquery", "" ]
Is it possible to use the standard ASP.NET login control, but just ask the user for a password? I am using a template, but the runtime complains that; ``` Login1: LayoutTemplate does not contain an IEditableTextControl with ID UserName for the username. ``` My current thinking, is to add the control with `style="display:none;"` which seems lame. The existing project already uses FormsAuthentication, so plan B might be to roll my own Authentication method. **Update** I have a 2 step login process. Step 1: "Who are you?" and Step 2: "What is your password?"
I'd sure style it with display:none long before rolling my own.
What functionality do you want from the Login Control? I assume your rolling your own authentication mechanism? Are you really going to gain a lot by reusing the login control? If so set the style to display:none. **Edit** If you identify the user on a previous page why not show a disabled textbox with the username or part of the username in it? I've seen some banks do this where on the first page you put the login and maybee the state you live in, then it validates that, then shows you the first three characters of the login name, and your site key and asks for your password.
ASP.NET Login control without a Username
[ "", "c#", "asp.net", "login-control", "" ]
a webservice returns some data to me. The data is actually just raw HTML (so no XML header, or tags around it, but just a piece of html). ``` <div class="Workorders"> <div id="woo_9142" class="Workorder"> <span class="Workorder">S1005</span> <span class="Pn">30-2</span> <span class="Description">Cooling Fan</span> <span class="Shortages">3616-1 (SV)</span> <span class="Company">xxx</span> </div> <div id="woo_9143" class="Workorder"> <span class="Workorder">S1006</span> <span class="Pn">30-2</span> <span class="Description">Cooling Fan</span> <span class="Shortages">3616-1 (SV)</span> <span class="Company">xxx</span> </div> </div> ``` **If this were XML like so:** ``` <workorders> <workorder id="woo_9142"> <partnumber>30-2</partnumber> </workorder> </workorders> ``` **I could go like this in jQuery:** ``` $('/workorders/workorder', data).each(function() { //This would give every partnumber $('partnumber', this).text(); }); ``` **How can I parse the returned HTML (like described at the beginning)?** ``` myNamespace.onSuccess = function(request) { //request contains the raw html string returned from the server //How can I make this possible: $(request).find('div.Workorders div.Workorder').each(function() { //Do something with the Workorder DIV in 'this' }); } ```
something like ``` myNamespace.onSuccess = function(request) { $(request.responseText).filter('div.Workorder').each(function() { $('span.Pn', $(this)).text(); }); } ```
Have you tried adding the html to the dom, hiding it and then process it: ``` myNamespace.onSuccess = function(request) { var hidden = document.createElement ( 'div' ); hidden.id = 'hiddenel'; $("body").append ( hidden ); $("#hiddenel").css ( 'visibility', 'hidden' ); $("#hiddenel").html ( resp ); $("#hiddenel").find ( 'div.Workorders div.Workorder').each(function() { ..... }); } ```
Javascript / jQuery - Parse returned 'data' as HTML for further selecting?
[ "", "javascript", "jquery", "html", "ajax", "" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way? --- See [How do the .strip/.rstrip/.lstrip string methods work in Python?](https://stackoverflow.com/questions/40990694) for a specific explanation of what the first attempt is doing.
[`strip`](https://docs.python.org/library/stdtypes.html#str.strip) doesn't mean "remove this substring". `x.strip(y)` treats `y` as a set of characters and strips any characters in that set from both ends of `x`. On **Python 3.9 and newer** you can use the [`removeprefix`](https://docs.python.org/library/stdtypes.html#str.removeprefix) and [`removesuffix`](https://docs.python.org/library/stdtypes.html#str.removesuffix) methods to remove an entire substring from either side of the string: ``` url = 'abcdc.com' url.removesuffix('.com') # Returns 'abcdc' url.removeprefix('abcdc.') # Returns 'com' ``` The relevant Python Enhancement Proposal is [PEP-616](https://www.python.org/dev/peps/pep-0616/). On **Python 3.8 and older** you can use [`endswith`](https://docs.python.org/library/stdtypes.html#str.endswith) and slicing: ``` url = 'abcdc.com' if url.endswith('.com'): url = url[:-4] ``` Or a [regular expression](https://docs.python.org/library/re.html): ``` import re url = 'abcdc.com' url = re.sub('\.com$', '', url) ```
If you are sure that the string only appears at the end, then the simplest way would be to use 'replace': ``` url = 'abcdc.com' print(url.replace('.com','')) ```
How do I remove a substring from the end of a string (remove a suffix of the string)?
[ "", "python", "string", "" ]
Alright, I'm confused as hell. I have an object that I store in a session. I can add items to this object. Pretty simple so far. I initialize the object like this: ``` $template = new Template($mysqli); $_SESSION['template'] = serialize($template); ``` Now this should create a brand spanking new object and assign it to the session. I then have some code that adds items through an AJAX request. That code is as follows: ``` $template = unserialize($_SESSION['template']); $prodid = $_GET['product_id']; $template->addItem($prodid); echo var_dump($template->getItems()); $_SESSION['template'] = serialize($template); ``` Again, should be simple. Now here's the issue, that first bit of code is not resetting `$_SESSION['template']` while it should, so I get all the items I've added so far, reloading the page doesn't fix it. I found the file that's causing the mischief but I don't know what I can do about this. It's an include and it's required for different portions of the site to function. I'm adding functionality to the site, I don't think the owners would be please if I removed functionality. Here's the file: ``` <?php include_once( 'DBE.class.php' ) ; ################################################ # Function: Sessions_open # Parameters: $path (string), $name (string) # Returns: bool # Description: This is an over-ride function call # that we need to create so that the php internal # session manager doesn't store our session in the # file system, since we are storing it in the # db. Storing a session in a file system on the # server inhibits scalability for two reasons: # 1: A large number of users may be hitting the site # and clog the space on the hard-drive of the server # due to the sheer amount of session files stored # 2: The website may be behind a load-balancer and # therefore the server handling the page request # may not have the session stored on its file system ################################################ function Sessions_open ( $path, $name ) { return TRUE ; } ################################################ # Function: Sessions_close # Parameters: N/A # Returns: bool # Description: This is an over-ride function call # that we need to create so that the php internal # session manager doesn't store our session in the # file system, since we are storing it in the # db. Storing a session in a file system on the # server inhibits scalability for two reasons: # 1: A large number of users may be hitting the site # and clog the space on the hard-drive of the server # due to the sheer amount of session files stored # 2: The website may be behind a load-balancer and # therefore the server handling the page request # may not have the session stored on its file system ################################################ function Sessions_close () { return TRUE ; } ################################################ # Function: Sessions_read # Parameters: $SessionID (string) # Returns: (string) or (false) on error # Description: This function is used at startup to read # the contents of the session. # If no sess data, the empty string ("") is returned. # Otherwise, the serialized sess data is returned. # On error, false is returned. ################################################ function Sessions_read ( $SessionID ) { include_once( 'DBE.class.php' ) ; $dbe = new DBE() ; //default return value to false $returnVal = FALSE ; $query = "SELECT DataValue FROM Sessions WHERE SessionID = '$SessionID' " ; $result = $dbe->Select( $query ) ; if( count( $result ) == 1 ) { $returnVal = $result[0]['DataValue'] ; //update the session so that we don't time-out after creating $query = "UPDATE Sessions SET LastUpdated = NOW() WHERE SessionID = '$SessionID'" ; $dbe->Update( $query ) ; } else { //Insert here to simplify the write function $query = "INSERT INTO Sessions (SessionID, DataValue) VALUES ( '$SessionID', '' )" ; $dbe->Insert( $query ) ; //pass the insert stmt //set returnVal to '' being that we didn't find the SessionID $returnVal = '' ; } return( $returnVal ) ; } ################################################ # Function: Sessions_write # Parameters: $SessionID (string), $Data # Returns: bool # Description: This function is used at startup to read # the contents of the session. # If no sess data, the empty string ("") is returned. # Otherwise, the serialized sess data is returned. # On error, false is returned. ################################################ function Sessions_write( $SessionID, $Data ) { include_once( 'DBE.class.php' ) ; $dbe = new DBE() ; //default to true $returnVal = TRUE ; //update the session $query = "UPDATE Sessions SET DataValue = '$Data' WHERE SessionID = '$SessionID'" ; $result = $dbe->Update( $query ) ; //pass the update stmt to the dbEngine.. //test for success if( $result == -1 ) $returnVal = FALSE ; //return the return value return( $returnVal ) ; } ################################################ # Function: Sessions_delete # Parameters: $SessionID (string) # Returns: bool # Description: This function is used to delete the session ################################################ function Sessions_destroy( $SessionID ) { include_once( 'DBE.class.php' ) ; $dbe = new DBE() ; $query = "DELETE FROM Sessions WHERE SessionID = '$SessionID' " ; $dbe->Delete( $query ) ; return( TRUE ) ; } ################################################ # Function: Sessions_delete # Parameters: $SessionID (string) # Returns: bool # Description: This function is used to delete the session ################################################ function Sessions_gc( $aMaxLifetime ) { include_once( 'DBE.class.php' ) ; $dbe = new DBE() ; $query = "DELETE FROM Sessions WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP( LastUpdated )) > $aMaxLifetime " ; $dbe->Delete( $query ) ; return( TRUE ) ; } session_set_save_handler( "Sessions_open", "Sessions_close", "Sessions_read", "Sessions_write", "Sessions_destroy", "Sessions_gc" ) ; ?> ``` I think that this is changing the basic functionality of sessions, but I'm not quite sure. And that's causing my trouble with resetting the template in the session. Anyone have any ideas or know what I can do to fix this problem. I'm totally stumped so any help is greatly appreciated.
I'm not sure if that's the issue, but this is what jumps out when i read your code: Your serialized object relies on a mysql connection > $template = new Template($mysqli); while your object (maybe) can be serialized and un-serialized without problems, the mysql connection can't, so your un-serialized $template tries to operate on an invalid connection/file handle. You can try re-attaching your un-serialized object to a valid db connection. Without knowing what's inside your Template class (and what resources it uses and how) it's hard to guess what's wrong but I hope this is a good enough clue on where to start looking. To give you a better idea of what I'm talking about, consider this: # template.php ``` <?php class Template { function __construct($c) { $this->conn = $c; $this->foo = "bar"; } function get_data() { $result = mysql_query("select 1234 as test", $this->conn); $data = mysql_fetch_array($result); return $data; } function attach_db($c) { $this->conn = $c; } } ?> ``` # first.php ``` <?php session_start(); require('template.php'); $conn = mysql_connect('localhost', 'root', ''); $template = new Template($conn); ?> <pre> Your $template var, freshly created: <?php var_dump($template); ?> Accessing the resources: <?php var_dump($template->get_data()); ?> <?php $_SESSION['template'] = serialize($template); ?> </pre> ``` # other.php ``` <?php session_start(); require('template.php'); $template = unserialize($_SESSION['template']); ?> <pre> Unserialized $template: <?php var_dump($template); ?> (notice that $template->foo === "bar" so your session un/serialization is working correctly) Accessing the (now invalid) mysql resources: <?php var_dump($template->get_data()); ?> </pre> ``` Calling first.php should give you this: > Your $template var, freshly created: > object(Template)#1 (2) { > ["conn"]=> > resource(3) of type (mysql link) > ["foo"]=> > string(3) "bar" > } > > Accessing the resources: > array(2) { > [0]=> > string(4) "1234" > ["test"]=> > string(4) "1234" > } Calling others.php should result in: > Unserialized $template: > object(Template)#1 (2) { > ["conn"]=> > int(0) > ["foo"]=> > string(3) "bar" > } > (notice that $template->foo === "bar" so your session un/serialization is working correctly) > > Accessing the (now invalid) mysql resources: > > Warning: mysql\_query(): supplied argument is not a valid MySQL-Link resource in template.php on line 9 > > Warning: mysql\_fetch\_array(): supplied argument is not a valid MySQL result resource in template.php on line 10 > > bool(false) To solve that you can re-create the resources that cannot be un/serialized. Like this: # solution.php ``` <?php session_start(); require('template.php'); $template = unserialize($_SESSION['template']); ?> <pre> Unserialized $template: <?php var_dump($template); ?> Attaching a valid db connection: <?php $conn = mysql_connect('localhost', 'root', ''); $template->attach_db($conn); var_dump($template); ?> Accessing the resources: <?php var_dump($template->get_data()); ?> </pre> ``` Now, calling solution.php after having called first.php should give you this: > Unserialized $template: > object(Template)#1 (2) { > ["conn"]=> > int(0) > ["foo"]=> > string(3) "bar" > } > > Attaching a valid db connection: > object(Template)#1 (2) { > ["conn"]=> > resource(3) of type (mysql link) > ["foo"]=> > string(3) "bar" > } > > Accessing the resources: > array(2) { > [0]=> > string(4) "1234" > ["test"]=> > string(4) "1234" > } As I said, without knowing what your template class does, it's not possible to say for sure what's happening.. this is just one possibility ;) Good luck!
Looks like they're overriding the standard session handler to store session data in the DB. Have a look in the Sessions table and check that your serialised object is being stored correctly.
PHP Session Confusion
[ "", "php", "session", "class", "" ]
I'm trying to make work the example from hibernate reference. I've got simple table Pupil with id, name and age fields. I've created correct (as I think) java-class for it according to all java-beans rules. I've created configuration file - hibernate.cfg.xml, just like in the example from reference. I've created hibernate mapping for one class Pupil, and here is the error occured. ``` <hibernate-mapping> <class name="Pupil" table="pupils"> ... </class> </hibernate-mapping> ``` table="pupils" is red in my IDE and I see message "cannot resolve table pupils". I've also founded very strange note in reference which says that most users fail with the same problem trying to run the example. Ah.. I'm very angry with this example.. IMHO if authors know that there is such problem they should add some information about it. But, how should I fix it? I don't want to deal with Ant here and with other instruments used in example. I'm using MySql 5.0, but I think it doesn't matter. UPD: source code Pupil.java - my persistent class ``` package domain; public class Pupil { private Integer id; private String name; private Integer age; protected Pupil () { } public Pupil (String name, int age) { this.age = age; this.name = name; } public Integer getId () { return id; } public void setId (Integer id) { this.id = id; } public String getName () { return name; } public void setName (String name) { this.name = name; } public Integer getAge () { return age; } public void setAge (Integer age) { this.age = age; } public String toString () { return "Pupil [ name = " + name + ", age = " + age + " ]"; } } ``` Pupil.hbm.xml is mapping for this class ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="domain" > <class name="Pupil" table="pupils"> <id name="id"> <generator class="native" /> </id> <property name="name" not-null="true"/> <property name="age"/> </class> </hibernate-mapping> ``` hibernate.cfg.xml - configuration for hibernate ``` <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hbm_test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <mapping resource="domain/Pupil.hbm.xml"/> </session-factory> </hibernate-configuration> ``` HibernateUtils.java ``` package utils; import org.hibernate.SessionFactory; import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration ().configure ().buildSessionFactory (); } catch (HibernateException he) { System.err.println (he); throw new ExceptionInInitializerError (he); } } public static SessionFactory getSessionFactory () { return sessionFactory; } } ``` Runner.java - class for testing hibernate ``` import org.hibernate.Session; import java.util.*; import utils.HibernateUtils; import domain.Pupil; public class Runner { public static void main (String[] args) { Session s = HibernateUtils.getSessionFactory ().getCurrentSession (); s.beginTransaction (); List pups = s.createQuery ("from Pupil").list (); for (Object obj : pups) { System.out.println (obj); } s.getTransaction ().commit (); HibernateUtils.getSessionFactory ().close (); } } ``` My libs: antlr-2.7.6.jar, asm.jar, asm-attrs.jar, cglib-2.1.3.jar, commons-collections-2.1.1.jar, commons-logging-1.0.4.jar, dom4j-1.6.1.jar, hibernate3.jar, jta.jar, log4j-1.2.11.jar, mysql-connector-java-5.1.7-bin.jar > Compile error: cannot resolve table pupils
This has nothing to do with Hibernate, this is an IDEA "issue" and you need to configure it properly for tables names validation in hbm.xml. From [this old thread](http://www.jetbrains.net/devnet/thread/280137): > In order for IntelliJ to provide > proper code completion and validation > for database tables/columns, it needs > to know about the database > structure of your application as well. > So, I'm referring to the > IntelliJ datasource. Think of it as a > "development-time datasource", > or something like that. > > To create one: > Window -> Tool Windows -> Data sources > Add ("plus" icon) -> JDBC data source > > As an alternative, you could try the > "Import" button in the "Date > sources" tool window. This makes > IntelliJ search your project for some > specific configuration files (like > "hibernate.cfg.xml"), from which it > can directly import a datasource > definition. > > However, if that fails, you can always > define a JDBC data source > manually (jdbc url, driver jar, driver > class, etc). > > Once you have a datasource configured, > test it by opening an SQL console > on it ("console" button in datasource > tool window), and type some > queries. IDEA should provide SQL code > completion here, for table and > column names. > > If this step works, go to the > definition of the datasource, and > invoke > > "Refresh Tables". This makes IntelliJ > retrieve the database structure. > > Next, open "Project Structure" > (Ctrl-Shift-Alt-S). > Select your Hibernate facet (though > either "Facets" or "Modules"). > > The options screen for the Hibernate > facet has a pane named "DataSources > Mapping". Here you can associate your > Hiberante session factory with a > specific IntelliJ datasource. > > After this step, SQL table/column code > completion and validation should > work in .hbm files as well. Applies to IDEA 7 also, read the whole thread if necessary.
To validate a hbm.xml file mappings, just do the following (Intellij Ultimate 2017.1): ``` View -> Tool Windows -> Database -> click (+) sign -> Data Source -> MySQL ``` You've added a datasource for your database's server. Now you should create the datasource. The next step is adding this datasource to hibernate mappings. Just follow me: ``` View -> Tool Windows -> Persistence ``` The Persistence window will be opened. You must see the project listed. ``` Right click on the project -> Assign Data Sources... ``` In the opened window, there should be 2 columns: "Session Factory" and "Data Source". Just add defined datasource above in the second column.
Hibernate error: cannot resolve table
[ "", "java", "hibernate", "intellij-idea", "mapping", "" ]
How can I test if a letter in a string is uppercase or lowercase using JavaScript?
The answer by josh and maleki will return true on both upper and lower case if the character or the whole string is numeric. making the result a false result. example using josh ``` var character = '5'; if (character == character.toUpperCase()) { alert ('upper case true'); } if (character == character.toLowerCase()){ alert ('lower case true'); } ``` another way is to test it first if it is numeric, else test it if upper or lower case example ``` var strings = 'this iS a TeSt 523 Now!'; var i=0; var character=''; while (i <= strings.length){ character = strings.charAt(i); if (!isNaN(character * 1)){ alert('character is numeric'); }else{ if (character == character.toUpperCase()) { alert ('upper case true'); } if (character == character.toLowerCase()){ alert ('lower case true'); } } i++; } ```
The problem with the other answers is, that some characters like numbers or punctuation also return true when checked for lowercase/uppercase. I found this to work very well for it, e.g. "3" will now return false ("3" is lowerCase by default) however consider to filter out numbers with isNaN() and make sure it's actually a string you're testing. Here the code: ``` function isLowerCase(str) { return str === str.toLowerCase() && str !== str.toUpperCase(); } ``` This will work for punctuation, numbers and letters: ``` assert(isLowerCase("a")) assert(!isLowerCase("Ü")) assert(!isLowerCase("4")) assert(!isLowerCase("_")) ``` To check one letter just call it using `isLowerCase(str[charIndex])`
How can I test if a letter in a string is uppercase or lowercase using JavaScript?
[ "", "javascript", "" ]
As we all know Javascript is a client side language , means code runs on client side and not on server side.Now what I want to know is that then how come getDate() retrives the server side value. ``` var myDate = new Date(); alert(myDate.getDate());//return current date. ```
In your code it doesn't. There is the possibility of setting the Date value with information from the server (ajax, or writing the information to the page on loading) and then it would show the server date. This would obviously require extra code.
This is definitely not the case. Your code will put the current day of the month in an alert box, using the date of the machine you're running the code on (i.e. the client). At least in a web page, anyway. Are you running the code some other way?
Date Object in javascript
[ "", "javascript", "" ]
Say I have a very simple XML with an empty tag 'B': ``` <Root> <A>foo</A> <B></B> <C>bar</C> </Root> ``` I'm currently using XSLT to remove a few tags, like 'C' for example: ``` <?xml version="1.0" ?> <xsl:stylesheet version="2.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="no" encoding="utf-8" omit-xml-declaration="yes" /> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> <xsl:template match="C" /> </xsl:stylesheet> ``` So far OK, but the problem is I end up having an output like this: ``` <Root> <A>foo</A> <B/> </Root> ``` when I actually really want: ``` <Root> <A>foo</A> <B></B> </Root> ``` Is there a way to prevent 'B' from collapsing? Thanks.
Ok, so here what worked for me: ``` <xsl:output method="html"> ```
Try this: ``` <script type="..." src="...">&#160;</script> ``` Your HTML output will be: ``` <script type="..." src="..."> </script> ``` The `&#160;` prevents the collapsing but translates to a blank space. It's worked for me in the past.
How to preserve Empty XML Tags after XSLT - prevent collapsing them from <B></B> to <B/>
[ "", "java", "xml", "xslt", "" ]
I would like to print an image of a dialog, as if [alt][Print Scrn] were used. Does the framework allow for this to be done programmatically?
The [Graphics.CopyFromScreen(..)](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.copyfromscreen.aspx) method should do what you need. Here's a good sample I found on the web: <http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html> **EDIT:** Code sample: (I created it as an extension method) ``` public static class FormExtensions { public static void SaveAsImage(this Form form, string fileName, ImageFormat format) { var image = new Bitmap(form.Width, form.Height); using (Graphics g = Graphics.FromImage(image)) { g.CopyFromScreen(form.Location, new Point(0, 0), form.Size); } image.Save(fileName, format); } } ``` can be used: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.SaveAsImage("foo.bmp", ImageFormat.Bmp); } } ```
What you could probably do is use the existing DLL that has that functionality for windows. It looks like you need to grab either some key commands or do it with a form button, and use the User32.dll. Since interop can sometimes be a big pain, I found a resource here that might help you do what you want: <http://www.cornetdesign.com/2005/04/screen-print-capture-in-c-using_08.html>
.NET 2.0 WinForm print screen
[ "", "c#", ".net", "winforms", "printing", "" ]
Question: is there a better way to do that? VB.Net ``` Function GuidToBase64(ByVal guid As Guid) As String Return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "") End Function Function Base64ToGuid(ByVal base64 As String) As Guid Dim guid As Guid base64 = base64.Replace("-", "/").Replace("_", "+") & "==" Try guid = New Guid(Convert.FromBase64String(base64)) Catch ex As Exception Throw New Exception("Bad Base64 conversion to GUID", ex) End Try Return guid End Function ``` C# ``` public string GuidToBase64(Guid guid) { return Convert.ToBase64String(guid.ToByteArray()).Replace("/", "-").Replace("+", "_").Replace("=", ""); } public Guid Base64ToGuid(string base64) { Guid guid = default(Guid); base64 = base64.Replace("-", "/").Replace("_", "+") + "=="; try { guid = new Guid(Convert.FromBase64String(base64)); } catch (Exception ex) { throw new Exception("Bad Base64 conversion to GUID", ex); } return guid; } ```
I understand that the reason you are clipping == in the end is that because you can be certain that for GUID (of 16 bytes), encoded string will *always* end with ==. So 2 characters can be saved in every conversion. Beside the point @Skurmedal already mentioned (should throw an exception in case of invalid string as input), I think the code you posted is just good enough.
You might want to check out this site: [http://prettycode.org/2009/11/12/short-guid/](http://web.archive.org/web/20100408172352/http://prettycode.org/2009/11/12/short-guid/) It looks very close to what you're doing. ``` public class ShortGuid { private readonly Guid guid; private readonly string value; /// <summary>Create a 22-character case-sensitive short GUID.</summary> public ShortGuid(Guid guid) { if (guid == null) { throw new ArgumentNullException("guid"); } this.guid = guid; this.value = Convert.ToBase64String(guid.ToByteArray()) .Substring(0, 22) .Replace("/", "_") .Replace("+", "-"); } /// <summary>Get the short GUID as a string.</summary> public override string ToString() { return this.value; } /// <summary>Get the Guid object from which the short GUID was created.</summary> public Guid ToGuid() { return this.guid; } /// <summary>Get a short GUID as a Guid object.</summary> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.FormatException"></exception> public static ShortGuid Parse(string shortGuid) { if (shortGuid == null) { throw new ArgumentNullException("shortGuid"); } else if (shortGuid.Length != 22) { throw new FormatException("Input string was not in a correct format."); } return new ShortGuid(new Guid(Convert.FromBase64String (shortGuid.Replace("_", "/").Replace("-", "+") + "=="))); } public static implicit operator String(ShortGuid guid) { return guid.ToString(); } public static implicit operator Guid(ShortGuid shortGuid) { return shortGuid.guid; } } ```
guid to base64, for URL
[ "", "c#", ".net", "vb.net", "guid", "base64", "" ]
I am currently taking a c++ course and trying to get a deep understanding of the whole thing. I came up with some theories, it would be great if somebody could confirm them: Every variable (local,global,staic,member and non-member) is guaranteed to have its ctor called before first use The ctors of primitives like int are essentially no-ops, so we have explicitly assign a value, there is no default zero value. the following classes are semantically the same (and should generate identical code) ``` class A { int n; }; ``` and ``` class A { int n; public: A() : n() {} }; ``` and ``` class A { int n; public: A() { n = int(); } }; ``` The variable n is in every case still uninitialized. EDIT: It seem that I absolutetly underestimated the complexity of this subject, most of my assumptions were wrong. Now Iam still trying to find out the basic rules of object initialisation.
You might find [this](http://unixjunkie.blogspot.com/2009/05/c-new-foo-vs-new-foo.html) interesting. > The difference between new Foo and new > Foo() is that former will be > uninitialized and the latter will be > default initialized (to zero) when Foo > is a POD type. So, when not using the > form with the parens, the member "a" > can contain garbage, but with the > parens "a" will always be initialized > to 0.
I'm afraid you are wrong. When you say: ``` int n = int(); ``` Then n (and all other POD types) will zero initialised. Also, make sure that you are very clear in your mind about the difference between initialisation and assignment - this is quite important in C++: ``` int n = int(); // initialisation n = 0; // assignment ```
Variable initialising and constructors
[ "", "c++", "variables", "constructor", "initialization", "" ]
Is there any easy way to identify the file initially handling the request, ignoring get arguments and handling (at least basic) mappings like `/` to `/index.php`? Ideally what I'm looking for is something like `$_SERVER['REQUEST_URI']`, except it returns the same value regardless of the get arguments and that value is the file requested, not the URI, nor the currently executing file (`$_SERVER['PHP_SELF']`). In other words, a `$_SERVER['REQUESTED_FILE']` or something. I haven't seen anything like that. Does it exist, or do I need to write something manually? **Update** Here are some example URLs paired with what I would like the result to be: ``` example.com/mypage.php : /mypage.php example.com/ : /index.php example.com/foo/?hello=world : /foo/index.php ``` And these return values are true even in included files. See my answer below before answering, I think I've found what I was looking for.
I decided to test it out myself. The `$_SERVER['SCRIPT_NAME']` variable serves up the path to the requested file, even if it's an index file, and without get parameters or anything else. The PHP documentation states this contains the *path* of the file, but it seems to be relative to the document root, just like `PHP_SELF`, but without the security vulnerability. Here is the code I used to test this: <https://gist.github.com/dimo414/5484870> The output when requesting `example.com/?foo=bar`: ``` __FILE__: /var/www/index.php PHP_SELF: /index.php SCRIPT_NAME: /index.php REQUEST_URI: /?foo=bar parse_url(REQUEST_URI): / __FILE__: /var/www/pathtest.php PHP_SELF: /index.php SCRIPT_NAME: /index.php REQUEST_URI: /?foo=bar parse_url(REQUEST_URI): / ``` And the output when requesting `example.com/index.php/<strong>XSS</strong>`: ``` __FILE__: /var/www/index.php PHP_SELF: /index.php/XSS # note the XSS exploit (this is bold in browser) SCRIPT_NAME: /index.php # No exploit here REQUEST_URI: /index.php/%3Cstrong%3EXSS%3C/strong%3E parse_url(REQUEST_URI): /index.php/%3Cstrong%3EXSS%3C/strong%3E __FILE__: /var/www/pathtest.php PHP_SELF: /index.php/XSS SCRIPT_NAME: /index.php REQUEST_URI: /index.php/%3Cstrong%3EXSS%3C/strong%3E parse_url(REQUEST_URI): /index.php/%3Cstrong%3EXSS%3C/strong%3E ``` As you can see, `$_SERVER['SCRIPT_NAME']` always gives back the file that originally handled the request, i.e. the file in the URL, without any XSS risks.
``` $_SERVER['PHP_SELF'] ``` Should return the actual script. But there are [various methods](http://blog.taragana.com/index.php/archive/understanding-_serverphp_self-php_self-_serverrequest_uri-and-_serverscript_name-in-php-and-when-to-use-what/). I had a better link to a matrix of all the various file-related environment variables but I can't find it. I'll edit if it turns up. Edit: I found [a nice SO thread that details the differences between them](https://stackoverflow.com/questions/279966/phpself-vs-pathinfo-vs-scriptname-vs-requesturi).
How To Identify The Requested Page In PHP
[ "", "php", "" ]