Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Notice how for every image that google indexes it has a small [thumbnail](http://images.google.com/images?q=jeff+atwood). These thumbnails are: 1. Less than 10KB in size. 2. The proportions of the width / height are the same as the ones in the original image. I would like to write a function (in python) that would take an image and create a thumbnail with these to properties. EDIT: So there are 3 answers right now and all of them are half right. I need a function that not only resizes the image proportionally, but also makes sure the file size is smaller than 10KB. How do I do that?
In [this short post](http://mail.python.org/pipermail/python-list/2005-August/338139.html), Mike Fletcher and the effbot show (and discuss detailed variation) an excellent approach for the task you want to do. **Edit**: as for the 10K requirement, it's hard (to say the least;-) to predict how well an image will compress, depending on the image's format, since today's compression algorithms are so subtle. If you want your thumbnail to be just about as large (in pixels) as feasible while respecting a <10K requirement, you may have to use a "trial and error" approach making successively more refined guesses about the scaling factor, until you reach an acceptable result. For example, here's a "binary search" approach to getting the correct size (there may well be better strategies!), with ample print statements &c to explain what's going on...: ``` import Image import cStringIO import math import os import stat # try no more than 10 times, then give up MAX_TRIES = 10 def getThumbnail(filename, max_bytes=(10*1024)): '''Get a thumbnail image of filename, <max_bytes''' original_size = os.stat(filename)[stat.ST_SIZE] print "Original file size: %.1f KB" % (original_size/1024.) image = Image.open(filename) image.load() print "Original image size: %dx%d pixels" % image.size min_bytes = int(0.9 * max_bytes) largest_side = max(image.size) smallest_side = 16 for attempt in range(MAX_TRIES): try_side = (largest_side + smallest_side) / 2 print "Attempt #%d of %d" % (attempt+1, MAX_TRIES) print "Side must be within [%d:%d], now trying %d" % ( smallest_side, largest_side, try_side) thumb = image.copy() thumb.thumbnail((try_side,try_side), Image.ANTIALIAS) afile = cStringIO.StringIO() thumb.save(afile, "PNG") resulting_size = len(afile.getvalue()) afile.close() print "Reduced file size: %.1f KB" % (resulting_size/1024.) print "Reduced image size: %dx%d pixels" % thumb.size if min_bytes <= resulting_size <= max_bytes: print "Success!" return thumb elif resulting_size > max_bytes: print "Too large (>%d), reducing more" % max_bytes largest_side = try_side else: print "Too small (<%d), reducing less" % min_bytes smallest_side = try_side print "too many attempts, returning what I've got!" return thumb def main(): thumb = getThumbnail("pyth.png") print "Reduced image size: %dx%d pixels" % thumb.size print "Saving to thumb.png" thumb.save("thumb.png") thumb_size = os.stat("thumb.png")[stat.ST_SIZE] print "Reduced file size: %.1f KB" % (thumb_size/1024.) print "Done, bye!" if __name__ == '__main__': main() ```
Did you read the [PIL documentation](http://www.pythonware.com/library/pil/handbook/image.htm)? There is an image.thumbnail method.
Generating an image thumbnail that is <10KB and did not lose proportions
[ "", "python", "image-processing", "python-imaging-library", "" ]
I am looking for help with the database scheme, not the actual "cloud" itself. In a site where users submit images and can tag images, how should the database be setup for optimal performance? I was thinking ``` ID - int(11), unique, auto_incremenet tag - varchar(20) imageID - int(11) ``` so suppose i upload an image, and tag it "toronto, sushi, summer". query would be: ``` INSERT INTO tags (tag, imageID) VALUES ('$tag[0]', $imageID); INSERT INTO tags (tag, imageID) VALUES ('$tag[1]', $imageID); INSERT INTO tags (tag, imageID) VALUES ('$tag[2]', $imageID); ``` Then to retrieve, i'd select \* from tags where imageID = $imagID. Is there a flaw with this?
You should have a HABTM(has and belongs to many) relationship between two tables one for the images, one for the tags, and a third table with combinations of image ids and tag ids. This way you do not limit the number of tags that a image can have or number of images a tag can belong to and you do not have duplication.
I don't see any real problems with this approach other than images that share the same tag have duplicate entries in the database. If you try to normalize though, you end up with a table that contains duplicate references to another table that holds the tags themselves, which in this case seems like a waste of time (coding, joining and traversing tables for MySQL). One tiny optimization I'd consider though is the order of your columns. Group the 'int's together, as they are fixed width for MySQL meaning they can be searched marginally faster in that order than int varchar int.
PHP Tag Cloud
[ "", "php", "tags", "cloud", "" ]
I am using the following method to reverse geocode a google maps latlng: ``` [GClientGeocoder.getLocations(address:String, callback:function)][1] ``` Which states as follows: As this method requires a call to a Google server, you must also pass a callback method to handle the response. This response will contain a Status code, and if successful, one or more Placemark objects. Can anyone point me to a definitive reference of what a Placemark object is as it seems to return different attributes for different locations. e.g. sometimes I get a ThoroughfareName and others an AddressLine. I would like to understand if I will always get one or other of them and whether they are interchangeable.
[This page](http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured) is from the Google Maps API documentation, and contains a pretty straightforward explanation of what a **Placemark** object is. However, the part you probably want to focus on is where it states what format Google uses for the **AddressDetails** object in a **Placemark**, which is **xAL (eXtensible Address Language)**. There is a link to the spec there, which leads to a downloadable schema (xsd file), which essentially defines the entire format. A word of warning: the spec is pretty extensive, but you may not need to worry about a great deal of it for your project. EDIT: Apologies for not being allowed to add links to the relevant pages for you.
You have to hunt for it, but Google does in fact have [some documentation about Placemarks](http://code.google.com/apis/maps/documentation/geocoding/index.html#ReverseGeocoding) hidden away.
Definitive reference for Google Maps Placemark object
[ "", "javascript", "google-maps", "geocoding", "" ]
I need to provide a utility on a PHP site for a client to upload files to an amazon S3 bucket. Are there any open source utilities available that I can use? ideally, this utility would allow the client to select a local file, press the upload button, and then would tell him the URL of the newly uploaded file. Bonus points if this can provide a list of existing files to browse through. Thanks! *Edit:* This isn't exactly what I'm looking for, but it certainly works as a workaround for now. <http://s3browse.com/>
The workaround you're using requires sharing your secret key with a 3rd party web site. Which is highly insecure and simply bad practice. Why not use S3fm? <http://s3.amazonaws.com/s3fm/index.html> Online, secure, convenient. Runs directly from Amazon S3 - no need to share your secret keys with anyone.
**UPDATE (july 2014)**: Here is the new official AWS SDK for PHP: * Github repository: <https://github.com/aws/aws-sdk-php> * Documentation: <http://docs.aws.amazon.com/aws-sdk-php/guide/latest/index.html> --- Amazon provides a PHP SDK for accessing AWS services, including S3. See on github: [amazonwebservices/aws-sdk-for-php](https://github.com/amazonwebservices/aws-sdk-for-php) See documentation: [AWS SDK for PHP](http://docs.amazonwebservices.com/AWSSDKforPHP/latest/), very well done, with a lot of examples.
Amazon S3 interface with PHP?
[ "", "php", "amazon-s3", "" ]
I had written an event handler for MouseMove for my form but When I add a panel to form, this handler does NOT run while mouse moves on panel. I added event handler to panel and this works but I had several panels on the form, is there an easier solution?
You could Implement IMessageFilter to pre-process messages that are going to your controls. <http://blogs.msdn.com/csharpfaq/archive/2004/10/20/245412.aspx> However, I don't think this is a very clean way to do things from a design perspective.
Unfortunately, WinForms doesn't support event bubbling. But you can write some code to ease the task of hooking up events. ``` public void AssignMouseMoveEvent(Form form) { foreach(Control control in form.Controls) { if(! (control is Panel)) continue; control.MouseMove += PanelMouseMove; } } ``` You should call the above code passing it your current form and it will assign PanelMouseMove as event handler for MouseMove event of all the panels.
Controls hide event's of form in C# Windows program
[ "", "c#", "" ]
i am generating **\*.reg** file using code which will have some important data. and user will save this into registry. upon application launch i am getting the values from registry and performing some validation.. but the problem is that in registry and in **\*.reg** file the information are stored in plain text. how can i create encrypted **\*.reg** file first. then in application start. how to decrypt the value(encrypted) from registry.. i read some articles. but they are related to encryption/decryption of file. here i am working with "\*.reg" file and Registry itself
Sorry Mohsan, that's the wrong way. d. showed the right way. Just imagine if you encrypt a .reg file. What should happen afterwards?? You'll like to import it into the registry, but before you can you have to decrypt it and so just plain text comes into registry which can be read be everyone. So don't encrypt your key or value names. Encrypt the content of your values within the registry. So your program can read it in, decrypt it and work with it. Here is an example: ``` [HKLM\Key\SubKey\SubSubKey\etc] @="" "Password"="KALSDJLSIWNKLDNISNDLKWDNLAW" ``` So you program opens the key, reads the value and computes the decrypt algorithm on that value, resolving it to: 'My Secret Password'
If your program is the only one that is reading the values from the registry you can save them encrypted and decrypt them on every use. This way the exported .reg file is going to contain encrypted data too. If there are other programs using the data you must ensure they can access and understand the information they need.
Encrypt Registry Contents
[ "", "c#", "encryption", "registry", "" ]
I try to do the same thing as Davs Rants Example : <http://blog.davglass.com/files/yui/tab3/> But I must forget something... I have this error : > Node was not found" code: "8 [Break on > this error] > this.\_tabParent.removeChild( > tab.get(ELEMENT) ); Here my code : ``` function onGenePubmedSubmit() { var contentCur = document.getElementById("curatedquery"); var contentValue = contentCur.value; // New tabView widget var tabView = new YAHOO.widget.TabView('tvcontainer'); // Define label and content var labelText = nameReq + '<span class="close">X</span>'; var tabcontainer = idReq; var content = "<div id="+tabcontainer+"></div>"; // Add new tab - work well ! if (labelText && content) { tabView.addTab( new YAHOO.widget.Tab({ label:labelText, content:content, id: 'pubmedView', active:true })); } // Define DataTable myPubmedListTable Columns var myColumnDefsPubmed = [ {key:"pmid", label:"PMID", sortable:true}, {key:"articletitle", label:"Article Title", sortable:true}, {key:"abstract", label:"Abstract", sortable:true}, {key:"authorlist", label:"Authorlist", sortable:true}, {key:"medline", label:"Medline", sortable:true} ]; // Define DataSource var myDataSourcePubmed = new YAHOO.util.DataSource("qct-list-article.html"); myDataSourcePubmed.responseType = YAHOO.util.DataSource.TYPE_JSON; myDataSourcePubmed.connXhrMode = "queueRequests"; myDataSourcePubmed.responseSchema = { resultsList: "articleItemList", fields: ["pmid","articletitle","abstract","authorlist","medline"] }; // myPubmedListTable config var oConfigsPubmed = { initialRequest: '?term='+ contentValue, selectionMode: "single" }; // Create new DataTable - myPubmedListTable var myPubmedListTable = new YAHOO.widget.DataTable(idReq, myColumnDefsPubmed, myDataSourcePubmed,oConfigsPubmed); // Show myPubmedListTable myPubmedListTable.onShow(); // Remove tab on tabView ----------- this part don't work---------- ! YAHOO.util.Event.on(tabView.getElementsByClassName('close')[0], 'click', function(ev) { YAHOO.util.Event.stopEvent(ev); // some test - but don't work ! // tabView.set('activeTab', tabView.get('tabs')[0]); // tabView.set('activeIndex', 1); // tabView.removeTab(tabView.get("activeTab")); tabView.removeTab(tabView); }); } ``` Can someone help me ? What I missing? Thank you.
I found a solution that works, and I added a paginator. ``` function onGenePubmedSubmit() { var contentCur = document.getElementById("curatedquery"); var contentCurValue = contentCur.value; var tabView = new YAHOO.widget.TabView('tvcontainer'); var labelText = nameReq + '<span class="close">X</span>'; var tabcontainer = idReq; var content = "<div id="+tabcontainer+"></div>"; if (labelText && content) { var ctabView = new YAHOO.widget.Tab({ label:labelText, content:content, id: 'pubmedView'+idReq, active:true }); } YAHOO.util.Event.on(ctabView.getElementsByClassName('close')[0], 'click', function(ev) { YAHOO.util.Event.stopEvent(ev); // Verify if Tab to remove is curently the activ Tab if (tabView.get('activeTab')==ctabView) { // We activate the first Tab tabView.set('activeTab', tabView.get('tabs')[0]); } // If Tab to remove not activ Tab else if (tabView.get('activeTab')!=ctabView) { // We set the index of the Tab that is currently active in the TabView. tabView.set('activeIndex',tabView.get('activeIndex')); } tabView.removeTab(ctabView); }); // Verify if tab exist (or not) var tabExist = document.getElementById('pubmedView'+idReq); if (tabExist == null) { tabView.addTab(ctabView); } else { alert("Tab already exist") ; } // Define DataTable myPubmedListTable Columns var myColumnDefsPubmed = [ {key:"pmid", label:"PMID", sortable:true}, {key:"articletitle", label:"Article Title", sortable:true}, {key:"abstract", label:"Abstract", sortable:true}, {key:"authorlist", label:"Authorlist", sortable:true}, {key:"medline", label:"Medline", sortable:true} ]; // Define DataSource var myDataSourcePubmed = new YAHOO.util.DataSource("qct-list-article.html"); myDataSourcePubmed.responseType = YAHOO.util.DataSource.TYPE_JSON; myDataSourcePubmed.connXhrMode = "queueRequests"; myDataSourcePubmed.responseSchema = { resultsList: "articleItemList", fields: ["pmid","articletitle","abstract","authorlist","medline"], metaFields: { totalRecords: "totalArticleRecords" // Access to value in the server response } }; // Add Paginator var pubmedPaginator = new YAHOO.widget.Paginator({ rowsPerPage: 5, template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE, rowsPerPageOptions: [5,10,15,20] }); var myRequestPubmedBuilder = function(oState,oSelf) { oState = oState || {pagination:null, sortedBy:null}; var retstart = (oState.pagination != null) ? oState.pagination.recordOffset : 0; var retmax = (oState.pagination != null) ? oState.pagination.rowsPerPage : 5; return '?term=' + contentCurValue + '&retstart=' + retstart + '&retmax=' + retmax; } // myPubmedListTable config var oConfigsPubmed = { initialRequest: '?term=' + contentCurValue + '&retstart=0' + '&retmax=5', dynamicData: true, // Enables dynamic server-driven data selectionMode: "single", paginator: pubmedPaginator, generateRequest : myRequestPubmedBuilder, caption : "Pubmed articles for this query : " //+ contentCountPubmed }; // Create new DataTable - myPubmedListTable if (tabExist == null) { var myPubmedListTable = new YAHOO.widget.DataTable(idReq, myColumnDefsPubmed, myDataSourcePubmed,oConfigsPubmed); myPubmedListTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { if (oPayload == undefined) { oPayload = {}; } oPayload.totalRecords = oResponse.meta.totalRecords; return oPayload; } // Show myPubmedListTable myPubmedListTable.onShow(); } } ```
There seem to be some strange things afoot here; I can't see where idReq is defined, and content is defined twice. I wonder if content being something weird like `<div id=></div>` could cause it.
TabView and close button problem
[ "", "javascript", "yui", "uitabview", "" ]
How can I get the number of rows affected by an UPDATE query in a Stored Procedure (SQL Server 2005), as a resultset. e.g. ``` CREATE PROCEDURE UpdateTables AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; UPDATE Table1 Set Column = 0 WHERE Column IS NULL UPDATE Table2 Set Column = 0 WHERE Column IS NULL UPDATE Table3 Set Column = 0 WHERE Column IS NULL UPDATE Table4 Set Column = 0 WHERE Column IS NULL END ``` Then return: ``` Table1 Table2 Table3 Table4 32 45 0 3 ```
``` CREATE PROCEDURE UpdateTables AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @RowCount1 INTEGER DECLARE @RowCount2 INTEGER DECLARE @RowCount3 INTEGER DECLARE @RowCount4 INTEGER UPDATE Table1 Set Column = 0 WHERE Column IS NULL SELECT @RowCount1 = @@ROWCOUNT UPDATE Table2 Set Column = 0 WHERE Column IS NULL SELECT @RowCount2 = @@ROWCOUNT UPDATE Table3 Set Column = 0 WHERE Column IS NULL SELECT @RowCount3 = @@ROWCOUNT UPDATE Table4 Set Column = 0 WHERE Column IS NULL SELECT @RowCount4 = @@ROWCOUNT SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4 END ```
This is exactly what the [`OUTPUT`](http://technet.microsoft.com/en-us/library/ms177564.aspx) clause in SQL Server 2005 onwards is excellent for. EXAMPLE ``` CREATE TABLE [dbo].[test_table]( [LockId] [int] IDENTITY(1,1) NOT NULL, [StartTime] [datetime] NULL, [EndTime] [datetime] NULL, PRIMARY KEY CLUSTERED ( [LockId] ASC ) ON [PRIMARY] ) ON [PRIMARY] INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 07','2009 JUL 07') INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 08','2009 JUL 08') INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 09','2009 JUL 09') INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 10','2009 JUL 10') INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 11','2009 JUL 11') INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 12','2009 JUL 12') INSERT INTO test_table(StartTime, EndTime) VALUES('2009 JUL 13','2009 JUL 13') UPDATE test_table SET StartTime = '2011 JUL 01' OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed WHERE StartTime > '2009 JUL 09' ``` Results in the following being returned ``` LockId StartTime EndTime ------------------------------------------------------- 4 2011-07-01 00:00:00.000 2009-07-10 00:00:00.000 5 2011-07-01 00:00:00.000 2009-07-11 00:00:00.000 6 2011-07-01 00:00:00.000 2009-07-12 00:00:00.000 7 2011-07-01 00:00:00.000 2009-07-13 00:00:00.000 ``` In your particular case, since you cannot use aggregate functions with `OUTPUT`, you need to capture the output of `INSERTED.*` in a table variable or temporary table and count the records. For example, ``` DECLARE @temp TABLE ( [LockId] [int], [StartTime] [datetime] NULL, [EndTime] [datetime] NULL ) UPDATE test_table SET StartTime = '2011 JUL 01' OUTPUT INSERTED.* INTO @temp WHERE StartTime > '2009 JUL 09' -- now get the count of affected records SELECT COUNT(*) FROM @temp ```
Return number of rows affected by UPDATE statements
[ "", "sql", "sql-server", "" ]
I am writing some code to type strings using the Robot class. Everything is mostly good (well, I have to use a big switch statement to get character keycodes), except some keys don't have keycodes, because they are actually a combination of `Shift` + some other key. For upper case letters, it is easy to check, using `Character.isUpperCase(c)`, but for all the symbols such as `!@#$%^&*()_+` and various punctuation are not considered "upper case" although they do require shift to be pressed in order to generate thier keystroke. I tried googling for it, but just found a forum post with no satisfactory answers. Is there any way to determine whether a character needs shift to be pressed, and if so, what character is the "un-shifted" version? EDIT: Here is the code I have so far. ``` public void GenerateKeyTyped(char c) { if (Character.isUpperCase(c)) { r.keyPress(KeyEvent.VK_SHIFT); } r.keyPress(GetKeyCode(c)); r.keyRelease(GetKeyCode(c)); if (Character.isUpperCase(c)) { r.keyRelease(KeyEvent.VK_SHIFT); } } ```
I don't know a way to solve your problem directly ( I just ended up using a Map for those characters) but it might give you some ideas: ``` import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Main3 { public static void main(String[] args) { try { Robot robot = new Robot(); HashMap<String, String> map = new HashMap<String, String>(); map.put("!", "1"); map.put("@", "2"); map.put("#", "3"); char[] charz = "abcdefgABCDEFG123!#".toCharArray(); for(int i = 0; i < charz.length; i++) { System.out.print(charz[i] + " : "); boolean shiftRequired = false; String key = String.valueOf(charz[i]); String value = map.get(key); if (value != null) { shiftRequired = true; key = value; } else if (Character.isUpperCase(key.charAt(0))) { shiftRequired = true; } else { key = key.toUpperCase(); } KeyStroke ks = KeyStroke.getKeyStroke("pressed " + key.toUpperCase()); int keyCode = ks.getKeyCode(); System.out.println(keyCode); if (shiftRequired) robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT); robot.keyPress( keyCode ); robot.keyRelease( keyCode ); if (shiftRequired) robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT); } } catch(Exception e) { e.printStackTrace(); } } } ```
I'm not sure if what you're looking for is possible. You could create your own table, but keep in mind that it'll then work for one keyboard layout only (many languages have their own keyboard layouts that are more suited for their specific character sets, also, there's the Dvorak layout that probably has it's own shifted vs unshifted keys) unless you take into account all keyboard layouts you want to support, and create custom tables for those.
How do you determine if a character requires the shift key to be down to be typed?
[ "", "java", "keycode", "shift", "awtrobot", "" ]
I am using JetBrains dotTrace, I've profiled my app which is **entirely CPU bound**. But the results as you walk down the tree **don't sum to the level above in the tree**, I only see method calls not the body lines of the node in questions method. **Is it possible to profile the source code line by line**. i.e for one node: * SimulatePair() 99.04% --nextUniform() 30.12% --IDCF() 24.08% So the method calls nextUniform + IDCF use 54% of the time in SimulatePair (or 54% total execution time I'm not sure how to read this) regardless what is happening the other 46% of SimulatePair I need some detail on a line by line basis. Any help or alternative tools is much appreciated. Thanks
Check out [ANTS](http://www.red-gate.com/products/ants_performance_profiler/index2.htm) ... > Line-level code timing – drill down to > the specific lines of code responsible > for performance inefficiencies
dotTrace 6 supports line by line profiling. Also, with the use of the Profiler API you can set via code which parts of the application you want to profile via PerformanceProfiler.Start and PerformanceProfiler.Stop. Really easy to use and powerful.
JetBrains dotTrace, is it possible to profile source code line by line? else I need another tool
[ "", "c#", "profiler", "profiling", "dottrace", "" ]
I ran across an interesting issue today. We have an application that utilizes Zend Frameworks caching functionality. A request to this application typically calls a factory method using the following line ``` $result = call_user_func_array(array("myclass", "factory"), array($id)); ``` The idea is to return an object from the factory method that we can access later on. When we implemented a caching feature, this call just, well, dies. No errors, just a white screen. Nothing in the error log. We can error log the line before ok, but trying to error\_log inside the factory method does nothing. Interestingly enough, changing the line to : ``` $result = call_user_func(array("myclass", "factory"), $id); ``` fixes the issue. We've spent a few hours looking around for bug reports and haven't come up with much to explain this behavior. Thoughts anyone?
I have had issues like this that came down to \_\_autoload not firing properly when a not-yet-loaded class was invoked through a PHP command. No other strategy than dumb trial and error for it as far as I know, just try if a line explicitly invoking the class before the PHP command solves it for you. ``` $dummy = new MyClassName; call_user_func_array(array('MyClassName', 'method'), array($id)); unset($dummy); ```
Which version of php are you using? There was an issue in combining `call_user_func_array` with `ReflectionClass` at one point. I'm not sure if it's fixed yet.
call_user_func_array vs. call_user_func
[ "", "php", "zend-framework", "caching", "" ]
I read some of the discussion in [this question](https://stackoverflow.com/questions/1088156/quickest-query-to-check-for-the-existence-of-a-row-in-oracle) and thought to myself that in my PL/SQL code I have "exists" style queries all over the place that don't use the ROWNUM=1 optimisation. The questions I have are: 1. Does the introduction of ROWNUM=1 significantly increase performance? 2. If so, under what conditions would performance be particularly improved (e.g lots of joins, constraints on unindexed columns, large tables, large result sets) I'm trying to determine of it is worth rewriting all of my existing queries to add a ROWNUM=1 optimisation. The queries I'm thinking of are ones that may have multiple joins and may query large tables. They have the general form of: ``` SELECT 1 INTO ln_count FROM table_1, table_2...., table_n WHERE <various joins and conditions>; IF ln_count > 0 THEN <do stuff> END IF; ``` I'm considering changing them to: ``` SELECT 1 INTO ln_count FROM table_1, table_2...., table_n WHERE <various joins and conditions> AND ROWNUM = 1; IF <local variable> > 0 THEN <do stuff> END IF; ```
It does improve performance significantly (tens of percent average) on queries which cannnot be solved by simple single index lookup e.g. table joins. However it has a potential to hide data/application error. Lets have a table: ``` create table t (id number(10,0), padding varchar2(1000)); ``` --intentionally don't use PK to make the example as simple as possible. The padding is used to simulate real data load in each record with a many records: ``` insert into t (id, padding) select rownum, rpad(' ', 1000) from dual connect by level < 10000 ``` Now if you ask something like ``` select 1 into ll_exists from t where id = 5; ``` the DB must go through the whole table whether it found the only matching record in the first data block (which by the way we cannot know because it could be inserted by many different ways) or in the last. That's because it doesn't know that there is only one matching record. On the other hand if you use ... and rownum = 1 than it can stop traversing through data after the record is found because you told it that there is not (or not needed) another matching record. The drawback is that with the rownum constraint you may get undeterministic results if the data contains more than one possible record. If the query was ``` select id into ll_id from t where mod (id, 2) = 1 and rownum = 1; ``` then I may receive from the DB answer 1 as well as 3 as well as 123 ... order is not guaranteed and this is the consequence. (without the rownum clause I would get a TOO\_MANY\_ROWS exception. It depends on situation which one is worse) If you really want query which tests existence then WRITE IT THAT WAY. ``` begin select 'It does' into ls_exists from dual where exists (your_original_query_without_rownum); do_something_when_it_does_exist exception when no_data_found then do_something_when_it_doesn't_exist end; ```
One rule of thumb in optimization is to not do it unless you have a hotspot you need to fix. However, if you are curious about the performance benefits, you might want to run some tests using both to see if you can measure any improved performance. [wikipedia quotes](http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize) Donald Knuth as saying: > "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
Under what conditions does ROWNUM=1 significantly increase performance in an "exists" syle query
[ "", "sql", "oracle", "optimization", "plsql", "" ]
I'm trying to put together a Java Webstart app, but don't want it to display the Webstart splash screen, or "downloading app" boxes. Is there any way I can turn them off? (I'm fine with it displaying the Permissions Request box, but nothing else).
Yes, use the -nosplash option. Place this: ``` <argument>-nosplash</argument> ``` in your JNLP document.
Or you can use your on startup image: MyProject1.0 My Company. Application Launcher For MyProject1.0 ....
Can I supress the loading dialogs in Java Web Start?
[ "", "java", "applet", "java-web-start", "" ]
I have to write an XML file using java.The contents should be written from a map.The map contains items as key and their market share as value.I need to build an XML file withe two tags.I will use this XML to build a piechart using amcharts.Can anyone help with an existing code? ``` <xml> <pie> <slice title="<Map key1>"><Map Value1></slice> <slice title="<Map key2>"><Map Value2></slice> <slice title="<Map key1>"><Map Value3></slice> . . . <slice title="<Map keyn>"><Map Valuen></slice> </pie> ```
There are a number of ways to do this using the standard API. (Insert your own caveats about verbosity and the factory pattern.) You can use the [XMLStreamWriter](http://java.sun.com/javase/6/docs/api/javax/xml/stream/XMLStreamWriter.html) to encode the data: ``` XMLOutputFactory factory = XMLOutputFactory .newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter( stream, "UTF-8"); try { writer.writeStartDocument("UTF-8", "1.0"); writer.writeStartElement("pie"); for (Entry<String, String> entry : map.entrySet()) { writer.writeStartElement("slice"); writer.writeAttribute("title", entry.getKey()); writer.writeCharacters(entry.getValue()); writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndDocument(); } finally { writer.close(); } ``` Alternatively, you could build a [DOM document](http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html) (not recommended) and emit that, or use [JAXB](http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXB.html) binding to marshal/unmarshal data ([tutorial](https://jaxb.dev.java.net/tutorial/index.html)). Sample annotated JAXB object: ``` @XmlRootElement(name = "pie") public class Pie { @XmlElement(name = "slice") public List<Slice> slices = new ArrayList<Slice>(); public Pie() { } public Pie(Map<String, String> sliceMap) { for (Map.Entry<String, String> entry : sliceMap .entrySet()) { Slice slice = new Slice(); slice.title = entry.getKey(); slice.value = entry.getValue(); slices.add(slice); } } static class Slice { @XmlAttribute public String title; @XmlValue public String value; } } ``` Test code: ``` Map<String, String> slices = new HashMap<String, String>(); slices.put("Title 1", "100"); slices.put("Title 2", "200"); Pie pie = new Pie(slices); JAXB.marshal(pie, System.out); ``` There are a host of third party APIs that can do the same jobs and various templating options have already been mentioned.
I would beware of writing XML directly since you have to worry about entity encoding. e.g. writing text content with `<`, `>` or `&` directly will generate invalid XML. The same will apply when using Velocity and Freemarker. If you do write the XML directly, make sure that all your text content gets encoded properly. You can do this using Apache Commons and [StringEscapeUtils.escapeXML()](http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml%28java.lang.String%29). EDIT: Looking again at your XML requirements, [XStream](http://xstream.codehaus.org/) may work for you. If you have a java.util.Map, XStream can write this straight out. You'll have to look at [aliasing](http://xstream.codehaus.org/alias-tutorial.html) to change your element names, but possibly worth looking at.
XML using Java
[ "", "java", "xml", "" ]
I have a file containing Unicode characters on a server running linux. If I SSH into the server and use tab-completion to navigate to the file/folder containing unicode characters I have no problem accessing the file/folder. The problem arises when I try accessing the file via PHP (the function I was accessing the file system from was `stat`). If I output the path generated by the PHP script to the browser and paste it into the terminal the file also seems to exist (even though looking at the terminal the file paths are exactly the same). I set PHP to use UTF8 as its default encoding via php\_ini as well as set `mb_internal_encoding`. I checked the PHP filepath string encoding and it comes out as UTF8, as it should. Poking around a bit more I decided to `hexdump` the é character that the terminal's tab-completion and compare it to the `hexdump` of the 'regular' é character created by the PHP script or by manually entering in the character via keyboard (option+e+e on os x). Here is the result: ``` echo -n é | hexdump 0000000 cc65 0081 0000003 echo -n é | hexdump 0000000 a9c3 0000002 ``` The é character that allows a correct file reference in the terminal is the 3-byte one. I'm not sure where to go from here, what encoding should I use in PHP? Should I be converting the path to another encoding via `iconv` or `mb_convert_encoding`?
Thanks to the tips given in the two answers I was able to poke around and find some methods for normalizing the different unicode decompositions of a given character. In the situation I was faced with I was accessing files created by a OS X Carbon application. It is a fairly popular application and thus its file names seemed to adhere to a specific unicode decomposition. In PHP 5.3 a [new set of functions][1] was introduced that allows you to normalize a unicode string to a particular decomposition. Apparently there are four decomposition standards which you can decompose you unicode string into. Python has had unicode normalization capabilties since version 2.3 via [unicode.normalize][2]. [This article][3] on python's handling of unicode strings was helpful in understanding encoding / string handling a bit better. Here is a quick example on normalizing a unicode filepath: ``` filePath = unicodedata.normalize('NFD', filePath) ``` I found that the NFD format worked for all my purposes, I wonder if this is this is the standard decomposition for unicode filenames. [1]: <https://www.php.net/manual/en/class.normalizer.php> [2]: <http://docs.python.org/library/unicodedata.html> [3]: <http://boodebr.org/main/python/all-about-python-and-unicode>
The three byte sequence is actually the utf8 representation of an [e (0x65)](http://www.fileformat.info/info/unicode/char/0065/index.htm) followed by a [combining ´ (0xcc 0x81)](http://www.fileformat.info/info/unicode/char/0301/index.htm), while 0xc3 0xa9 stands "directly" for [é](http://www.fileformat.info/info/unicode/char/00e9/index.htm). An utf-8 aware collation should be aware of the possible decompositions, but I don't know how you can enable that (and probably recompile the php source) on a mac. Best I can offer is the ["Using UTF-8 with Gentoo"](http://www.gentoo.org/doc/en/utf-8.xml) description.
UTF8 Filenames in PHP and Different Unicode Encodings
[ "", "php", "unicode", "encoding", "utf-8", "filepath", "" ]
I'm making a program in Python to be distributed to windows users via an installer. The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it. So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key. Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language? All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself. Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.
You don't need `PyCrypto` or `PyMe`, fine though those packages may be - you will have all kinds of problems building under Windows. Instead, why not avoid the rabbit-holes and do what I did? Use `gnupg 1.4.9`. You don't need to do a full installation on end-user machines - just `gpg.exe` and `iconv.dll` from the distribution are sufficient, and you just need to have them somewhere in the path or accessed from your Python code using a full pathname. No changes to the registry are needed, and everything (executables and data files) can be confined to a single folder if you want. There's a module `GPG.py` which was originally written by Andrew Kuchling, improved by Richard Jones and improved further by Steve Traugott. It's available [here](https://web.archive.org/web/20090921072827/http://trac.t7a.org/isconf/browser/trunk/lib/python/isconf/GPG.py), but as-is it's not suitable for Windows because it uses `os.fork()`. Although originally part of `PyCrypto`, **it is completely independent of the other parts of `PyCrypto` and needs only gpg.exe/iconv.dll in order to work**. I have a version (`gnupg.py`) derived from Traugott's `GPG.py`, which uses the `subprocess` module. It works fine under Windows, at least for my purposes - I use it to do the following: * Key management - generation, listing, export etc. * Import keys from an external source (e.g. public keys received from a partner company) * Encrypt and decrypt data * Sign and verify signatures The module I've got is not ideal to show right now, because it includes some other stuff which shouldn't be there - which means I can't release it as-is at the moment. At some point, perhaps in the next couple of weeks, I hope to be able to tidy it up, add some more unit tests (I don't have any unit tests for sign/verify, for example) and release it (either under the original `PyCrypto` licence or a similar commercial-friendly license). If you can't wait, go with Traugott's module and modify it yourself - it wasn't too much work to make it work with the `subprocess` module. This approach was a lot less painful than the others (e.g. `SWIG`-based solutions, or solutions which require building with `MinGW`/`MSYS`), which I considered and experimented with. I've used the same (`gpg.exe`/`iconv.dll`) approach with systems written in other languages, e.g. `C#`, with equally painless results. P.S. It works with Python 2.4 as well as Python 2.5 and later. Not tested with other versions, though I don't foresee any problems.
After a LOT of digging, I found a package that worked for me. Although it is said to support the generation of keys, I didn't test it. However I did manage to decrypt a message that was encrypted using a GPG public key. The advantage of this package is that it does not require a GPG executable file on the machine, and is a Python based implementation of the OpenPGP (rather than a wrapper around the executable). I created the private and public keys using GPG4win and kleopatra for windows See my code below. ``` import pgpy emsg = pgpy.PGPMessage.from_file(<path to the file from the client that was encrypted using your public key>) key,_ = pgpy.PGPKey.from_file(<path to your private key>) with key.unlock(<your private key passpharase>): print (key.decrypt(emsg).message) ``` Although the question is very old. I hope this helps future users.
How to do PGP in Python (generate keys, encrypt/decrypt)
[ "", "python", "encryption", "public-key-encryption", "gnupg", "pgp", "" ]
Can we place C# textBox controls in a C# dropdown combobox? That is, when the combo is dropped down, each of its items will show a textbox.
In windows forms, it's not exactly possible, but you can intercept the window message that causes the combobox to drop down and show a panel or form instead. As a place to start: ``` public class UserControlComboBox : ComboBox, IMessageFilter { public readonly MyControlClass UserControl = new MyControlClass(); protected override void WndProc(ref Message m) { if ((m.Msg == 0x0201) || (m.Msg == 0x0203)) { if (DroppedDown) HideUserControl(); else ShowUserControl(); } else { base.WndProc(ref m); } } public bool PreFilterMessage(ref Message m) { // intercept mouse events if ((m.Msg >= 0x0200) && (m.Msg <= 0x020A)) { if (this.UserControl.RectangleToScreen(this.UserControl.DisplayRectangle).Contains(Cursor.Position)) { // clicks inside the user control, handle normally return false; } else { // clicks outside the user controlcollapse it. if ((m.Msg == 0x0201) || (m.Msg == 0x0203)) this.HideUserControl(); return true; } } else return false; } public new bool DroppedDown { get { return this.UserControl.Visible; } } protected void ShowUserControl() { if (!this.Visible) return; this.UserControl.Anchor = this.Anchor; this.UserControl.BackColor = this.BackColor; this.UserControl.Font = this.Font; this.UserControl.ForeColor = this.ForeColor; // you can be cleverer than this if you need to this.UserControl.Top = this.Bottom; this.UserControl.Left = this.Left; this.UserControl.Width = Math.Max(this.UserControl.Width, this.Width); this.Parent.Controls.Add(this.UserControl); this.UserControl.Visible = true; this.UserControl.BringToFront(); base.OnDropDown(EventArgs.Empty); // start listening for clicks Application.AddMessageFilter(this); } protected void HideUserControl() { Application.RemoveMessageFilter(this); base.OnDropDownClosed(EventArgs.Empty); this.UserControl.Visible = false; this.Parent.Controls.Remove(this.UserControl); // you probably want to replace this with something more sensible this.Text = this.UserControl.Text; } protected override void Dispose(bool disposing) { if (disposing) { this.UserControl.Dispose(); } base.Dispose(disposing); } } ```
yes, example in WPF: ``` <Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <ComboBox Margin="49,61,75,0" Height="25" VerticalAlignment="Top"> <ComboBox.Items> <ComboBoxItem> <TextBox>TextBox</TextBox> </ComboBoxItem> <ComboBoxItem> <TextBlock>TextBlock</TextBlock> </ComboBoxItem> <ComboBoxItem> <Button>Button</Button> </ComboBoxItem> </ComboBox.Items> </ComboBox> </Grid> </Window> ``` in Windows Forms combobox could be a hassle.
C# - .net controls as ComboBox Items
[ "", "c#", "combobox", "" ]
I have an image. I would like to go over that image, pixel by pixel, and any pixel that is not black should be turned to white. How do I do this? (Python). Thanks!
You should use the `point` function, which exists specifically for this reason. ``` converter= ( (0,) + 255*(255,) ).__getitem__ def black_or_white(img): return img.convert('L').point(converter) ```
The most efficient way is to use the point function ``` def only_black(band): if band > 0: return 255 return 0 result = im.convert('L').point(only_black) ``` This is what the [PIL documentation](http://effbot.org/imagingbook/image.htm) has to say about this: > When converting to a bilevel image > (mode "1"), the source image is first > converted to black and white. > Resulting values larger than 127 are > then set to white, and the image is > dithered. To use other thresholds, use > the point method.
Cleaning an image to only black
[ "", "python", "image-processing", "python-imaging-library", "" ]
A simple question. I have an ASP.NET web application which contains several assemblies and I need to create a list of version information for every assembly in the web site. (And perhaps even a few others too, but the focus is mostly for the site itself.) This list will be displayed within the same application on a protected page and is used to validate the installation and upgrades for the website. Of course, I could just walk through all binaries in the BIN folder and extract information from them but is there a better option to do this? And second question: what's the best method to just extract version information from another assembly? But I guess that one has asked before and I can find an answer to this myself. (Something with reflection, GetExecutingAssembly and some more stuff.)
``` IEnumerable<String> GetLoadedAssemblies() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { yield return assembly.ToString(); } } ``` Gives you the name (including version number) of every assembly being used in the app domain. `mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089` etc. One possible gotcha with using this: if the website has just started then some of the assemblies you are interested in might not have been loaded into the AppDomain yet, as they're unlikely to be referenced by a special page with just this functionality on it. If you click around the site first to make sure everything is loaded it should work OK, but if you need something more robust you'd have to add some AppDomain.Load() statements to the above code.
You could also use the [GetReferencedAssemblies()](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getreferencedassemblies.aspx) method of the Assembly class to get all of the assemblies referenced by your web application.
List of version numbers of assemblies used by it's web site
[ "", "c#", "asp.net", "web", "" ]
I'm not sure why these have to be unique, but from reading the MySQL forums it appears that they do. However, I think it has something more to do with the INDEX name. I have two tables that have foreign key constraints referencing the same primary key on a third table. If it helps, I'm using MySQL workbench to design the schema. I usually name my foreign key on each table the same name as the primary key it references. I guess this isn't possible. It will create the first table with the foreign key constraint, but when it tries to create the second table it throws an error. Here is the second table it throws the error on: ``` CREATE TABLE IF NOT EXISTS `joe`.`products_to_categories` ( `product_to_category_id` INT NOT NULL AUTO_INCREMENT , `category_id` INT NOT NULL , `product_id` INT NOT NULL , PRIMARY KEY (`product_to_category_id`) , INDEX `category_id` (`category_id` ASC) , INDEX `product_id` (`product_id` ASC) , CONSTRAINT `category_id` FOREIGN KEY (`category_id` ) REFERENCES `joe`.`categories` (`category_id` ) ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT `product_id` FOREIGN KEY (`product_id` ) REFERENCES `joe`.`products` (`product_id` ) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; ``` I want the foreign key names to be the same as the primary key in both of the other tables. What should I remove here so that I can use these names. What is the best practice here.
It is not possible because you would have a conflict in the filename for the file that is used for the index IIRC. I probably would name the key < tablename >\_< column\_name > or something like that.
You are creating an index (constraint) by the name of `product_id` via: INDEX `product_id` Then you are going and creating another constraint (for the foreign key) with the same name: CONSTRAINT `product_id` What you need to do is allow the server to provide a default, unique constraint name by removing the CONSTRAINT `product_id` See this URL: <http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html> "If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically."
How can I get around this foreign key constraint having to have a unique name?
[ "", "sql", "mysql", "foreign-keys", "" ]
Is it possible to link a static library built with VS2005 into an application that is to be built with gcc (in Cygwin)?
Unlike UNIX where there was no standard C++ ABI for years, Windows has had a standard C++ ABI from the beginning. So, yes, [it's possible](http://oldwiki.mingw.org/index.php/sample%20DLL). But it [can be difficult](http://oldwiki.mingw.org/index.php/CreateImportLibraries).
Theoretically it should work, but I would suggest to just try it.
Linking VS2005 static library with gcc in Windows
[ "", "c++", "gcc", "visual-studio-2005", "" ]
This question is a furtherance of the one asked in [this thread](https://stackoverflow.com/questions/1117693/initializing-template-base-class-member-types-in-derived-class-initializer-lists). Using the following class definitions: ``` template <class T> class Foo { public: Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg) { /* do something for foo */ } T Foo_T; // either a TypeA or a TypeB - TBD foo_arg_t _foo_arg; }; template <class T> class Bar : public Foo<T> { public: Bar (const foo_arg_t bar_arg, const a_arg_t a_arg) : Foo<T>(bar_arg) // base-class initializer { Foo<T>::Foo_T = T(a_arg); } Bar (const foo_arg_t bar_arg, const b_arg_t b_arg) : Foo<T>(bar_arg) { Foo<T>::Foo_T = T(b_arg); } void BarFunc (); }; template <class T> void Bar<T>::BarFunc () { std::cout << _foo_arg << std::endl; // This doesn't work - compiler error is: error: ‘_foo_arg’ was not declared in this scope std::cout << Bar<T>::_foo_arg << std::endl; // This works! } ``` When accessing the members of the template-class's base-class, it seems like I must always explicitly qualify the members using the template-style syntax of `Bar<T>::_foo_arg`. Is there a way to avoid this? Can a 'using' statement/directive come into play in a template class method to simplify the code? **Edit:** The scope issue is resolved by qualifying the variable with this-> syntax.
You can use `this->` to make clear that you are referring to a member of the class: ``` void Bar<T>::BarFunc () { std::cout << this->_foo_arg << std::endl; } ``` Alternatively you can also use "`using`" in the method: ``` void Bar<T>::BarFunc () { using Bar<T>::_foo_arg; // Might not work in g++, IIRC std::cout << _foo_arg << std::endl; } ``` This makes it clear to the compiler that the member name depends on the template parameters so that it searches for the definition of that name in the right places. For more information also see [this entry in the C++ Faq Lite](https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members).
Here the base class is not a nondependent base class( which means one with a complete type that can be determined without knowing the template arguments), and `_foo_arg` is a nondependent name. Standard C++ says that nondependent names are not looked up in dependent base classes. To correct the code, it suffices to make the name `_foo_arg` dependent because dependent names can be looked up only at the time of instantiation, and at that time the exact base specialization that must be explored will be known. For example: ``` // solution#1 std::cout << this->_foo_arg << std::endl; ``` An alternative consists in introducing a dependency using a qualified name: ``` // solution#2 std::cout << Foo<T>::_foo_arg << std::endl; ``` Care must be taken with this solution, because if the unqualified nondependent name is used to form a virtual function call, then the qualification inhibits the virtual call mechanism and the meaning of the program changes. And you can bring a name from a dependent base class in the derived class once by `using`: ``` // solution#3 template <class T> class Bar : public Foo<T> { public: ... void BarFunc (); private: using Foo<T>::_foo_arg; }; template <class T> void Bar<T>::BarFunc () { std::cout << _foo_arg << std::endl; // works } ```
Derived template-class access to base-class member-data
[ "", "c++", "templates", "inheritance", "scope", "name-lookup", "" ]
Ok, I have some C# code that looks like this and I was wondering what other developers would recommend if I am trying to put this into Objective-C. ``` List<List<string>> meta_data ``` I'm planning on using `NSMutableArray` but how to exactly get that two-dimensional array figured out is my problem, since there is no such thing as a multidimensional array in Objective-C. I'm new to using `NSMutableArray`, so I still need some help every now and then. I know I will just add string objects to the array using NSString once I have the whole "two-dimensional" part figured out.
An array can hold any object. I'm not familiar with C# code, but I imagine all your trying to do is nested arrays. What you need to be using is objectAtIndex: for NSArrays. ``` NSString *hello = @"Hello World"; NSMutableArray *insideArray = [[NSMutableArray alloc] initWithObjects:hello,nil]; NSMutableArray *outsideArray = [[NSMutableArray alloc] init]; [outsideArray addObject:insideArray]; // Then access it by: NSString *retrieveString = [[outsideArray objectAtIndex:0] objectAtIndex:0]; ``` I think your looking for something like that. Does that help?
Something like this: ``` //Create the array of strings NSMutableArray *strings = [[NSMutableArray alloc] init]; [strings addObject:@"someString"]; [strings addObject:@"someOtherString"]; //Create the array to hold the string array NSMutableArray *container = [[NSMutableArray alloc] init]; [container addObject:strings]; ```
Two Dimension NSMutableArray help?
[ "", "c#", "objective-c", "cocoa", "nsstring", "nsmutablearray", "" ]
In .NET & C#, suppose `ClassB` has a field that is of type `ClassA`. One can easily use method `GetFields` to list `ClassB`'s fields. However, I want to *also* list the fields of those `ClassB` fields that *themselves* have fields. For example, `ClassB`'s field `x` has fields `b`, `s`, and `i`. I'd like to (programmatically) list those fields (as suggested by my comments in the code below). ``` class ClassA { public byte b ; public short s ; public int i ; } class ClassB { public long l ; public ClassA x ; } class MainClass { public static void Main ( ) { ClassA myAObject = new ClassA () ; ClassB myBObject = new ClassB () ; // My goal is this: // ***Using myBObject only***, print its fields, and the fields // of those fields that, *themselves*, have fields. // The output should look like this: // Int64 l // ClassA x // Byte b // Int16 s // Int32 i } } ```
Use the `FieldInfo.FieldType` to reflect over the type of the fields in your class. E.g. ``` fieldInfo.FieldType.GetFields(); ``` Here is a complete sample based on your code that uses recursion in case you have `ClassZ` inside `ClassA`. It breaks if you have a cyclic object graph. ``` using System; using System.Reflection; class ClassA { public byte b; public short s; public int i; } class ClassB { public long l; public ClassA x; } class MainClass { public static void Main() { ClassB myBObject = new ClassB(); WriteFields(myBObject.GetType(), 0); } static void WriteFields(Type type, Int32 indent) { foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { Console.WriteLine("{0}{1}\t{2}", new String('\t', indent), fieldInfo.FieldType.Name, fieldInfo.Name); if (fieldInfo.FieldType.IsClass) WriteFields(fieldInfo.FieldType, indent + 1); } } } ```
The class that does this already exists! Take a look at the Microsoft C# Samples for Visual Studio: <http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=csharpsamples&ReleaseId=8> Specifically, look at the ObjectDumper sample as it goes n-levels deep. For example: ``` ClassB myBObject = new ClassB(); ... ObjectDumper.Write(myBObject, Int32.MaxValue); //Default 3rd argument value is Console.Out, but you can use //any TextWriter as the optional third argument ``` It has already taken into account whether an object in the graph has been visited, Value types vs. object types vs. enumerable types, etc.
.NET, C#, Reflection: list the fields of a field that, itself, has fields
[ "", "c#", ".net", "reflection", "recursion", "" ]
I am trying to model a tree relationship in a table. For instance, there are "Categories" and categories can themselves be inside a Parent category. My schema is: ``` id int PRIMARY KEY, parent_id int, name ``` My question is, should I label the parent\_id column as a Foreign key? Foreign implies "outside" and not self-referencing. Is there a different type of key for this purpose? My question is similar to: [Self-referencing constraint in MS SQL](https://stackoverflow.com/questions/528529/self-referencing-constraint-in-ms-sql), but I'm asking a different question, cascading not being an issue.
Self-referencing foreign keys happen all the time. E.g. an employee might have another "employee" as his manager, so the manager\_id will be a foreign key to the employee\_id field in the same table. Foreign keys are the natural candidate for representing the parent node in hierarchical data, although they're not exclusively used for that :)
If you have very deep levels of nesting it may not be easy to performantly select out all descendants of a particular node, since most DB's do not handle recursion very well. Another approach is to use what's called the "Nested Set Model" to represent the relationships. A great article is available here: <http://www.intelligententerprise.com/001020/celko.jhtml>
Should I use a Foreign Key to Show Tree Relationship in SQL
[ "", "sql", "database", "database-design", "foreign-keys", "foreign-key-relationship", "" ]
I use this snippet to create a console from inside a dll. That dll gets loaded in a game. [CODE SNIPPET](http://www.codeguru.com/cpp/v-s/debug/article.php/c1249) The console window creates fine. But when i write stuff to it, i just get stuff like "???D??". I know i have to use the printf() syntax. So i use ``` wprintf("%s", "test"); ``` Any pointers?
~~Try using:~~ ``` wprintf(L"%s", "test"); ``` as wprintf takes an wide character string as input **Edit**: Based on the fact that the behaviour of %s and %S changes when used in wprintf what about: ``` wprintf("%s", L"test"); ``` The %s in wprintf expects a wide character string this L"test" is. I removed the "L" on the format parameter since wprintf is defined as: ``` int wprintf(char *fmt, ...) ```
You're calling wprintf(), the "wide-character" version of the printf() routine. There's one nasty catch with these "wide-character" functions, in that the meaning of "%s" changes: printf() - "%s" means argument is a normal string, "%S" means it's a wide-character string wprintf() - "%s" means argument is a wide-character string, "%S" means it's a normal string So your call to wprintf() is telling it that the argument is a wide-character string, but it's not: change it to ``` printf("%s", "test"); ```
WriteConsole() weird characters?
[ "", "c++", "windows", "console", "" ]
Lets say we have a derivided class "SerializableLabel" from the base class "System.Windows.Controls. ``` [XmlRoot("SerializableLabel")] public class SerializableLabel : Label { public string foo = "bar"; } ``` I'd like to serialize this class but ignore ALL of the properties in the parent class. Ideally the xml would look something like: ``` <SerializableLable> <foo>bar</foo> </SerializableLable> ``` **How is this best achieved?** My first attempt used the typical XmlSerializer approach: ``` XmlSerializer s = new XmlSerializer(typeof(SerializableLabel)); TextWriter w = new StreamWriter("test.xml"); s.Serialize(w, lbl); w.Close(); ``` But this raises an exception because the serializer attempts to serialize a base class property which is an interface (ICommand Command).
One possible root of the above problems (including the one pointed out by JP) is that your class hierarchy tries to violate the [Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). In simpler terms, the derived class tries **not** to do what the base class already does. In still other words, you're trying to create a derived label that is not substitutable for the base label. The most effective remedy here may involve decoupling the two things that **SerializableLabel** is tries to do, (a) UI-related functions and (b) storing serializable data, and having them in different classes.
If you want to ignore properties during serialization, you can use Xml Attribute overrides. See [this question](https://stackoverflow.com/questions/720400/xml-serialize-annotations/1060022#1060022) for an intro to attribute overrides.
.net XmlSerializer, ignore base class properties
[ "", "c#", ".net", "xml-serialization", "" ]
Have you ever had to justify the choice over using .NET instead of Java based on performance? For a typical high volume transaction processing system that can perform the following operations, * Concurrent Database transactions * Mathematical computations * Interaction with other web services (SOAP/XML, XML-RPC) My approach would be to code benchmark tests in both Java for the JVM and C# for .NET CLR that benchmark the above operations under various levels of load and compare the results. Language and platform preferences aside, **I am interested in hearing how you would go about doing a conclusive performance comparison** between the Java VM and .NET CLR? Are there any comprehensive and respected benchmarks that exist?
I don't have exact numbers on the efficiency of the JVM vs the CLR, but the difference, if any, is likely to be small. However, on the language side, C# does have some more low level constructs than Java, which would allow for more optimization. Constructs such as: * User defined value types. Fast to allocate, no memory overhead (which is 12 bytes per reference type in both the CLR and JVM if I remember correctly). Useful for things that let themselves naturally be expressed as values, like vectors and matrices. So mathematical operations. Combine this with `ref` and `out` to avoid excessive copying of these large value types. * Unsafe blocks of code that allow a little more 'close to the metal' optimization. For example, while the CLR and JVM can avoid array bounds checks in some situations, in a lot of cases, they can't and every array access requires a check whether or not the index is still within bounds of the array. Using unsafe code here allows you to access the memory of the array directly with pointers and circumvent any bounds checks. This can mean a significant saving. And on the very low level side, there's also `stackalloc` which allows you to allocate arrays directly on the stack, whereas a normal array is allocated on the heap, which is slower, but also more convenient. I personally don't know any practical applications of `stackalloc`. * True generics, unlike the type erasing generics of Java, avoiding unneeded casting and boxing. But if this is a problem in your Java program, it can easily be solved with some extra work (switching from for example a `ArrayList<Integer>` to a custom type that internally uses an `int[]` buffer.) This all seems biased towards C# and I do think C# has better low level language constructs available that can help with performance. However, I doubt these differences really matter (and they might not even apply in your case, using pointers gains you nothing if all you do is database access, where Java might be faster) if the choice impedes you in some other way (like going cross platform). Go for correctness, the platform that matches your requirements, rather than minor performance differences.
***a conclusive performance comparison between the Java VM and .Net CLR*** is a pipe dream. You can always make a performance test that will make one look better than the other since engineering a complex system always involves compromises. If you narrow down the type of benchmarks to runtime speed and memory you might find articles like this: <http://www.codeproject.com/KB/dotnet/RuntimePerformance.aspx> that is by no means the end of the debate.
Benchmarking Performance on Java VM vs .NET CLR
[ "", "java", ".net", "performance", "jvm", "benchmarking", "" ]
I have VS2005. How can I compile my project under specific version of .NET? I have installed 1.0, 2.0, 3.0 & 3.5. Tnx in advance.
You can't I'm afraid. VS2005 only works with .NET framework 2.0. You'll need the appropriate versions of Visual Studio to work with other versions: * 1.0: Visual Studio .NET * 1.1: Visual Studio .NET 2003 * 2.0: Visual Studio 2005 / 2008 * 3.0 / 3.5: Visual Studio 2008 * 4.0: Visual Studio 2010 jmservera points out that some 3.0 libraries are compatible with Visual Studio 2005. For example WCF is compatible, while LINQ isn't. Some of these require additional downloads, for example to use Windows Workflow Foundation comfortably in Visual Studio 2005, you need to install [this extension](http://www.microsoft.com/downloads/details.aspx?FamilyId=5D61409E-1FA3-48CF-8023-E8F38E709BA6&displaylang=en "Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation)").
This is just for your information: If you are using VS version greater than or equal to 2008, you can do this by right clicking the project you want to build, click `Properties`, and select the `Application` tab (if not already selected). Change the value in the `Target Framework` dropdown list. [![Target Framework](https://i.stack.imgur.com/cGXPG.jpg)](https://i.stack.imgur.com/cGXPG.jpg) (source: [scottgu.com](http://www.scottgu.com/blogposts/multitarget/step6.jpg))
How to choose .NET version to compile project?
[ "", "c#", ".net", "visual-studio", "" ]
``` class Widget { public: Widget() { cout<<"~Widget()"<<endl; } ~Widget() { cout<<"~Widget()"<<endl; } void* operator new(size_t sz) throw(bad_alloc) { cout<<"operator new"<<endl; throw bad_alloc(); } void operator delete(void *v) { cout<<"operator delete"<<endl; } }; int main() { Widget* w = 0; try { w = new Widget(); } catch(bad_alloc) { cout<<"Out of Memory"<<endl; } delete w; getch(); return 1; } ``` In this code, `delete w` does not call the overloaded `delete` operator when the destructor is there. If the destructor is omitted, the overloaded `delete` is called. Why is this so? **Output when ~Widget() is written** > operator new > Out of Memory **Output when ~Widget() is not written** > operator new > Out of Memory > operator delete
I remember something similar on operator delete a while ago in comp.lang.c++.moderated. I cannot find it now, but the answer stated something like this .. > Unfortunately, the language > specification is not sufficiently > clear on whether the control should go > into the overloaded 'operator delete' > when the delete-expression is invoked > on the null-pointer of corresponding > type, even though the standard does > say that delete-expression on > null-pointer is a no-op. And *James Kanze* specifically said: > It's still the responisiblity of > operator delete (or delete[]) to > check; the standard doesn't guarantee > that it won't be given a null pointer; > the standard requires that it be a > no-op if given a null pointer. Or that > the implementation is allowed to call > it. According to the latest draft, > "The value of the first argument > supplied to a deallocation function > may be a null pointer value; if so, > and if the deallocation function is > one supplied in the standard library, > the call has no effect." I'm not quite > sure what the implications of that "is > one supplied in the standard library" > are meant to be---taken literally, > since his function is not one provided > by the standard library, the sentence > wouldn't seem to apply. But somehow, > that doesn't make sense I remember this becoz i had a similar prob sometime back and had preserved the answer in a .txt file. **UPDATE-1:** Oh i found it [here](http://bytes.com/groups/cpp/853692-null-pointer-overloaded-operator-delete). Also read this link [defect report](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#348). So, the answer is ***Unspecified***. Chapter ***5.3.5/7***.
First of all, this can really be simplified down to `delete (Widget*)0` - everything else in your `main()` is unnecessary to repro this. It's a code generation artefact that happens because 1) user-defined `operator delete` must be able to handle NULL values, and 2) compiler tries to generate the most optimal code possible. First let's consider the case when no user-defined destructor is involved. If that's the case, there's no code to run on the instance, except for `operator delete`. There's no point in checking for null before transferring control to `operator delete`, because the latter should do a check anyway; and so the compiler just generates unconditional call of `operator delete` (and you see the latter print a message). Now the second case - destructor was defined. This means that your `delete` statement actually expands into two calls - destructor, and `operator delete`. But destructor cannot be safely called on a null pointer, because it could try to access class fields (the compiler could figure out that your particular destructor doesn't really do it and so is safe to call with null `this`, but looks like they don't bother in practice). So it inserts a null check in there before the destructor call. And once the check is already there, it might as well use it skip the call to `operator delete`, too - after all it's required to be a no-op anyway, and it will spare an extra meaningless check for null inside `operator delete` itself in case the pointer actually is null. So far as I can see, nothing in this is in any way guaranteed by ISO C++ spec. It's just that both compilers do the same optimization here.
delete a NULL pointer does not call overloaded delete when destructor is written
[ "", "c++", "memory-management", "destructor", "" ]
What are your tricks on getting the caching part of web application just right? Make the expiry date too long and we'll have a lot of stale caches, too short and we risk the servers overloaded with unnecessary requests. How to make sure that all changes will refresh all cache? How to embed SVN revision into code/url? Does having multiple version side-by-side really help to address version mismatch problem?
I think you are on the right track with putting version numbers on your js css files. And you may want to use a build tool to put all of this together for you like <http://ant.apache.org/> or <http://nant.sourceforge.net/>
Look at the [minify](http://code.google.com/p/minify/) project. It's written in PHP but you could use it as a blueprint for any language. Key features: * a config file to combine & minify several js or css files into one * always uses the last modified date of the last modified file in a config group as a URL parameter example resource might look like ``` <script type="text/javascript" src="/min/g=js1&1248185458"></script> ``` which would fetch the 'js1' group of javascript files in your configuration with the version number "1248185458" which is really just the last modified date converted to epoch time. When you put updated js files on your production servers, they'll have a new modified date which automatically becomes a new version number - no stale caches, **no manual versioning**. It's a very cool project with some really well thought out ideas about optimization and caching. I've modified the process slightly to insert [YUI compressor](http://developer.yahoo.com/yui/compressor/) into the build process. You can optimize it even more by preventing the last modified lookups **from the browser** by modifying your server's headers ([here](http://www.askapache.com/htaccess/apache-speed-cache-control.html) and [here](http://www.askapache.com/htaccess/apache-speed-last-modified.html)).
How to deal with browser cache?
[ "", "javascript", "css", "browser", "caching", "" ]
I was just told that I might have to work on a project where i will be working with ASP.NET 3.5 and C#. Someone in our team said that we should change all the pages to HTML when we publish the site. So instead of having *www.test.com/Page.aspx* we will have *www.test.com/Page.html* **So what i would like to know is:** A.) How can this be done and with what tool? B.) Why should this be done and what can we benefit from it? (Was told to prevent hackers to get it) C.) Is this recommended? Thanks in advance.
A) You do it by changing Web.config: ``` <system.web> <httpHandlers> <add verb="*" path="*.html" type="System.Web.UI.PageHandlerFactory"/> </httpHandlers> </system.web> ``` B) The reason would be to prevent viewers from knowing what runtime is behind the site, but in most cases with ASP.NET, it's easy to recognize from its additions to the HTML (such as view state etc.) C) It's up to you really, I wouldn't say it's good or bad. --- ### In response to your comment below: It's possible that you need to specify a `buildHandler` as well: ``` <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true"> <buildProviders> <add extension=".html" type="System.Web.Compilation.PageBuildProvider" /> </buildProviders> </compilation> <httpHandlers> <add verb="*" path="*.html" type="System.Web.UI.PageHandlerFactory" /> </httpHandlers> </system.web> </configuration> ```
B) C) If the urls are public, you should put in url's relevant information, and things that are unlikely to change in the next 10-20 years (or more..), and that would be: * a short description about the presented page These things may change over time: * ids - if you port the data to other systems * .html .php .jsp .do .aspx if you change the technology * /controller/view/main if you rearrange the structure of your site If the urls are private, it doesn't really matter how you construct them, as long as it helps your application.
Why do some people turn their asp.net pages into HTML pages when published?
[ "", "c#", "asp.net", "html", "security", "" ]
The method below called **UserCanAccessThisPage** is based on the following logic: each user and each page has a list of groups. If any of these match, the user has access to the page. The code below does what I want, but **my solution is very C# 1** (or C# 2, at least I didn't use ArrayList). Can anyone **refactor this** so it is more straight-forward, e.g. using lambdas to do away with the two methods? I just can't get the syntax to do it. ``` using System; using System.Collections.Generic; using System.Linq; namespace TestCompare2343 { class Program { static void Main(string[] args) { string anonymousUserAccessGroups = "loggedOutUsers"; string normalUserAccessGroups = "loggedInUsers, members"; string developerUserAccessGroups = "loggedInUsers, members, administrators, developers"; string loginPageAccessGroups = "loggedOutUsers"; string logoutPageAccessGroups = "loggedInUsers"; string memberInfoPageAccessGroups = "members"; string devPageAccessGroups = "developers"; //test anonymousUser Console.WriteLine(StringHelpers.UserCanAccessThisPage(anonymousUserAccessGroups, loginPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(anonymousUserAccessGroups, logoutPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(anonymousUserAccessGroups, memberInfoPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(anonymousUserAccessGroups, devPageAccessGroups)); Console.WriteLine("---"); //test anonymousUser Console.WriteLine(StringHelpers.UserCanAccessThisPage(normalUserAccessGroups, loginPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(normalUserAccessGroups, logoutPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(normalUserAccessGroups, memberInfoPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(normalUserAccessGroups, devPageAccessGroups)); Console.WriteLine("---"); //test anonymousUser Console.WriteLine(StringHelpers.UserCanAccessThisPage(developerUserAccessGroups, loginPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(developerUserAccessGroups, logoutPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(developerUserAccessGroups, memberInfoPageAccessGroups)); Console.WriteLine(StringHelpers.UserCanAccessThisPage(developerUserAccessGroups, devPageAccessGroups)); Console.WriteLine("---"); Console.ReadLine(); } } public class StringHelpers { public static bool UserCanAccessThisPage(string userAccessGroups, string pageItemAccessGroups) { List<string> userAccessGroupsList = StringHelpers.SplitAndTrimCommaDelimitedString(userAccessGroups); List<string> pageItemAccessGroupList = StringHelpers.SplitAndTrimCommaDelimitedString(pageItemAccessGroups); foreach (string userAccessGroup in userAccessGroupsList) { foreach (string pageItemAccessGroup in pageItemAccessGroupList) { if (userAccessGroup == pageItemAccessGroup) return true; } } return false; } public static List<string> SplitAndTrimCommaDelimitedString(string line) { List<string> piecesWithSpaces = line.Split(',').ToList<string>(); List<string> piecesWithoutSpaces = new List<string>(); foreach (string pieceWithSpace in piecesWithSpaces) { piecesWithoutSpaces.Add(pieceWithSpace.Trim()); } return piecesWithoutSpaces; } } } ``` # Answer: Fredrik had the most concise code that solved the original task above: ``` public static bool UserCanAccessThisPage(string userAccessGroups, string pageItemAccessGroups) { return userAccessGroups .Split(',') .Select(s => s.Trim()) .Contains(pageItemAccessGroups); } ``` # The code I used: But Shaul was correct in assuming that the PageItems can also have multiple entries, e.g. "members,guests", and so I actually used Shaul's code: ``` public static bool UserCanAccessThisPage(string userAccessGroups, string pageItemAccessGroups) { List<string> userAccessGroupsList = StringHelpers.SplitAndTrimCommaDelimitedString(userAccessGroups); List<string> pageItemAccessGroupList = StringHelpers.SplitAndTrimCommaDelimitedString(pageItemAccessGroups); return userAccessGroupsList.Any(userAccessGroup => pageItemAccessGroupList.Any(pageItemAccessGroup => userAccessGroup == pageItemAccessGroup)); } public static List<string> SplitAndTrimCommaDelimitedString(string line) { return line.Split(',').Select(s => s.Trim()).ToList(); } ```
StringHelpers could look like this: ``` public class StringHelpers { private static readonly char[] separator = ",".ToCharArray(); public static bool UserCanAccessThisPage( string userAccessGroups, string pageItemAccessGroups) { return userAccessGroups .Split(separator) // split on comma .Select(s => s.Trim()) // trim elements .Contains(pageItemAccessGroups); // match } } ```
OK, you said you wanted compact...! :) ``` public static bool UserCanAccessThisPage(string userAccessGroups, string pageItemAccessGroups) { List<string> userAccessGroupsList = StringHelpers.SplitAndTrimCommaDelimitedString(userAccessGroups); List<string> pageItemAccessGroupList = StringHelpers.SplitAndTrimCommaDelimitedString(pageItemAccessGroups); return userAccessGroupsList.Any(userAccessGroup => pageItemAccessGroupList.Any(pageItemAccessGroup => userAccessGroup == pageItemAccessGroup)); // or: // return userAccessGroupsList.Any(userAccessGroup => pageItemAccessGroupList.Contains(userAccessGroup)); } public static List<string> SplitAndTrimCommaDelimitedString(string line) { return line.Split(',').Select(s => s.Trim()).ToList(); } ```
What is the shortest code to compare two comma-separated strings for a match?
[ "", "c#", "lambda", "" ]
I am building a 'keyword' highlighting script and I need to write a regular expression to parse the following url, to find the searched for keywords to highlight. I am REALLY bad with regex, so I was hoping someone who rocks it, could help. Our search string uses "skw" as the parameter and "%2c" (comma) to separate terms, with "+" for spaces. Example URLS: <http://[url].com/Search.aspx?skw=term1> <http://[url].com/Search.aspx?skw=term1%2c+term2> Is there a single RegExp that I can use that will give me a collection that looks like this? ``` var "http://[url].com/Search.aspx?skw=term+one%2c+term2".match([Expression]); matches[0] = "term one" matches[1] = "term2" ``` Thanks! Any help is greatly appreciated.
``` https?://[^\?]+\?skw=([^%]*)(?:%2c\+*(.*))? ``` In javascript this is ``` var myregexp = /https?:\/\/[^\?]+(?:\?|\?[^&]*&)skw=([^%]*)(?:%2c\+*(.*))?/; var match = myregexp.exec(subject); if (match != null && match.length > 1) { var term1 = match[1]; var term2 = match[2]; } ``` EDIT: Sorry, I re-read your question, to handle multiple terms you need to combine this with a split ``` var subject = "http://[url].com/Search.aspx?skw=term1+one%2c+term2"; var myregexp = /https?:\/\/[^\?]+(?:\?|\?[^&]*&)skw=([^&]*)?/; var match = myregexp.exec(subject); if (match != null && match.length > 1) { var terms = unescape(match[1]).split(","); } ```
You can't do this with a single match, but you can do it with a matches, a replace and a split: ``` url.match(/\?(?:.*&)?skw=([^&]*)/)[1].replace(/\+/g, " ").split('%2c') ``` You may want to do the match separately and bail out if the match fails (which it could if yur URL didn't have an skw parameter). You probably really want to do an unescape too, to handle other escaped characters in the query: ``` unescape(url.match(/\?(?:.*&)?skw=([^&]*)/)[1].replace(/\+/g, " ")).split(',') ```
Regex/Javascript Help - Search URL term Parsing
[ "", "javascript", "regex", "parsing", "" ]
I've been looking recently at Boost.Spirit (the version included in Boost 1.39), however I'm quite confused from the docs alone. What I'm looking for is for an example of a toy language implemented with Boost.Spirit -- something along the lines of a tiny Javascript or Lua or so, where you basically create an AST and process is. I'd be happy if it just supports function/variable definitions and the basic operators, I just want to see how you would create a normal AST using Boost.Spirit, and how to implement basic rules like identifiers, declarations, etc. So far, I've tried the calculator example, but it's unclear for me how to implement a larger grammar with Spirit. The mini\_c example which is bundled on the other hand looks quite complicated already, and it's not too well documented. Is there some easy to understand guide to Boost.Spirit out there, or a book maybe?
[An introductory article from CP](http://www.codeproject.com/KB/stl/introduction_spirit.aspx) [A JSON parser implemented using Boost.Spirit from CodeProject](http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx) [Spirit Application Repository](http://spirit.sourceforge.net/repository/applications/show_contents.php)
The Spirit documentation includes examples and tutorials. An example for [generating an AST for a mini XML-like language](http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/qi/tutorials/mini_xml___asts_.html) is included. A very useful [overview presentation by Joel de Guzman and Hartmut Kaiser](http://boost-spirit.com/home/wp-content/uploads/2010/05/A_Framework_for_RAD_Spirit.pdf) is also available.
Getting started guide for Boost.Spirit?
[ "", "c++", "boost-spirit", "" ]
I am using this function to close existing form and open a new form. If there is no exixting form, it throws error. Error : Target : System.Object MarshaledInvoke(System.Windows.Forms.Control, System.Delegate, System.Object[], Boolean) Message : Invoke or BeginInvoke cannot be called on a control until the window handle has been created. Stack : at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous) SO need to check for any form open before closing the form to avoid the error. How? ``` static public void NewMainForm(Form main, bool ClosePreviousMain) { if (main != null) { Global.ActiveForm = main.Text; if (ClosePreviousMain & MyContext.curMain != null) { MyContext.curMain.FormClosed -= new FormClosedEventHandler(main_FormClosed); //Need to check for any form active and then close the form. MyContext.curMain.Invoke(new Action(MyContext.curMain.Dispose)); } MyContext.curMain = main; MyContext.curMain.FormClosed += new FormClosedEventHandler(main_FormClosed); MyContext.curMain.ShowDialog(); } } ```
You can use the [Application.OpenForms](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.openforms.aspx) collection.
``` if (ApplicationFormStatus.CheckIfFormIsOpen("FormName")) { // It means it exists, so close the form } public bool CheckIfFormIsOpen(string formname) { //FormCollection fc = Application.OpenForms; //foreach (Form frm in fc) //{ // if (frm.Name == formname) // { // return true; // } //} //return false; bool formOpen= Application.OpenForms.Cast<Form>().Any(form => form.Name == formname); return formOpen; } ``` I have pasted the two methods one simple one and the second one is the LINQ.
Find the open forms in c# windows application
[ "", "c#", "windows", "winforms", "" ]
Is there any magic tools i can use to scan source code that was written for PHP4 to highlight deprecated functions in PHP5? I'm currently running the latest version of PHP on a server and need to port this code. Is there anything out there that can give me a hand?
PHP 5.3 will throw an [`E_DEPRECATED`](http://us.php.net/manual/en/migration53.deprecated.php) warning if you set your error reporting levels to show them.
I wanted to do something like this myself. Using this list of [deprecated features in PHP 5.3.x](http://php.net/manual/en/migration53.deprecated.php), I made a regex to search for any use of these functions: ``` (?i:(call_user_method\(|call_user_method_array\(|define_syslog_variables\(|dl\(|ereg\(|ereg_replace\(|eregi\(|eregi_replace\(|set_magic_quotes_runtime\(|session_register\(|session_unregister\(|session_is_registered\(|set_socket_blocking\(|split\(|spliti\(|sql_regcase\(|mysql_db_query\(|mysql_escape_string\()) ``` *(Case insensitive, with each function name including the opening parenthesis just to avoid false positives; "dl" would bring up lots of noise otherwise.)* If you're on a system with `find` and `grep`, you could then just execute something like this: ``` find <directory to search> -type f -name '*.php' -exec grep -R -P -H "<above regex>" {} \; ``` Just to make a more concrete example, I just used the following: ``` find htdocs -type f -name '*.php' -exec grep -R -P -H "(?i:(call_user_method\(|call_user_method_array\(|define_syslog_variables\(|dl\(|ereg\(|ereg_replace\(|eregi\(|eregi_replace\(|set_magic_quotes_runtime\(|session_register\(|session_unregister\(|session_is_registered\(|set_socket_blocking\(|split\(|spliti\(|sql_regcase\(|mysql_db_query\(|mysql_escape_string\())" {} \; ``` Looks like I now need to replace a few instances of `session_register` and `session_unregister` myself! The same sort of thing could be done for deprecated INI directives and parameters.
Tools to highlight deprecated functions in PHP4 sources?
[ "", "php", "deprecated", "" ]
I have web application written in java using Eclipse. It has just one servlet that does some file manipulations. How do I build war file so I can easily deploy it to my remote server.
Right-click on the project, select 'Export...', then choose web -> WAR.
You should be able to use Maven to package a WAR to deploy to your remote server. It looks a little daunting, but once you create your own WAR file you should be ok, check out: <http://maven.apache.org/plugins/maven-war-plugin/usage.html> In fact you should be able to manage deployment using the Maven Glassfish plugin here: <https://maven-glassfish-plugin.dev.java.net/> That will allow you to start,stop,deploy,undeploy etc... your web app. Example here: <https://maven-glassfish-plugin.dev.java.net/examples/complete.html>
How do I build .war file in Eclipse for Glassfish server
[ "", "java", "eclipse", "build-process", "" ]
Im having this function to determine weather a user exists in a database or not DM is my DataModule AQ\_LOGIN an ADOQuery BENU is my Table filled with Users and their Password Here comes the code: ``` function UserCheckExist(Login, pw: string): boolean; begin with DM do begin AQ_LOGIN.Close; AQ_LOGIN.SQL.Clear; AQ_LOGIN.SQL.Add('select BLOGIN from BENU where BLOGIN = ''Login'' AND BPW = ''pw'''); AQ_LOGIN.Open; end; end; ``` My question now is: How can I make the function return true or false weather the User with the according password exists? Thanks in advance.
``` function UserCheckExist(Login, pw: string): boolean; begin with DM do begin AQ_LOGIN.Close; AQ_LOGIN.SQL.Clear; AQ_LOGIN.SQL.Add('select BLOGIN from BENU where BLOGIN = ''Login'' AND BPW = ''pw'''); AQ_LOGIN.Open; Result := (AQ_LOGIN.RecordCount > 0); AQ_LOGIN.Close; end; end; ```
I'd go with smok1's answer (I was just posting something like it) but I'd parameterise your inputs, thus; ``` AQ_LOGIN.SQL.Add('select count(*) from BENU where BLOGIN=:login and BPW=:pw'); AQ_LOGIN.Parameters.ParamByName('login').AsString:=login; AQ_LOGIN.Parameters.ParamByName('pw').AsString:=pw; ``` then as with smok1 - open the dataset and look at the value of the returned count. NB - don't have an ADO delphi component handy but 99.9% sure that's the syntax :-) edit: one of the advantages of using parameters like this is that you won't have to sanitise your input strings (for things like quotes) - the component knows what to do with your strings. You wouldn't expect to have a username with a single quote in it, but you might have a password with one. :-)
SQL Return values in Delphi via ADO
[ "", "sql", "delphi", "ado", "" ]
I was wondering if ``` synchronize (lock) { ... } ``` Where lock is an instance of `java.util.concurrent.locks.Lock`, treats `lock` like any other object or as the try-finally idiom i.e. ``` lock.lock(); try { ... } finally { lock.unlock(); } ```
[Lock documentation](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html): > Note that Lock instances are just > normal objects and can themselves be > used as the target in a synchronized > statement. Acquiring the monitor lock > of a Lock instance has no specified > relationship with invoking any of the > lock() methods of that instance. It is > recommended that to avoid confusion > you never use Lock instances in this > way, except within their own > implementation. So basically, it's treated as any other object. And, don't do that.
It will treat the lock just like any other object.
Java synchronize statement around a lock
[ "", "java", "multithreading", "synchronization", "locking", "" ]
I am in the process of creating an input form on a record specific page e.g. (property/rentals/rec\_id). On submission, the data should be inserted, validated and return to the original page from which it was sent with any relevant messages. * If the validation fails, reload the form page a re-populate the form * Echo the specific validation error - e.g. invalid email address etc * If successful, insert data, reload the page and display success message. function class() { ``` $this->load->library('form_validation'); $this->form_validation->set_rules('name','name','required|trim'); $this->form_validation->set_rules('email','email','required|trim|valid_email'); $fields['name'] = 'Name'; $fields['email'] = 'Email Address'; $this->validation->set_fields($fields); if ($this->form_validation->run() == FALSE) { //failed - reload page and re-populate fields with any error messages } else { // display form with success message } ``` } Normally this is simply done by 'loading a view' and passing the relevant data to repopulate the page, fields or display messages. But I have to use a 'redirect' back to the product specific page. Is there any good way to do this other than using session data to carry the validation errors..? Thanks in advance, Michael
Take a look at the CodeIgniter manual on Sessions and see if 'FlashData' is of any use.
You may use the `set_value('field_name')` function to re-populate the form. Sample usage in view: > `<input type="text name="name" value="<?php echo set_value('name'); ?>" />"` To display the errors from the form\_validation, you may use the `validation_errors()` function. Sample usage in view: > `<?php echo validation_errors(); ?>` Also, see [link text](http://codeigniter.com/user_guide/libraries/form_validation.html) for more info.
Codeigniter Form Validation...form re-population
[ "", "php", "validation", "codeigniter", "" ]
data: ``` id bb 1 14,35 2 5,11,12,125,36 3 3,23,45,15,1 4 651 5 5,1,6 6 1,7 ``` For example, i wan't get id which with value '1'. So id(3,5,6) should return , but not others with '14' or '11'. DB: Mysql
``` select * from test where find_in_set('1',bbb) ``` or ``` select * from test where bbb REGEXP '(^|,)1(,|$)' ```
This is not the most efficient solution but it might give you what you want off the table: ``` select id from MyTable where bb like '%,1,%' union select id from MyTable where bb like '1,%' union select id from MyTable where bb like '%,1' union select id from MyTable where bb like '1' ``` cheers
How to get result from a column with combined data?
[ "", "sql", "mysql", "" ]
How can hibernate can access a private field/method of a java class , for example to set the @Id ? Thanks
Like Crippledsmurf says, it uses reflection. See [Reflection: Breaking all the Rules](http://www.eclipsezone.com/eclipse/forums/t16714.html) and [Hibernate: Preserving an Object's Contract](http://www.javalobby.org/java/forums/m91937279.html#).
Try ``` import java.lang.reflect.Field; class Test { private final int value; Test(int value) { this.value = value; } public String toString() { return "" + value; } } public class Main { public static void main(String... args) throws NoSuchFieldException, IllegalAccessException { Test test = new Test(12345); System.out.println("test= "+test); Field value = Test.class.getDeclaredField("value"); value.setAccessible(true); System.out.println("test.value= "+value.get(test)); value.set(test, 99999); System.out.println("test= "+test); System.out.println("test.value= "+value.get(test)); } } ``` prints ``` test= 12345 test.value= 12345 test= 99999 test.value= 99999 ```
How can hibernate access a private field?
[ "", "java", "hibernate", "reflection", "field", "private", "" ]
I have narrowed down my problem to the `mysql_connect` call I am doing in PHP. It produces an error message. What would you suggest I should do to fix the problem with this error: > Error Summary > HTTP Error 500.0 - Internal Server Error > The page cannot be displayed because an internal server error has occurred. > > > Detailed Error Information > > Module IsapiModule > > Notification ExecuteRequestHandler > > Handler PHP > > Error Code 0x00000000 > > Requested URL <http://localhost:80/getuser.php?q=3&sid=0.2953613724031635> > > Physical Path C:\inetpub\wwwroot\getuser.php > > Logon Method Anonymous > > Logon User Anonymous > > Most likely causes: > > * IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. > * IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. > * IIS was not able to process configuration for the Web site or application. > * The authenticated user does not have permission to use this DLL. > * The request is mapped to a managed handler but the .NET Extensibility Feature is not installed. > > Things you can try: > > * Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account. > * Check the event logs to see if any additional information was logged. > * Verify the permissions for the DLL. > * Install the .NET Extensibility feature if the request is mapped to a managed handler. > * Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here. > > Links and More InformationThis error means that there was a problem while processing the request. The request was received by the Web server, but during processing a fatal error occurred, causing the 500 error. > > Microsoft Knowledge Base Articles: > > * 294807
Check phpinfo() for presence of MySQL functions. If those exist, try connecting to other MySQL servers. Try to narrow down if the problem is with your code, your PHP library, your SQL server or your web server by changing variables. CHeck for logs, I know Apache has an error log where detailed PHP error information goes -- IIS probably has something similar. Consider recompiling and reinstalling PHP.
Though Avinash mentioned apache, he may be on the right track in the sense that you could be missing the actual library for mysql to interact with IIS. I didn't read through the whole thing, but this may help you out: <http://www.atksolutions.com/articles/install_php_mysql_iis.html> Also, I saw your response to Josh... You should have a table in your phpinfo for mysql.
mysql_connect error 500
[ "", "php", "mysql", "iis", "" ]
This may be silly, but it's been nagging the back of my brain for a while. Python gives us two built-in ways to delete attributes from objects, the **del** command word and the **delattr** built-in function. I prefer **delattr** because it I think its a bit more explicit: ``` del foo.bar delattr(foo, "bar") ``` But I'm wondering if there might be under-the-hood differences between them.
The first is more efficient than the second. `del foo.bar` compiles to two bytecode instructions: ``` 2 0 LOAD_FAST 0 (foo) 3 DELETE_ATTR 0 (bar) ``` whereas `delattr(foo, "bar")` takes five: ``` 2 0 LOAD_GLOBAL 0 (delattr) 3 LOAD_FAST 0 (foo) 6 LOAD_CONST 1 ('bar') 9 CALL_FUNCTION 2 12 POP_TOP ``` This translates into the first running *slightly* faster (but it's not a huge difference – .15 μs on my machine). Like the others have said, you should really only use the second form when the attribute that you're deleting is determined dynamically. [Edited to show the bytecode instructions generated inside a function, where the compiler can use `LOAD_FAST` and `LOAD_GLOBAL`]
* **del** is more explicit and efficient; * **delattr** allows dynamic attribute deleting. Consider the following examples: ``` for name in ATTRIBUTES: delattr(obj, name) ``` or: ``` def _cleanup(self, name): """Do cleanup for an attribute""" value = getattr(self, name) self._pre_cleanup(name, value) delattr(self, name) self._post_cleanup(name, value) ``` You can't do it with **del**.
Which is better in python, del or delattr?
[ "", "python", "del", "" ]
I'm working with a [`DOMDocument`](https://php.net/manual/en/class.domdocument.php), and I'm wondering if there exists some way of using CSS-like selectors to select nodes like we would in [jQuery](https://api.jquery.com/category/selectors/). Example situation: I'm parsing an XML file, one snippet of which looks like this: ``` <gesmes:Envelope> <gesmes:subject>Reference rates</gesmes:subject> <gesmes:Sender> <gesmes:name>European Central Bank</gesmes:name> </gesmes:Sender> <Cube> <Cube time="2009-07-13"> <Cube currency="USD" rate="1.3975"/> <Cube currency="JPY" rate="129.03"/> <Cube currency="BGN" rate="1.9558"/> <Cube currency="CZK" rate="26.028"/> </Cube> </Cube> </gesmes:Envelope> ``` Accessing this structure with jQuery-like selectors would be dead simple. For example, I could use ``` $("Cube[currency]") ``` to retrieve all the `Cube` elements with the 'currency' attribute. But how can I do the same thing with PHP's `DOMDocument`? I'd like to select elements which have an attribute, or have a particular attribute value.
If you want to manipulate the DOM ala Jquery, PHPQuery is something for you. <http://code.google.com/p/phpquery/> A simple example of what you can do with it. ``` // almost everything can be a chain $li = null; $doc['ul > li'] ->addClass('my-new-class') ->filter(':last') ->addClass('last-li'); ```
Take a look at the [`DOMXPath`](http://php.net/manual/en/class.domxpath.php) class in PHP. It uses XPath, so you'll need to read up on XPath syntax if you're unfamiliar with it. There's some documentation on [MSDN](https://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx), or you can read the [W3 spec](http://www.w3.org/TR/xpath/) if you're particularly brave. To solve your example problem: `//cube[@currency]` is an XPath query that selects all elements in the document with a currency attribute. Usage of this with the `DOMXPath` class would look like this: ``` $xpath = new DOMXpath($myDomDocument); $cubesWithCurrencies = $xpath->query('//cube[@currency]'); ``` `$cubesWithCurrencies` is now a [`DOMNodeList`](http://php.net/manual/en/class.domnodelist.php) that you can iterate over.
jQuery-like selectors for PHP DOMDocument
[ "", "php", "jquery", "css", "xml", "css-selectors", "" ]
I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it'd be nice to not run. Is there a way to do this using JavaScript? My reference point: Gmail Chat plays a sound if the window you're using isn't active.
Since originally writing this answer, a new specification has reached *recommendation* status thanks to the W3C. The [Page Visibility API](http://www.w3.org/TR/page-visibility/) (on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API)) now allows us to more accurately detect when a page is hidden to the user. ``` document.addEventListener("visibilitychange", onchange); ``` Current browser support: * Chrome 13+ * Internet Explorer 10+ * Firefox 10+ * Opera 12.10+ [[read notes](https://dev.opera.com/blog/page-visibility-api-support-in-opera-12-10/)] The following code falls back to the less reliable blur/focus method in incompatible browsers: ``` (function() { var hidden = "hidden"; // Standards: if (hidden in document) document.addEventListener("visibilitychange", onchange); else if ((hidden = "mozHidden") in document) document.addEventListener("mozvisibilitychange", onchange); else if ((hidden = "webkitHidden") in document) document.addEventListener("webkitvisibilitychange", onchange); else if ((hidden = "msHidden") in document) document.addEventListener("msvisibilitychange", onchange); // IE 9 and lower: else if ("onfocusin" in document) document.onfocusin = document.onfocusout = onchange; // All others: else window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange; function onchange (evt) { var v = "visible", h = "hidden", evtMap = { focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h }; evt = evt || window.event; if (evt.type in evtMap) document.body.className = evtMap[evt.type]; else document.body.className = this[hidden] ? "hidden" : "visible"; } // set the initial state (but only if browser supports the Page Visibility API) if( document[hidden] !== undefined ) onchange({type: document[hidden] ? "blur" : "focus"}); })(); ``` `onfocusin` and `onfocusout` are [required for IE 9 and lower](http://www.thefutureoftheweb.com/blog/detect-browser-window-focus), while all others make use of `onfocus` and `onblur`, except for iOS, which uses `onpageshow` and `onpagehide`.
I would use jQuery because then all you have to do is this: ``` $(window).blur(function(){ //your code here }); $(window).focus(function(){ //your code }); ``` Or at least it worked for me.
Is there a way to detect if a browser window is not currently active?
[ "", "javascript", "browser", "focus", "window", "" ]
I tried following the answer to [this question](https://stackoverflow.com/questions/87621/how-do-i-map-xml-to-c-objects), but could not get xsd.exe to happily take the XSD files and turn them into a class. Using the XSD files here: <http://download.adamhaile.com/SO/XSD.zip> Can anyone help me convert these to a valid C# class that can then be used to serialize an XML document to? Note: Yes, these are from an undocumented Yahoo Movies API that I'm trying to use. It looks like it's using a standard Microsoft based schema pattern, so I would imagine this is quite possible. Here is an example of the results from one of the API calls: <http://new.api.movies.yahoo.com/v2/listTheatersByPostalCode?pcode=12345&count=30&yprop=msapi> <http://download.adamhaile.com/SO/XSD.zip>
Be sure to put all referenced schemas on the cmd line. When I do this, I get a bunch of warnings. ``` $ xsd /c listTheatersByPostalCode.xsd yahooMovie.xsd yahooMovieCredit.xsd yahooMovieMedia.xsd yahooMoviePhoto.xsd yahooMovieTheater.xsd yahooMovieTheaterAmenity.xsd yahooMultimedia.xsd yahooUser.xsd Microsoft (R) Xml Schemas/DataTypes support utility [Microsoft (R) .NET Framework, Version 2.0.50727.42] Copyright (C) Microsoft Corporation. All rights reserved. Schema validation warning: The global element 'urn:yahoo:movie:theater:TheaterList' has already been declared. Line 6, position 4. Schema validation warning: The global attribute 'urn:yahoo:movie:theater:id' has already been declared. Line 7, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:TheaterListType' has already been declared. Line 10, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:TheaterType' has already been declared. Line 19, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:PostalAddressType' has already been declared. Line 32, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:AmenityListType' has already been declared. Line 55, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:MovieListType' has already been declared. Line 65, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:MovieType' has already been declared. Line 71, position 4. Schema validation warning: The complexType 'urn:yahoo:movie:theater:ShowsType' has already been declared. Line 82, position 4. Warning: Schema could not be validated. Class generation may fail or may produce incorrect results. ``` If I yank out yahooTheater.xsd from that list, it works fine. I didn't even look at the XSDs but it seems to me that xsd.exe thinks some elements have been doubly defined. you may be able to manually reconcile that problem by combining yahootheater.xsd with yahooTheaterAmenity.xsd. Or, if you don't care about the amenity part, drop it.
Use the xsd.exe that comes with visual studio. iirc xsd /classes theschema.xsd But since you tried that, what went wrong ?
Convert XSD files to C# Serializable Class
[ "", "c#", "xml", "xsd", "" ]
How can I programmatically tell if the terminal services service is running and is healthy? I'm creating a .net console application that will check if terminal services are running on a list of computers. I can check the remote registry entry to see if it's enabled, but that doesn't mean it's running. I was thinking of making a socket connection to port 3389, but it doesn't have to be listening on that port either. Is there an elegant way to check for this? Regards,
If you (or, specifically, the user the application runs as) has permission to do so, you could remotely query the SCM of the target machine to determine if the TS service is running. You should be able to use System.ServiceProcess.ServiceController.GetServices(string machineName) to get a list of all the services on the computer, iterate the result to find the Terminal Services service and query its status.
Never done anything with it, but WMI is probably the way to go to check processes on remote computers, etc.
How to programmatically tell if the terminal server service is running
[ "", "c#", ".net", "terminal", "service", "" ]
I have a memory block that is divided into a series of location that can be retrieved and returned by client code. The method that returns locations back looks like this: ``` void ReturnLocation(void *address) { int location = AddressToLocation(address); // I need the location here // some code DoSmthA(location); } void DoSmthA(int location) { // I need the address, but also the location void *address = LocationToAddress(location); // do something with the address DoSmthB(location); } void DoSmthB(int location) { // Again, I need the address, but also the location void *address = LocationToAddress(location); // do something with the address DoSmthC(location); // It may go on this way... } // ------------------------------------------------------ void* LocationToAddress(int location) { return (void *)((char *)this + HEADER_SIZE + (location * LocationSize)); } int AddressToLocation(void *address) { return (int)(((__int64)address - HEADER_SIZE - (__int64)this) / LocationSize); } ``` My question is: should I pass only the location to the helper methods, or it is faster to pass each time the address too (and not compute it again and again): ``` void DoSmthA(int location, void *address) { } ``` or even better to use a struct like this: ``` struct LocationInfo { int Location; void *Address; }; void DoSmthA(LocationInfo locInfo) { } ``` This methods may be called million of times and I'm not sure if the operations to compute the address from the location (two additions and one multiplication) are faster or slower than passing a second parameter containing the address. Thanks in advance!
Profile it. Do what is *actually* faster in your case, on your compiler and with your code base. Not what was faster in my unrelated test, on my unrelated compiler. Passing an argument to a function is a pretty cheap operation. A stack push/pop, basically. Computing the location might be very fast, if the division can be optimized away (depends on the value of LocationSize, and whether it is known at compile-time). So try both, see which is faster in the real world. CPU's are complex beasts, and performance is not trivial.
You're getting into the kind of optimization where different combination of CPU/compiler and even memory controler can make a difference. We're talking about 1,000,000's of operations only, unless you're adding a few 0's to it, I don't think you can even measure the difference in performance. So, do whatever is easier for maintenance. Developer time is 100x machine time IMO.
Cost of passing an optional parameter to a method rather than computing it
[ "", "c++", "performance", "optimization", "memory", "" ]
I have a variable that im define with another variable and some text. ``` $title = "New Amsbrook School" //demo text $message = "$title just added, Congrats!"; ``` Echoing of $message returns New just added, Contrats! Problem is if there is a space in $title, it breaks and doesnt show the rest of the contents.
Needs a semi-colon at the end of the first line, before the comment.
You missed a semicolon at the end of $title string ;-)
php variable inside another variable
[ "", "php", "" ]
I have a menu: ``` <ul> <li id="active"><a href="/">Головна</a></li> <li><a href="/about/">Про компанію</a></li> <li><a href="/work/">Діяльність</a></li> <li><a href="/initiative/">Ініціативи</a></li> <li><a href="/statti/">Статті</a></li> </ul> ``` Can you suggest a way to change id=active attribute for this list. If for example I clicked on about, I want this li element to be marked as active. Thanks
There is [an elegant css method](http://www.456bereastreet.com/archive/200503/setting_the_current_menu_state_with_css/) of styling the currently active navigation state without any javascript or server side support. Basically one id (e.g. as body id attribute) that uniquely identifies the navigation state is enough to create css selectors that highlight the active state.
Use class, not id. The reason is that id is for identifying elements, which in this case would mean that the only element in the page identified by "active" would be this one, even if you have other contexts needing an "actiuve" distinction. Using class lets you have several "active" elements in different context, and is more semantically correct.
JS: Specifying current element in the menu
[ "", "javascript", "html", "css", "" ]
In python 2.6, the following code: ``` import urlparse qsdata = "test=test&test2=test2&test2=test3" qs = urlparse.parse_qs(qsdata) print qs ``` Gives the following output: ``` {'test': ['test'], 'test2': ['test2', 'test3']} ``` Which means that even though there is only one value for test, it is still being parsed into a list. Is there a way to ensure that if there's only one value, it is not parsed into a list, so that the result would look like this? ``` {'test': 'test', 'test2': ['test2', 'test3']} ```
You could fix it afterwards... ``` import urlparse qsdata = "test=test&test2=test2&test2=test3" qs = dict( (k, v if len(v)>1 else v[0] ) for k, v in urlparse.parse_qs(qsdata).iteritems() ) print qs ``` However, I don't think *I* would want this. If a parameter that is normally a list happens to arrive with only one item set, then I would have a string instead of the list of strings I normally receive.
A sidenote for someone just wanting a simple dictionary and never needing multiple values with the same key, try: ``` dict(urlparse.parse_qsl('foo=bar&baz=qux')) ``` This will give you a nice `{'foo': 'bar', 'baz': 'qux'}`. Please note that if there *are* multiple values for the same key, you'll only get the last one.
How to stop Python parse_qs from parsing single values into lists?
[ "", "python", "python-2.6", "" ]
Or are we all sticking to our taught "&&, ||, !" way? Any thoughts in why we should use one or the other? I'm just wondering because several answers state thate code should be as natural as possible, but I haven't seen a lot of code with "and, or, not" while this is more natural.
Those were not supported in the old days. And even now you need to give a special switch to some compilers to enable these keywords. That's probably because old code base may have had some functions || variables named "and" "or" "not".
I like the idea of the `not` operator because it is more visible than the `!` operator. For example: ``` if (!foo.bar()) { ... } if (not foo.bar()) { ... } ``` I suggest that the second one is more visible and readable. I don't think the same argument necessarily applies to the `and` and `or` forms, though.
Is anybody using the named boolean operators?
[ "", "c++", "boolean", "" ]
Currently I have a lot of python objects in my code similar to the following: ``` class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] ``` Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings. ``` from django.db import models class myDjangoModelClass(): myName = models.CharField(max_length=64) myFriends = ??? # what goes here? ``` Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code. **Edit:** I added this [related question](https://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list), which people may find useful.
Would this relationship not be better expressed as a one-to-many foreign key relationship to a `Friends` table? I understand that `myFriends` are just strings but I would think that a better design would be to create a `Friend` model and have `MyClass` contain a foreign key realtionship to the resulting table.
## **"Premature optimization is the root of all evil."** With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping. To return a `list` of friend names we'll need to create a custom Django Field class that will return a list when accessed. David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code: ``` from django.db import models class SeparatedValuesField(models.TextField): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): self.token = kwargs.pop('token', ',') super(SeparatedValuesField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return if isinstance(value, list): return value return value.split(self.token) def get_db_prep_value(self, value): if not value: return assert(isinstance(value, list) or isinstance(value, tuple)) return self.token.join([unicode(s) for s in value]) def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_db_prep_value(value) ``` The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class: ``` from django.db import models from custom.fields import SeparatedValuesField class Person(models.Model): name = models.CharField(max_length=64) friends = SeparatedValuesField() ```
What is the most efficient way to store a list in the Django models?
[ "", "python", "django", "django-models", "" ]
I wrote an application which allows people to contribute plugins to extend the functionality. Such plugins are deployed as DLL files, which the framework picks up during runtime. Each plugin features a factory function which is called multiple times during the lifetime of the application to create objects. So far, in order to handle the ownership issue with these objects, I used a simple counting shared pointer on the returned objects so that they are destroyed whenever the last reference is removed. However, this tends to trigger crashes on Windows since it's not unlikely to happen that the object is new'ed in the plugin DLL but later (due to a deref() call on the shared pointer) deleted in the main application - and AFAIK this malloc/free mixup is a no-no on Windows. My current solution to this is to let deref() not call 'delete this;' directly but rather a 'release();' function which must be implemented by the plugins and calls 'delete this;'. However, it's quite annoying that each and every plugin has to implement this trivial function - I worked around this so far by providing a convenience macro plugin authors have to use. Does anybody have alternative ideas maybe? So far, my approach is that all objects contributed by plugins is allocated in the plugins and also released there - of course, an alternative might be to let all memory be allocated in the main application (by providing a pointer to a malloc-like function to the plugins which they can then call as needed) and released there as well. The issue with this is that it's not as convenient for the plugin authors, I think. I'd be interested in any other perspectives on this issue. *UPDATE:* I just realized that I could reimplement operator new and operator delete on the baseclass of the objects returned by the plugins, so that new'ing them and delete'ing them will always result in function calls into the same module (so that either all allocations and free's are done in the plugin, or in the framework).
There are two solutions. Solution one is "share more" - you can move new/delete across DLL boundaries if both sides use the same CRT DLL (/MD or /MDd in MSVC). Solution two is "share less" - let each DLL have its own C++ heap, and do not split new/delete across DLL boundaries.
It turned out that the easiest way to make sure that memory is not allocated in one DLL and released in another is this: reimplement `operator new` and `operator delete` on the base class of the objects which are returned from the plugins. In the implementations of these functions, call 'alloc' and 'free' functions (which have been passed from the main application when loading the plugin). That way, plugins can keep using 'new' and 'delete' but the memory will actually be allocated and released in the main application.
DLL memory manager mixup
[ "", "c++", "windows", "memory", "dll", "" ]
I'm not asking if these are truly random. I just wanted to know if two users hit the a page at the same time can they get the same random number? I'm thinking if i run this on a multicore server will i generate the same randon number a good amount of time due to syncing or whatever other reasons? ``` public static class SBackend { static Random randObj = null; public static void init() { randObj = new Random((int)DateTime.Now.ToBinary()); runFirstTime(); } public static long getRandomId() { long randNum = (long)randObj.Next() << 33; randNum |= (uint)randObj.Next() << 2; randNum |= (uint)randObj.Next() & 3; return randNum; } } ```
Yes it is possible for that to generate the same numbers. The seed adds nothing (it is time based by default anyway). Also - if it is static, you should synchronize it (`Next` is not thread-safe): ``` static readonly Random rand = new Random(); public static int NextInt32() { lock(rand) { return rand.Next();} } public static long NextInt64() { lock(rand) { // using your algorithm... long randNum = (long)rand.Next() << 33; randNum |= (uint)rand.Next() << 2; randNum |= (uint)rand.Next() & 3; return randNum; } } ``` This can **still** generate the same number by coincidence of course... Perhaps consider a cryptographic random number generator if entropy is important.
well, if you only use it to generate random numbers which are never same, why not use System.Guid.NewGuid()?
Are these random numbers 'safe'
[ "", "c#", "random", "security", "" ]
I'm building a simple game which consists of Mobiles -- the in-game characters (Mobs). Each mob can perform certain functions. In order to give that functionality to the Mob, I've created a Behavior. For example, let's say a mob needs to move around the game field, I would give it the MoveBehavior - this is added to an internal list of Behaviors for the mob class: ``` // Defined in the Mob class List<Behavior> behaviors; // Later on, add behavior... movingMob.addBehavior(new MovingBehavior()); ``` My question is this. Most behaviors will manipulate something about the mob. In the MoveBehavior example, it will change the mob's X,Y position in the world. However, each behavior needs specific information, such as "movementRate" -- where should movementRate be stored? Should it be stored in the Mob class? Other Mobs may attempt to interact with it by slowing/speeding up the mob and it's easier to access at the mob level... but not all mobs have a movementRate so it would cause clutter. Or should it be stored in the MoveBehavior class? This hides it away, making it a little harder for other mobs to interact with - but it doesn't clutter up a non-moving mob with extra and un-used properties (for example, a tower that doesn't move would never need to use the movementRate).
This is the classic "behavioral composition" problem. The trade-off is that the more independent the behaviors are, the more difficult it is for them to interact with each other. From a game programming viewpoint, the simplest solution is a decide on a set of "core" or "engine" data, and put that in the main object, then have the behaviors be able to access and modify that data - potentially through a functional interface. If you want behavior specific data, that's fine, but to avoid collisions in the names of variables, you may want to make the interface for accessing it include the behavior name. Like: ``` obj.getBehaviorValue("movement", "speed") obj.setBehaviorValue("movement", "speed", 4) ``` That way two behaviors can both define their own variables called speed and not collide. This type of cross-behavior getters and setters would allow communication when it is required. I'd suggest looking at a scripting language like Lua or Python for this..
If it is related to the behavior, and only makes sense in the context of that behavior, then it should be stored as part of it. A movement rate only makes sense for something that can move. Which means it should be stored as part of the object that represents its ability to move, which seems to be your MoveBehavior. If that makes it too hard to access, it sounds more like a problem with your design. Then the question is not "should I cheat, and place some of the variables inside the Mob class instead of the behavior it belongs to", but rather "how do I make it easier to interact with these individual behaviors". I can think of several ways to implement this. The obvious is a simple member function on the Mob class which allows you to select individual behaviors, something like this: ``` class Mob { private List<Behavior> behaviors; public T Get<T>(); // try to find the requested behavior type, and return it if it exists } ``` Others can then do something like this: ``` Mob m; MovementBehavior b = m.Get<MovementBehavior(); if (b != null) { b.SetMovementRate(1.20f); } ``` You might also place some of this outside the Mob class, creating a helper function which modifies the movement rate if it exists, and does nothing otherwise: ``` static class MovementHelper { public static SetMovementRate(Mob m, float movementrate){ MovementBehavior b = m.Get<MovementBehavior(); if (b != null) { b.SetMovementRate(1.20f); } } } ``` and then others could use it like this: ``` MovementHelper.SetMovementRate(m, 1.20f); ``` which would provide easy access to modifying the behavior, but without cluttering up the Mob class. (Of course, it'd be tempting to turn this into an extension method, but that might lead to too much assorted clutter in the Mob class' public interface. It may be preferable to make it clear that this is helper functionality that resides outside the Mob class itself)
Architecture for Game - To couple or not to couple?
[ "", "c#", "architecture", "" ]
I have always wondered how delegates can be useful and why shall we use them? Other then being type safe and all those advantages in Visual Studio Documentation, what are real world uses of delegates. I already found one and it's very targeted. ``` using System; namespace HelloNamespace { class Greetings{ public static void DisplayEnglish() { Console.WriteLine("Hello, world!"); } public static void DisplayItalian() { Console.WriteLine("Ciao, mondo!"); } public static void DisplaySpanish() { Console.WriteLine("Hola, imundo!"); } } delegate void delGreeting(); class HelloWorld { static void Main(string [] args) { int iChoice=int.Parse(args[0]); delGreeting [] arrayofGreetings={ new delGreeting(Greetings.DisplayEnglish), new delGreeting(Greetings.DisplayItalian), new delGreeting(Greetings.DisplaySpanish)}; arrayofGreetings[iChoice-1](); } } } ``` But this doesn't show me exactly the advantages of using delegates rather than a conditional "If ... { }" that parses the argument and run the method. Does anyone know why it's better to use delegate here rather than "if ... { }". Also do you have other examples that demonstrate the usefulness of delegates. Thanks!
The most common real-world everyday use of delegates that I can think of in C# would be event handling. When you have a button on a WinForm, and you want to do something when the button is clicked, then what you do is you end up registering a delegate function to be called by the button when it is clicked. All of this happens for you automatically behind the scenes in the code generated by Visual Studio itself, so you might not see where it happens. A real-world case that might be more useful to you would be if you wanted to make a library that people can use that will read data off an Internet feed, and notify them when the feed has been updated. By using delegates, then programmers who are using your library would be able to have their own code called whenever the feed is updated.
Delegates are a great way of **injecting functionality** into a method. They greatly help with **code reuse** because of this. Think about it, lets say you have a group of related methods that have almost the same functionality but vary on just a few lines of code. You could refactor all of the things these methods have in common into one single method, then you could inject the specialised functionality in via a delegate. Take for example all of the IEnumerable extension methods used by LINQ. All of them define common functionality but need a delegate passing to them to define how the return data is projected, or how the data is filtered, sorted, etc...
Uses of delegates in C# (or other languages)
[ "", "c#", ".net", "delegates", "" ]
I am trying to run jquery through a rails app. I have the edit information in a popup window and i want to change that to show information after they click update. It should work but this line ``` $(".edit_business).append("<%= escape_javascript(render(:file => 'businesses/show')) %>"); ``` is throwing an illegal character issue. This code is in my update.js.erb file. The escape\_javascript is there but it's throwing an error in my console.
Are you actually missing that quote? ``` $(".edit_business").append(...) ```
You're missing a quote in $(".edit\_business")
illegal character, Javascript
[ "", "javascript", "ruby-on-rails", "illegal-characters", "" ]
We have a git repository which contains source for a few related Java WARs and JARs. It would be nice if the Java code could somehow: ``` System.err.println("I was built from git commit " + commitID); ``` (Obviously real code might be putting this into an HTTP header, logging it on startup, or whatever, that's not important right now) We are using Ant to build (at least for production builds, it seems some programmers do their testing from inside Eclipse which I know even less about) binaries. Is there a canonical way to get the commit id for the current git checkout into our Java at build time? If not, can people using Ant to build suggest how they'd do it and we'll see if a canonical solution emerges? I'm sure I can invent something myself entirely from whole cloth, but this seems like a re-usable building block, so I'd rather not.
I don't know if there are any Ant task for git (I googled a bit without success), anyway Ant can update a properties file with Piotr's option (`git rev-parse HEAD`) and then in runtime use that properties to get the revision number. This is cleaner and *IDE friendly* than having Ant generating a .java file.
You can get the last commit SHA with ``` git rev-parse HEAD ``` but it's generally a lot more useful to use ``` git describe ``` which will give you something that looks like this: ``` v0.7.0-185-g83e38c7 ``` This works if you have tags - it will tell you how many commits from the last valid tag your current checkout is at plus a partial SHA for that commit, so you can use it to base a checkout off of later. You can use this identifier just like a SHA in most circumstances, but it's much more human readable.
Injecting current git commit id into Java webapp
[ "", "java", "git", "ant", "" ]
This method works as expected - it creates a JTree with a root node and two child *container* nodes (each with a respective leaf node): ``` private JComponent createSideBar() { final DefaultMutableTreeNode top = new DefaultMutableTreeNode("Projects"); final JTree tree = new JTree(top); DefaultMutableTreeNode project = new DefaultMutableTreeNode("project 1"); DefaultMutableTreeNode version = new DefaultMutableTreeNode("version 1"); project.add(version); top.add(project); TreePath treePath = new TreePath(project.getPath()); // tree.expandPath(treePath); project = new DefaultMutableTreeNode("project 2"); version = new DefaultMutableTreeNode("version 2"); project.add(version); top.add(project); return tree; } ``` In this case, the tree starts out closed. I'd like the application to start with all nodes fully expanded so I started by adding the following: ``` tree.expandPath(treePath); ``` but when I un-comment it from the code above, the second set of child nodes don't show up, ie: Project 2 and Version 2 do not show up. In fact, all subsequently added nodes never show up. For what its worth, I'm using JDK 1.5. From the docs, I can't seem to see any restrictions or why this method would have such ill-effects ... I'm going to try to look at the source but was hoping someone might have a good idea what and why this is expected behavior. I'm wondering if each subsequent node 'add' is somehow disallowed somehow - but I can't imagine would work for most run-time use cases. Thanks, -Luther
Unfortunately, Swing is often "helpful". In this case, it is creating a model for you from the data supplied, much the same as a `JList` would create a model if you supplied a `Vector`. `JTree` and accomplices (primarily the Pluggable Look & Feel) will add listeners to the model to keep informed of updates. If you just change the data behind the (implicit) model's back, nothing will get updated other than by chance. So, what you should do is explicitly create a model. When the model data changes (always on the EDT, of course), cause the relevant event to be fired.
If nodes are added to a node which has already been expanded, you need to [reload the model](http://java.sun.com/javase/6/docs/api/javax/swing/tree/DefaultTreeModel.html#reload()). ``` ((DefaultTreeModel)tree.getModel()).reload(); ``` or ``` ((DefaultTreeModel)tree.getModel()).reload(top); ``` This [second version](http://java.sun.com/javase/6/docs/api/javax/swing/tree/DefaultTreeModel.html#reload(javax.swing.tree.TreeNode)) is more useful if you want to reload only a small part of a large tree.
Java Swing JTree Expansion
[ "", "java", "swing", "" ]
Imagine that during a ``` foreach(var item in enumerable) ``` The enumerable items change. It will affect the current foreach? Example: ``` var enumerable = new List<int>(); enumerable.Add(1); Parallel.ForEach<int>(enumerable, item => { enumerable.Add(item + 1); }); ``` It will loop forever?
Generally, it should throw an exception. The `List<T>` implementation of GetEnumerator() Provides an `Enumerator<T>` object whose `MoveNext()` method looks like this (from Reflector): ``` public bool MoveNext() { List<T> list = this.list; if ((this.version == list._version) && (this.index < list._size)) { this.current = list._items[this.index]; this.index++; return true; } return this.MoveNextRare(); } private bool MoveNextRare() { if (this.version != this.list._version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } this.index = this.list._size + 1; this.current = default(T); return false; } ``` The `list._version` is modified (incremented) on each operation which modifies the List.
Depends on the nature of the enumerator. Many of them throw exception when the collection changes. For instance, `List<T>` throws an `InvalidOperationException` if the collection changes during enumeration.
When items change while being enumerated does it affects the enumeration?
[ "", "c#", ".net", "concurrency", "ienumerable", "enumeration", "" ]
I'm getting reports from my website of weird Javascript errors in a piece of code that normally works well, all with the following user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; GTB6; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.30618) Should I assumed that the IE7 in Windows Media Center is a full-blown IE and really investigate this? (in case it may also happen for other users of IE 7) Or can I assume this is some kind of Windows Media Center quirk and brush it off? (yes, I am willing to lose this percentage of users in exchange for not having to actually get a Media Center just to test IE7 in it) Thanks!
My user agent on IE8 on Windows Vista SP2 64-bit: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; Zune 3.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729) The Media Center PC 5.0 just means that Media Center is installed on the system (its Windows Vista Home Premium or Windows Vista Ultimate pretty much). Here's the break down of the user agent you provided: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; GTB6; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.30618) Mozilla/4.0 -- Netscape 4.0 compatible - Compatible with whatever we just claimed to be, but not actually MSIE 7.0 - Internet Explorer 7.0 Windows NT 6.0 - Windows Vista WOW64 - 32-bit IE on a 64-bit Windows Trident/4.0 - I'm really Internet Explorer 8 trying to be Internet Explorer 7 --> this might be the source of your problems GTB6 - Google Toolbar 6 is installed SLCC1 - Secure Licensing Commerce Client is available (for Windows Anytime Upgrade detection) .NET CLR 2.0.50727 - .NET Framework 2 is installed Media Center PC 5.0 - Windows Media Center 5 (the version in Windows Vista) is installed .NET CLR 3.0.30618 - .NET Framework 3 is installed
Im not sure it's an actual Media Center PC. It seem like some version of IE7. EDIT: The WOW64 is the 32 compatability layer on a 64bit system - that might ring a bell. Anyway I found it at: <http://www.zytrax.com/tech/web/msie-history.html>, maybe that helps a little.
Is the IE 7 in Windows Media Center a full featured IE?
[ "", "javascript", "internet-explorer-7", "mediacenter", "" ]
How i can make some improvement in my IRC client made in Python. The improvement is: How i can put something that the user can type the *HOST, PORT, NICK, INDENT and REALNAME* strings and the message? And here is the code of the program: > simplebot.py > > ``` > import sys > import socket > import string > > HOST="irc.freenode.net" > PORT=6667 > NICK="MauBot" > IDENT="maubot" > REALNAME="MauritsBot" > readbuffer="" > > s=socket.socket( ) > s.connect((HOST, PORT)) > s.send("NICK %s\r\n" % NICK) > s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) > > while 1: > readbuffer=readbuffer+s.recv(1024) > temp=string.split(readbuffer, "\n") > readbuffer=temp.pop( ) > > for line in temp: > line=string.rstrip(line) > line=string.split(line) > > if(line[0]=="PING"): > s.send("PONG %s\r\n" % line[1]) > ``` Remember that i'm starting in Python development. Here is where i have found this code: <http://oreilly.com/pub/h/1968>.Thanks.
So you want the user to control the exact connection information that the IRC client uses? In order to do this, you must collect input from the user before you start your connection using the [raw\_input](http://docs.python.org/library/functions.html#raw_input) function. NOTE: raw\_input will strip a trailing newline character. ``` HOST = raw_input('Enter Host: ') PORT = int(raw_input('Enter Port: ')) ``` ...for all of the values that you want the user to be able to configure. Example: ``` HOST = raw_input('Enter host: ') print HOST >>> Enter host: stackoverflow.com stackoverflow.com >>> ```
You already have the blueprint there for what you want it to do. You're doing: ``` if(line[0]=="PING"): ``` No reason you couldn't adapt that scheme to accept input of `PORT`, `NICK`, etc. Also, while 1 isn't very Pythonic. Yes it works, but really there is no reason not to use `True`. It's not a big deal, but it makes the code slightly more readable.
Improve a IRC Client in Python
[ "", "python", "sockets", "client", "python-3.x", "irc", "" ]
Is there a flag or other reliable method to detect if a compiled C++ binary was compiled with optimizations? I'm okay with compiler-specific solutions. --- **Edit:** This is for a build deployment system, which could accidentally deploy binaries that were not built properly. A water-tight solution is unlikely, but it will save some pain (and money) if this can be detected some of the time. The compiler will often be gcc, sometimes sun, and if there's a MSVC solution, I don't want to rule that out for the benefit of the community.
Recent versions of GCC have a [way to report which flags were used to compile a binary](http://gcc.gnu.org/gcc-4.3/changes.html#mpfropts) (third bullet point). There is a related command line switch (--fverbose-asm) that "only records the information in the assembler output file as comments, so the information never reaches the object file." The --frecord-gcc-switches switch "causes the command line that was used to invoke the compiler to be recorded into the object file that is being created."
## Possible Heuristics Solution If I would be given this task and it would prove it is a reasonable task (see below), I would perform "a frequency analysis" of the patterns seen in the executable disassembly. As a programmer I am able to distinguish between an optimized and an unoptimized (debug) code at a first glance. I would try to formalize the decision process, with Visual Studio and the x86 platform the typical features seen in an unoptimized exe would be: * functions with full prologue/epilogue (ebp based stack frames) * a lot of mov-s from/into memory (all variables placed in the memory) This is definitely not 100 %, but with longer exe I would expect the results to be quite reliable. I assume for other x86 platforms including GCC the rules will be similar, if not the same, and for other platforms similar rules can be found. Other heuristics like detection of the runtime library may work as well, depending on compiler settings. ## Task sounds silly That said, I think such task "smells" and under most circumstances it would be sensible to avoid it completely. If you will provide the real reason behind such task, it is very likely some sensible solution will be found.
Detect if C++ binary is optimized
[ "", "c++", "optimization", "" ]
I am working with OpenCV and I would like to put the entire library inside it's own namespace. I've looked around quite a bit but haven't found an answer... Can you do this without modifying the library source code? If then how?
Basically no. You could attempt to do it by writing wrappers and macros, but it would be unlikely to work. If you really need to do this, a better approach is to fork the library and make the needed namespace additions. Of course, you would REALLY need to do it to take this approach, and I suspect you don't.
You could in principle write a program that would parse the library's symbol export tables, and alter the names of symbols there. You'd still need to change the headers of course. That said it would be much easier to write a simple script to add namespace tags and recompile the library.
Can you put a library inside a namespace?
[ "", "c++", "opencv", "namespaces", "" ]
I'm having a bit of trouble with the mktime function. On my production server, if I execute the following: ``` echo '<p>' . mktime(24, 0,0, 8,29,2009) . ' - 12pm</p>'; echo '<p>' . mktime(23, 0,0, 8,29,2009) . ' - 11pm</p>'; echo '<p>' . mktime(22, 0,0, 8,29,2009) . ' - 10pm</p>'; ``` And then convert those timestamps back to readable format (using [www.unixtimestamp.com](http://www.unixtimestamp.com) for quick conversion), the times are all off by one hour. I originally thought this was a problem with 2400 VS 0000, but that wouldn't account for the other dates being off. Any ideas?
Your server has a different time zone than you are expecting. Unix timestamps are measured in seconds since 1.1.1970 00:00:00 **GMT**, so you have a hidden time zone conversion in your code. You can either * use [`gmmktime()`](http://de.php.net/manual/en/function.gmmktime.php) to create a timestamp for a GMT date, * use the builtin [DateTime class](http://de.php.net/manual/en/datetime.construct.php), * correct the [timezone settings in php.ini](http://de.php.net/manual/en/datetime.configuration.php#ini.date.timezone), or * set the time zone to use with the function [`date_default_timezone_set()`](http://de.php.net/manual/en/function.date-default-timezone-set.php).
I just ran the following from the command line and got the following (expected) output. What happens if you run them? ``` $ php -r "echo date('H:i:s Y-m-d', mktime(24, 0, 0, 8, 29, 2009));" 00:00:00 2009-08-30 $ php -r "echo date('H:i:s Y-m-d', mktime(23, 0, 0, 8, 29, 2009));" 23:00:00 2009-08-29 $ php -r "echo date('H:i:s Y-m-d', mktime(22, 0, 0, 8, 29, 2009));" 22:00:00 2009-08-29 ```
MKTime Function Returning Wrong Time?
[ "", "php", "datetime", "mktime", "" ]
Does C++ have any type of utility to return to the beginning of a function after a function call? For example, example the call to help() in the calculate function. ``` void help() { cout << "Welcome to this annoying calculator program.\n"; cout << "You can add(+), subtract(-), multiply(*), divide(/),\n"; cout << "find the remainder(%), square root(sqrt()), use exponents(pow(x,x)),\n"; cout << "use parentheses, assign variables (ex: let x = 3), and assign\n"; cout << " constants (ex: const pi = 3.14). Happy Calculating!\n"; return; } void clean_up_mess() // purge error tokens { ts.ignore(print); } const string prompt = "> "; const string result = "= "; void calculate() { while(true) try { cout << prompt; Token t = ts.get(); if (t.kind == help_user) help(); else if (t.kind == quit) return; while (t.kind == print) t=ts.get(); ts.unget(t); cout << result << statement() << endl; } catch(runtime_error& e) { cerr << e.what() << endl; clean_up_mess(); } } ``` While technically my implementation of a help function works fine, it's not perfect. After help is called, and returns, it proceeds with trying to cout << result << statement() << endl; which isn't possible because no values have been entered. Thus it gives a little error message (elsewhere in the program) and then proceeds on with the program. No problem with functionality, but it's ugly and I don't like it (:P). So is there any way for when the help function returns, to return to the beginning of calculate and start over? (I played around with inserting a function call in if(t.kind == help\_user) block to call calculate, but as I figured that just delays the problem rather than solving it.)
You can use goto, but the moment you do that consider yourself over. It's considered bad practice and good uses of it are rare and far apart. I think what you're looking for is continue: ``` void do_calculate(void) { while (true) { cout << prompt; Token t = ts.get(); if (t.kind == help_user) { help(); continue; // <- here } else if (t.kind == quit) { return; } while (t.kind == print) { t = ts.get(); } ts.unget(t); cout << result << statement() << endl; } } void calculate() { try { do_calculate(); } catch (const std::exception& e) { cerr << e.what() << endl; clean_up_mess(); } } ``` I have also reformatted your code. I think this is more readable, to each his own but just wanted to let you compare. * The try/catch clause is now no longer interfering with the calculation function. * The 'if' statements use brackets for consistency. Also, it's much easier to read, because I *know* whatever the if is controlling is within these brackets. * The catch will catch a std::exception, rather than runtime\_error. All standard exceptions inherit from std::exception, so by catching that you know you can catch anything.
This might be what you're looking for? ``` if (t.kind == help_user) { help(); continue; } ```
Method to return to beginning of function
[ "", "c++", "" ]
Is there any way to hide or encrypt JavaScript code to prevent people from viewing, copying, and/or modifying proprietary programs?
You can obfuscate it, but there's no way of protecting it completely. example obfuscator: <https://obfuscator.io>
No, it's not possible. If it runs on the client browser, it must be downloaded by the client browser. It's pretty trivial to use Fiddler to inspect the HTTP session and get any downloaded js files. There are tricks you can use. One of the most obvious is to employ a javascript obfuscator. Then again, obfuscation only prevents casual snooping, and doesnt prevent people from lifting and using your code. You can try compiled action script in the form of a flash movie.
How can I hide or encrypt JavaScript code?
[ "", "javascript", "encryption", "obfuscation", "" ]
An ordinary object, I can use ``` o.__repr__() ``` to see something like ``` '<__main__.A object at 0x9d78fec>' ``` But, say, a Django User just returns ``` <User:bob> ``` How can I see the actual address of one of these, or compare whether two such model-objects are actually the same object or not?
`id()` will return the identity of the object (generally implemented as the address), which is guaranteed unique for two objects which exist at the same point in time. However the obvious way to check whether two objects are identical is to use the operator explicitely designed for this: `is` ie. ``` if obj1 is obj2: # Objects are identical. ```
You can get the id of any object: ``` a = object() print hex(id(a)) ``` Although for CPython, this is the address of the object, this is not guaranteed I believe (and may be different on other implementations like iron python). Same id means same object, though.
How do I find the memory address of a Python / Django model object?
[ "", "python", "django", "django-models", "" ]
Hopefully no one has asked this question - didn't see it, but I apologize if it's a duplicate. Anyway, I'm building some plug-ins with Eclipse RCP and am using SWT for my UI. I have a Composite that contains some panels and other items - anyway, I've noticed a bit of a difference in the appearance of the UI depending on how my OS is set up. I'm running windows XP but am using the "classic" look/feel which is that of Windows 98. When it's like this - the UI looks fine; however, when I switch to the newer XP look/feel with that tacky blue bar and what not - labels and borders in my composite are different. Is there a way I can force SWT to use the classic look/feel?
You need a javaw.exe.manifest bound to your application. Here is an article that describes the problem: <http://www.javalobby.org/forums/thread.jspa?threadID=15414&tstart=0>
I think it is a design decision of SWT to make it inherit the platform look and feel. I imagine this is partly to address the usual "java apps look rubbish/out of place/different" comments and partly to make it easier to load the relevant fragments at startup. I don't know of any way to override the standard values.
Force Look/Feel in SWT
[ "", "java", "eclipse", "user-interface", "swt", "eclipse-rcp", "" ]
I have the following code: ``` template <int size> inline uint hashfn( const char* pStr ) { uint result = *pStr; switch ( size ) { case 10: result *= 4; result += *pStr; case 9: result *= 4; result += *pStr; ... ... case 2: result *= 4; result += *pStr; } return result; } ``` This code is a hash function for DNA sequences of certain lenghts where the length is a template parameter. It is an unrolled loop with a switch statement to jump in at the right spot. The size is however a constant since it is a template parameter. Could I specialize this for certain size values? Maybe with something like: ``` template <int 2> inline uint hashfn( const char* pStr ) { uint result = *pStr; result *= 4; ++pStr; result += *pStr; return result; } ```
I would tend to do it recursively with templates. E.g. : ``` template<class TOp,int factor> struct recursive_unroll { __forceinline static void result( TOp& k ) { k(); recursive_unroll<TOp,factor-1>::result( k ); } }; template<class TOp> struct recursive_unroll<TOp,0> { __forceinline static void result( TOp& k ) {} }; struct op { op( const char* s ) : res( 0 ), pStr( s ) {} unsigned int res; const char* pStr; __forceinline void operator()() { res *= 4; res += *pStr; ++pStr; //std::cout << res << std::endl; } }; char str[] = "dasjlfkhaskjfdhkljhsdaru899weiu"; int _tmain(int argc, _TCHAR* argv[]) { op tmp( str ); recursive_unroll<op,sizeof( str ) >::result( tmp ); std::cout << tmp.res << std::endl; return 0; } ``` This produces optimal code for me. Without **\_\_forceinline** the code is not properly inlined. You should always bench your code before using such optimizations. And then you should look at the assembly and decipher what your compiler already does for you. But in this case, it seems to be an boost (for me). --- **\_\_forceinline** is a Microsoft Visual Studio specific extension. The compiler should generate optimal code, but for this it doesn't. So here I used this extension.
Please read up about loop unrolling on wikipedia. The whole point is to save comparisons on the loop variable. Did you profile the code? I do not see how this can save you cycles compared to a loop. Any modern compiler should completely unroll a loop with a small static loop count for you. I also hope you don't use the hashes for modulo-based hash tables, as you will lose the upper bits of your hash.
Can one unroll a loop when working with an integer template parameter?
[ "", "c++", "templates", "metaprogramming", "" ]
So I am a little confused, I have been looking around trying to determine an appropriate way of inheriting from std::exception for my own type. Now according to cplusplus.com (and i know this isn't necessarily the standard, thats why I'm asking), std::exception is a base class with no members. However, after looking at my implementation of the standard library (VS 2005), the class std::exception is quite clearly defined with two member variables: ``` class _CRTIMP_PURE exception { // base of all library exceptions ... private: const char *_m_what; int _m_doFree; }; ``` Now is this standard to have these members included within the base class std::exception, my understanding was that it isn't. My reason for asking is that my derived exception class really only needs a single string for its information, thus this implementation would work fine. However, I'm worried that this is non-standard, and as such I might be better off inheriting from std::exception and adding the appropriate members + copy/assignment code myself.
The `std::exception` class is defined as: ``` namespace std { class exception { public: exception() throw(); exception(const exception&) throw(); exception& operator=(const exception&) throw(); virtual ~exception() throw(); virtual const char* what() const throw(); }; } ``` That is the contract that you have to live up to when it comes to substitutability. The Standard defines the specifics of each member. The only one that usually requires consideration is that `what()` returns a *"null-terminated multi-byte string, suitable for display as a `wstring`"*. The other part is obeying and ensuring the `throw()` contract.
To make your own exception class, you want to overload the following function: ``` virtual const char* what() const throw() ``` If you look at the Visual Studio implementation, `exception` uses `malloc` to allocate memory to store the character string. If that memory isn't available, `_m_what` is set to a predefined string. `_m_doFree` is a flag that stores whether `free` needs to be called on this memory.
Inheriting from std::exception, ambiguity in definitions of std::exception
[ "", "c++", "exception", "" ]
Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class. Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python. What's the best recommended way of pursuing this issue? EDIT: Here is roughly what I mean... ``` class A(models.Model): field = models.TextField() class B(A): other = <class specific functionality> class C(A): other2 = <different functionality> class D(A): #I would like class D to have a foreign key to either B or C, but not both. ``` Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.
From the [Django Docs](http://docs.djangoproject.com/en/dev/topics/db/models/#one-to-one-relationships): > For example, if you were building a > database of "places", you would build > pretty standard stuff such as address, > phone number, etc. in the database. > Then, if you wanted to build a > database of restaurants on top of the > places, instead of repeating yourself > and replicating those fields in the > Restaurant model, you could make > Restaurant have a OneToOneField to > Place (because a restaurant "is a" > place; in fact, to handle this you'd > typically use inheritance, which > involves an implicit one-to-one > relation). Normally, you would just have `Restaurant` inherit from `Place`. Sadly, you need what I consider a hack: making a one-to-one reference from subclass to superclass (`Restaurant` to `Place`)
One way to do this is to add an intermediate class as follows: ``` class A(Model): class Meta(Model.Meta): abstract = True # common definitions here class Target(A): # this is the target for links from D - you then need to access the # subclass through ".b" or ".c" # (no fields here) class B(Target): # additional fields here class C(Target): # additional fields here class D(A): b_or_c = ForeignKey(Target) def resolve_target(self): # this does the work for you in testing for whether it is linked # to a b or c instance try: return self.b_or_c.b except B.DoesNotExist: return self.b_or_c.c ``` Using an intermediate class (Target) guarantees that there will only be one link from D to either B or C. Does that make sense? See [model inheritance](https://docs.djangoproject.com/en/3.0/topics/db/models/#model-inheritance) for more information. In your database there will be tables for Target, B, C and D, but not A, because that was marked as abstract (instead, columns related to attributes on A will be present in Target and D). [Warning: I have not actually tried this code - any corrections welcome!]
Django Model Inheritance And Foreign Keys
[ "", "python", "django", "inheritance", "django-models", "foreign-keys", "" ]
This question relates to those parts of the KenKen Latin Square puzzles which ask you to find all possible combinations of ncells numbers with values x such that 1 <= x <= maxval and x(1) + ... + x(ncells) = targetsum. Having tested several of the more promising answers, I'm going to award the answer-prize to Lennart Regebro, because: 1. his routine is as fast as mine (+-5%), and 2. he pointed out that my original routine had a bug somewhere, which led me to see what it was really trying to do. Thanks, Lennart. chrispy contributed an algorithm that seems equivalent to Lennart's, but 5 hrs later, sooo, first to the wire gets it. A remark: Alex Martelli's bare-bones recursive algorithm is an example of making every possible combination and throwing them all at a sieve and seeing which go through the holes. This approach takes 20+ times longer than Lennart's or mine. (Jack up the input to max\_val = 100, n\_cells = 5, target\_sum = 250 and on my box it's 18 secs vs. 8+ mins.) Moral: Not generating every possible combination is good. Another remark: Lennart's and my routines generate **the same answers in the same order**. Are they in fact the same algorithm seen from different angles? I don't know. Something occurs to me. If you sort the answers, starting, say, with (8,8,2,1,1) and ending with (4,4,4,4,4) (what you get with max\_val=8, n\_cells=5, target\_sum=20), the series forms kind of a "slowest descent", with the first ones being "hot" and the last one being "cold" and the greatest possible number of stages in between. Is this related to "informational entropy"? What's the proper metric for looking at it? Is there an algorithm that producs the combinations in descending (or ascending) order of heat? (This one doesn't, as far as I can see, although it's close over short stretches, looking at normalized std. dev.) Here's the Python routine: ``` #!/usr/bin/env python #filename: makeAddCombos.07.py -- stripped for StackOverflow def initialize_combo( max_val, n_cells, target_sum): """returns combo Starting from left, fills combo to max_val or an intermediate value from 1 up. E.g.: Given max_val = 5, n_cells=4, target_sum = 11, creates [5,4,1,1]. """ combo = [] #Put 1 in each cell. combo += [1] * n_cells need = target_sum - sum(combo) #Fill as many cells as possible to max_val. n_full_cells = need //(max_val - 1) top_up = max_val - 1 for i in range( n_full_cells): combo[i] += top_up need = target_sum - sum(combo) # Then add the rest to next item. if need > 0: combo[n_full_cells] += need return combo #def initialize_combo() def scrunch_left( combo): """returns (new_combo,done) done Boolean; if True, ignore new_combo, all done; if Falso, new_combo is valid. Starts a new combo list. Scanning from right to left, looks for first element at least 2 greater than right-end element. If one is found, decrements it, then scrunches all available counts on its right up against its right-hand side. Returns the modified combo. If none found, (that is, either no step or single step of 1), process done. """ new_combo = [] right_end = combo[-1] length = len(combo) c_range = range(length-1, -1, -1) found_step_gt_1 = False for index in c_range: value = combo[index] if (value - right_end) > 1: found_step_gt_1 = True break if not found_step_gt_1: return ( new_combo,True) if index > 0: new_combo += combo[:index] ceil = combo[index] - 1 new_combo += [ceil] new_combo += [1] * ((length - 1) - index) need = sum(combo[index:]) - sum(new_combo[index:]) fill_height = ceil - 1 ndivf = need // fill_height nmodf = need % fill_height if ndivf > 0: for j in range(index + 1, index + ndivf + 1): new_combo[j] += fill_height if nmodf > 0: new_combo[index + ndivf + 1] += nmodf return (new_combo, False) #def scrunch_left() def make_combos_n_cells_ge_two( combos, max_val, n_cells, target_sum): """ Build combos, list of tuples of 2 or more addends. """ combo = initialize_combo( max_val, n_cells, target_sum) combos.append( tuple( combo)) while True: (combo, done) = scrunch_left( combo) if done: break else: combos.append( tuple( combo)) return combos #def make_combos_n_cells_ge_two() if __name__ == '__main__': combos = [] max_val = 8 n_cells = 5 target_sum = 20 if n_cells == 1: combos.append( (target_sum,)) else: combos = make_combos_n_cells_ge_two( combos, max_val, n_cells, target_sum) import pprint pprint.pprint( combos) ```
First of all, I'd use variable names that mean something, so that the code gets comprehensible. Then, after I understood the problem, it's clearly a recursive problem, as once you have chosen one number, the question of finding the possible values for the rest of the squares are exactly the same problem, but with different values in. So I would do it like this: ``` from __future__ import division from math import ceil def make_combos(max_val,target_sum,n_cells): combos = [] # The highest possible value of the next cell is whatever is # largest of the max_val, or the target_sum minus the number # of remaining cells (as you can't enter 0). highest = min(max_val, target_sum - n_cells + 1) # The lowest is the lowest number you can have that will add upp to # target_sum if you multiply it with n_cells. lowest = int(ceil(target_sum/n_cells)) for x in range(highest, lowest-1, -1): if n_cells == 1: # This is the last cell, no more recursion. combos.append((x,)) break # Recurse to get the next cell: # Set the max to x (or we'll get duplicates like # (6,3,2,1) and (6,2,3,1), which is pointless. # Reduce the target_sum with x to keep the sum correct. # Reduce the number of cells with 1. for combo in make_combos(x, target_sum-x, n_cells-1): combos.append((x,)+combo) return combos if __name__ == '__main__': import pprint # And by using pprint the output gets easier to read pprint.pprint(make_combos( 6,12,4)) ``` I also notice that your solution still seems buggy. For the values `max_val=8, target_sum=20 and n_cells=5` your code doesn't find the solution `(8,6,4,1,1,)`, as an example. I'm not sure if that means I've missed a rule in this or not, but as I understand the rules that should be a valid option. Here's a version using generators, It saves a couple of lines, and memory if the values are really big, but as recursion, generators can be tricky to "get". ``` from __future__ import division from math import ceil def make_combos(max_val,target_sum,n_cells): highest = min(max_val, target_sum - n_cells + 1) lowest = int(ceil(target_sum/n_cells)) for x in xrange(highest, lowest-1, -1): if n_cells == 1: yield (x,) break for combo in make_combos(x, target_sum-x, n_cells-1): yield (x,)+combo if __name__ == '__main__': import pprint pprint.pprint(list(make_combos( 6,12,4))) ```
Your algorithm seems pretty good at first blush, and I don't think OO or another language would improve the code. I can't say if recursion would have helped but I admire the non-recursive approach. I bet it was harder to get working and it's harder to read but it likely is more efficient and it's definitely quite clever. To be honest I didn't analyze the algorithm in detail but it certainly looks like something that took a long while to get working correctly. I bet there were lots of off-by-1 errors and weird edge cases you had to think through, eh? Given all that, basically all I tried to do was pretty up your code as best I could by replacing the numerous C-isms with more idiomatic Python-isms. Often times what requires a loop in C can be done in one line in Python. Also I tried to rename things to follow Python naming conventions better and cleaned up the comments a bit. Hope I don't offend you with any of my changes. You can take what you want and leave the rest. :-) Here are the notes I took as I worked: * Changed the code that initializes `tmp` to a bunch of 1's to the more idiomatic `tmp = [1] * n_cells`. * Changed `for` loop that sums up `tmp_sum` to idiomatic `sum(tmp)`. * Then replaced all the loops with a `tmp = <list> + <list>` one-liner. * Moved `raise doneException` to `init_tmp_new_ceiling` and got rid of the `succeeded` flag. * The check in `init_tmp_new_ceiling` actually seems unnecessary. Removing it, the only `raise`s left were in `make_combos_n_cells`, so I just changed those to regular returns and dropped `doneException` entirely. * Normalized mix of 4 spaces and 8 spaces for indentation. * Removed unnecessary parentheses around your `if` conditions. * `tmp[p2] - tmp[p1] == 0` is the same thing as `tmp[p2] == tmp[p1]`. * Changed `while True: if new_ceiling_flag: break` to `while not new_ceiling_flag`. * You don't need to initialize variables to 0 at the top of your functions. * Removed `combos` list and changed function to `yield` its tuples as they are generated. * Renamed `tmp` to `combo`. * Renamed `new_ceiling_flag` to `ceiling_changed`. And here's the code for your perusal: ``` def initial_combo(ceiling=5, target_sum=13, num_cells=4): """ Returns a list of possible addends, probably to be modified further. Starts a new combo list, then, starting from left, fills items to ceiling or intermediate between 1 and ceiling or just 1. E.g.: Given ceiling = 5, target_sum = 13, num_cells = 4: creates [5,5,2,1]. """ num_full_cells = (target_sum - num_cells) // (ceiling - 1) combo = [ceiling] * num_full_cells \ + [1] * (num_cells - num_full_cells) if num_cells > num_full_cells: combo[num_full_cells] += target_sum - sum(combo) return combo def all_combos(ceiling, target_sum, num_cells): # p0 points at the rightmost item and moves left under some conditions # p1 starts out at rightmost items and steps left # p2 starts out immediately to the left of p1 and steps left as p1 does # So, combo[p2] and combo[p1] always point at a pair of adjacent items. # d combo[p2] - combo[p1]; immediate difference # cd combo[p2] - combo[p0]; cumulative difference # The ceiling decreases by 1 each iteration. while True: combo = initial_combo(ceiling, target_sum, num_cells) yield tuple(combo) ceiling_changed = False # Generate all of the remaining combos with this ceiling. while not ceiling_changed: p2, p1, p0 = -2, -1, -1 while combo[p2] == combo[p1] and abs(p2) <= num_cells: # 3,3,3,3 if abs(p2) == num_cells: return p2 -= 1 p1 -= 1 p0 -= 1 cd = 0 # slide_ptrs_left loop while abs(p2) <= num_cells: d = combo[p2] - combo[p1] cd += d # 5,5,3,3 or 5,5,4,3 if cd > 1: if abs(p2) < num_cells: # 5,5,3,3 --> 5,4,4,3 if d > 1: combo[p2] -= 1 combo[p1] += 1 # d == 1; 5,5,4,3 --> 5,4,4,4 else: combo[p2] -= 1 combo[p0] += 1 yield tuple(combo) # abs(p2) == num_cells; 5,4,4,3 else: ceiling -= 1 ceiling_changed = True # Resume at make_combo_same_ceiling while # and follow branch. break # 4,3,3,3 or 4,4,3,3 elif cd == 1: if abs(p2) == num_cells: return p1 -= 1 p2 -= 1 if __name__ == '__main__': print list(all_combos(ceiling=6, target_sum=12, num_cells=4)) ```
KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm
[ "", "python", "algorithm", "statistics", "puzzle", "combinations", "" ]
Thats it really.. I am using VS2008 Express. All the samples say just to set the PasswordChar, but nothing gets masked. I also tried setting the "UseSystemPasswordChar" = true.. no luck.. ``` // Set to no text. textBox1.Text = ""; // The password character is an asterisk. textBox1.PasswordChar = '*'; // The control will allow no more than 14 characters. textBox1.MaxLength = 14; ``` The reason I'm using a TextBox is because I want the user to be able to hit return and it submits the data. Its important to note I guess that I have MultiLine = true so that I can capture the return. I can't seem to be able to capture a return with a maskedTextBox. All I get is a system beep. a solution to either is fine for me!
If you read [the documentation](http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.passwordchar(VS.80).aspx) is says "If the Multiline property is set to true, setting the PasswordChar property has no visual effect."
UseSystemPasswordChar doesn't function when Multiline is set to true. The standard Windows Forms textbox accepts returns even when Multiline = false. Solution: Set Multiline = False, and set a button on your form to use the AcceptButton property, or capture the return/enter key in the "KeyPress" event of the textbox.
Password Character not working on System.Windows.Forms.TextBox
[ "", "c#", "winforms", "textbox", "passwords", "maskedtextbox", "" ]
I'm building a toplist for my site and instead of recording in and out hits and emptying the database every 24 hours I would like to record in and out hits "within the last 24 hours", this way the toplist will always look busy no matter what time you look at it, while still acurately ranking sites. So basically I'll have to add a record to the database logging an 'in' hit (for example) and the remove it around 24 hours later, or simply not consider it when ranking the sites. I want to know the most efficient way of doing this, I have some ideas but they all seem really resource heavy. I hope you understand what I'm trying to achieve :) Any help would be appreciated.
You don't necessarily have to delete "old" data all the time. You can also limit the data set to records within the last 24 hours when querying data. ``` WHERE site='xyz' AND hit_datetime > Now()-Interval 24 hour ``` see <http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html>
I would delete the data that is older than 24 hours with a simple ``` DELETE...WHERE hit_time < now() - interval 24 hour ``` The other question is - when to call it? The tradeoff is between performance and stale data. The more often you call it, the less "stale" data there will be, but the server load will grow. I see several approaches, pick one that suits your needs most: * Call it at the start of every script. This can be optmized by calling it only if the script will do something with the hit data. That way every script will always run with "correct" data. However this will have the maximum load. * Schedule a cron job and call it once every 1h/2h/24h/etc. This way there will be a little bit of "stale" data, but the overhead will be reduced to a minimum. * Do it like PHP does it with sessions - on every script startup give it a x% (x is configurable) chance of being run. That is, take a value from 0 to 100, and if it is smaller than x, execute the DELETE. You can also invent some other schemes - for example, run it once per user session; or run it only if the execution time is evenly divisable by, say, 7; or something else. Either way you trade off performance for correctness.
PHP MySql Storing Data for 24 hours
[ "", "php", "mysql", "" ]
I'm storing localized strings in a single datatable using MS Sql (2008 or whatever). Most of the strings are short and can be represented with varchar(200), while about 10% are much longer require something like varchar(5000). My question is, is there a performance advantage when retrieving shorter strings if I break this into two tables like this: ``` CREATE TABLE ShortTextTable(ID bigint IDENTITY(1,1) NOT NULL, TextValue nvarchar(200)) CREATE TABLE LongTextTable(ID bigint IDENTITY(1,1) NOT NULL, TextValue nvarchar(4000)) ``` Versus: ``` CREATE TABLE TextTable(ID bigint IDENTITY(1,1) NOT NULL, TextValue nvarchar(4000)) ``` This data will rarely be updated, I'm only really concerned about reads.
It depends. Could be premature optimization. With smaller columns, you will fit more rows per page, obviously, but your usage patterns may mean that the horizontal partition you are proposing is not very efficient, since it's getting things from both new tables. I think we need to see the read usage pattern and how the table is joined to. Also, it is partitioning a space that is logically one space, and will no longer be manageable as one space (i.e. add an index in both places, etc.) You'd really have to see a bottle neck and profile the proposed change before I would partition it like this. I'm not sure, but it might be possible to **literally** partition (using SQL Server's partitioned tables feature) the table based on length of the column. Again, whether this would help would need to be profiled.
No, no real gain. To see bottlenecks because of the string size interleaves, specially base don an int PK, it would be a real extreme. On the other hand the mess of working with such a storage schema is very clear and present: you have to decide, based on the length of a string *you did not yet retrieve* on which table to look! You'll probably end up looking by trial and error (try one table, then the other), which is by far more wasteful than that any table nvarchar storage structure issue.
SQL nvarchar Performance
[ "", "sql", "sql-server", "performance", "sql-server-2008", "nvarchar", "" ]
Well, I think I have a very basic doubt here: I'm developing an app on GAE (Java) and performing a query to the datastore that returns a lot of entities, so I need to cache it. I was using memcache and it was working great, but if I keep the list of entities in a static variable, the whole request goes as twice as fast than using memcache. I think that's because I'm not deserializing the entities all the time. What would be the drawback of using a static variable instead on memcache? I don't know if there could be several instances of my application in the cloud, and thus several instances of my static variable? The list of entities I'm trying to cache are the best (greater score) posts of the last week. I take that list and choose 5 random posts and show them in a couple of pages. Thanks for the help!
App Engine scales by creating new instances of your application as the number of users hitting it increases. As drudru said, different users might be served by different instances. In general, memcache is the fastest place to store something you want to be globally consistent. However, in your case there may be some room for improvement. You mention you have a list of posts and you randomly choose 5 to show to users. Does it matter if 2 different users see a different set of 5? If you're choosing random ones anyway, maybe it doesn't matter. Then you could store the full list of posts in memcache, and pull 5 random ones out of memcache and store them in a static variable. Second, what exactly are you memcaching, and how are you pulling it out? Are you storing a whole bunch of full posts in memcache, getting them all, then choosing 5? Maybe you could just download the list of posts, choose 5, and only get the 5 you need? If you think it's the deserializing that's slowing you down, this might help. Are you doing any processing on the posts after you get them? If so, could the results of that processing be cached?
You cannot rely on static variables (or anything else in JVM memory) to be around when the next request hits, because Google is free to start and stop virtual machines when they feel like it. From the looks of it, they seem to prefer to start additional JVMs instead of additional threads in the same JVM, which compounds this issue. But, you should be able to use static variables as a cache layer, provided you have a way to load the data from somewhere else if it went away. I would also not try to go overboard with memory usage there, there must be a quota on how much memory you can use.
Google App Engine: Memcache or Static variable?
[ "", "java", "google-app-engine", "memcached", "google-cloud-datastore", "static-variables", "" ]
I want to hide the cursor when showing a webpage that is meant to display information in a building hall. It doesn't have to be interactive at all. I tried changing the cursor property and using a transparent cursor image but it didn't solve my problem. Does anybody know if this can be done? I suppose this can be thought of as a security threat for a user that can't know what he is clicking on, so I'm not very optimistic... Thank you!
With CSS: ``` selector { cursor: none; } ``` An example: ``` <div class="nocursor"> Some stuff </div> <style type="text/css"> .nocursor { cursor:none; } </style> ``` To set this on an element in Javascript, you can use the `style` property: ``` <div id="nocursor"><!-- some stuff --></div> <script type="text/javascript"> document.getElementById('nocursor').style.cursor = 'none'; </script> ``` If you want to set this on the whole body: ``` <script type="text/javascript"> document.body.style.cursor = 'none'; </script> ``` Make sure you really want to hide the cursor, though. It can *really* annoy people.
# [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) While the `cursor: none` CSS solution is definitely a solid and easy *workaround*, if your actual goal is to *remove* the default cursor while your web application is being used, or implement your *own* interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) instead. You can use [requestPointerLock](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) on an element to remove the cursor, and redirect all `mousemove` events to that element (which you may or may not handle): ``` document.body.requestPointerLock(); ``` To release the lock, you can use [exitPointerLock](https://developer.mozilla.org/en-US/docs/Web/API/Document/exitPointerLock): ``` document.exitPointerLock(); ``` --- ## Additional notes **No cursor, for real** This is a very powerful API call. It not only renders your cursor invisible, but *it actually removes your operating system's native cursor*. You won't be able to select text, or do *anything* with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using `exitPointerLock` or pressing `ESC` in some browsers). That is, you cannot leave the window with your cursor for it to show again, as there is no cursor. **Restrictions** As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example: ``` document.addEventListener("click", function () { document.body.requestPointerLock(); }); ``` Also, `requestPointerLock` won't work from a sandboxed `iframe` unless the `allow-pointer-lock` permission is set. **User-notifications** Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the `pointerchange` event on the element on which `requestPointerLock` was called: ``` document.body.addEventListener("pointerlockchange", function () { if (document.pointerLockElement === document.body) { // Pointer is now locked to <body>. } }); ``` Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see [Disable pointer-lock notification in Firefox](https://superuser.com/questions/1209306/disable-pointer-lock-notification-in-firefox). **Listening to raw mouse movement** The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element `requestPointerLock` was called on. This can be listened to simply by using the `mousemove` event, then accessing the `movementX` and `movementY` properties on the event object: ``` document.body.addEventListener("mousemove", function (e) { console.log("Moved by " + e.movementX + ", " + e.movementY); }); ```
Is it possible to hide the cursor in a webpage using CSS or Javascript?
[ "", "javascript", "html", "css", "" ]
Using JavaScript, how do I create an HTML table that can "accept" numeric matrix data from Excel (or Google spreadsheet), via "copy" in the spreadsheet and then "paste" into the table in the browser.
This would only work reliably on IE since Firefox (and likely others) don't allow access to the clipboard without specifically allowing it; the earlier suggestion of pasting into a textarea first might work better than this. When you copy from a spreadsheet, generally the cells are separated with a tab (chr9) and the rows with a CR (chr13). This script converts the clipboard into a 2D array and then builds a table from it. Not too elegant but it seems to work copying data out of Excel. ``` <html> <head> <script language="javascript"> function clip() { // get the clipboard text var clipText = window.clipboardData.getData('Text'); // split into rows clipRows = clipText.split(String.fromCharCode(13)); // split rows into columns for (i=0; i<clipRows.length; i++) { clipRows[i] = clipRows[i].split(String.fromCharCode(9)); } // write out in a table newTable = document.createElement("table") newTable.border = 1; for (i=0; i<clipRows.length - 1; i++) { newRow = newTable.insertRow(); for (j=0; j<clipRows[i].length; j++) { newCell = newRow.insertCell(); if (clipRows[i][j].length == 0) { newCell.innerText = ' '; } else { newCell.innerText = clipRows[i][j]; } } } document.body.appendChild(newTable); } </script> </head> <body> <input type="button" onclick="clip()"> </body> </html> ```
Here is the javascript code I created (based on the helpful answers). I'm new to javascript, so I'm sure there is much better way to do this, but it seems to work... The goal is to "paste" two columns of numerical data into the text area from a spreadsheet (I've tried both excel and google spreadsheet) and create floating point vectors "xf" and "yf". Hopefully useful to someone. Criticism welcome... It assumes these exist on an html page... ``` <textarea id="psmtext" rows=24 cols=72> </textarea> <input type="button" value="run code" onClick="psmtest();"> ``` --- ``` function psmtest(){ ``` var psmtext = document.getElementById("psmtext"); var st = psmtext.value; Ast = st.split("\n"); var numrows = Ast.length; var ii; var xs = []; var ys = []; for (ii = 0 ; ii < numrows ; ii++) { // tab or comma deliminated data if ( Ast[ii].split(",",2)[1] != null ){ ys[ii] = Ast[ii].split(",")[1]; xs[ii] = Ast[ii].split(",")[0];} if ( Ast[ii].split("\t",2)[1] != null ){ ys[ii] = Ast[ii].split("\t")[1]; xs[ii] = Ast[ii].split("\t")[0];} } var xss = []; var yss = []; var numgoodrows = 0; var iii =0; for (ii = 0 ; ii < numrows ; ii++) { if ( xs[ii] != null && ys[ii] != null) { xss[iii] = xs[ii]; yss[iii] = ys[ii]; iii++; } } numgoodrows = iii; // next I need to convert to floating point array var xf = [], var yf = []; var xf = []; var yf = []; for (ii = 0 ; ii < numgoodrows ; ii++) { xf[ii] = parseFloat(xss[ii]); yf[ii] = parseFloat(yss[ii]); } }
Paste Excel data into HTML table
[ "", "javascript", "html-table", "spreadsheet", "" ]
I´m dynamically creating an instance of a class with reflection and this works fine, except when trying to do this through unit testing - I´m using the MS testing framework. I get the familiar error of: "Could not load file or assembly 'Assy' or one of its dependencies. The system cannot find the file specified" I have copied the dll into the bin\debug bin of the Unit test project - is this not the correct place to put it? ``` string assyName = "Go.Data.SqlServer"; string typeName = "GoMolaMola.Data.SqlServer.DataProviderFactory"; Assembly assy = Assembly.Load( assyName ); object o = assy.CreateInstance( typeName ); ``` Any ideas? I'm new to unit testing and any help would be appreciated. Thanks
The `bin/Debug` folder is not where the unit tests run. Visual Studio will copy the output of your unit test compilation to a `TestResults` folder (typically keeping the last five test runs, each with a timestamp embedded in the folder name) and run the unit tests there. If you want the .DLL in that folder, either create a reference to the .DLL from your test project, or use the [DeploymentItem](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.webtesting.deploymentitemattribute.aspx) attribute to make sure the item is copied to the test directory.
I faced this problem too and none of the above answer worked for me :( 1. Adding reference to project doesn't work for me 2. Adding the DeploymentItem attribute also doesn't work 3. Adding the Post-Build command is also not possible in this case as Unit test engine is creating a new out directory each time with time stamp....and its searching that assembly in this new directory. but I managed to solve this by enabling deployment and adding the specified file in Local Test Setting -->Deployment
Problem with reflection in Unit/Integration tests
[ "", "c#", "unit-testing", "reflection", "" ]
I am using **Ubuntu 9.04** I have installed the following package versions: ``` unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 python2.6-dev ``` I have configured `/etc/unixodbc.ini` like this: ``` [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /usr/lib/odbc/libtdsodbc.so Setup = /usr/lib/odbc/libtdsS.so CPTimeout = CPReuse = UsageCount = 2 ``` I have configured `/etc/freetds/freetds.conf` like this: ``` [global] tds version = 8.0 client charset = UTF-8 text size = 4294967295 ``` I have grabbed pyodbc revision `31e2fae4adbf1b2af1726e5668a3414cf46b454f` from `http://github.com/mkleehammer/pyodbc` and installed it using "`python setup.py install`" I have a windows machine with *Microsoft SQL Server 2000* installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full privileges. I am using the following python code to setup the connection: ``` import pyodbc odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS" con = pyodbc.connect(odbcstring) cur = con.cursor() cur.execute(""" IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'testing') DROP TABLE testing """) cur.execute(''' CREATE TABLE testing ( id INTEGER NOT NULL IDENTITY(1,1), myimage IMAGE NULL, PRIMARY KEY (id) ) ''') con.commit() ``` Everything **WORKS** up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there. Now I want to insert some data on the table. ``` cur = con.cursor() # using web data for exact reproduction of the error by all. # I'm actually reading a local file in my real code. url = 'http://www.forestwander.com/wp-content/original/2009_02/west-virginia-mountains.jpg' data = urllib2.urlopen(url).read() sql = "INSERT INTO testing (myimage) VALUES (?)" ``` Now here on my original question, I was having trouble using `cur.execute(sql, (data,))` but now I've edited the question, because following Vinay Sajip's answer below (THANKS), I have changed it to: ``` cur.execute(sql, (pyodbc.Binary(data),)) con.commit() ``` And insertion **is working perfectly**. I can confirm the size of the inserted data using the following test code: ``` cur.execute('SELECT DATALENGTH(myimage) FROM testing WHERE id = 1') data_inside = cur.fetchone()[0] assert data_inside == len(data) ``` Which passes **perfectly**!!! Now the problem is on retrieval of the data back. I am trying the common approach: ``` cur.execute('SELECT myimage FROM testing WHERE id = 1') result = cur.fetchone() returned_data = str(result[0]) # transforming buffer object print 'Original: %d; Returned: %d' % (len(data), len(returned_data)) assert data == returned_data ``` However that fails!! ``` Original: 4744611; Returned: 4096 Traceback (most recent call last): File "/home/nosklo/devel/teste_mssql_pyodbc_unicode.py", line 53, in <module> assert data == returned_data AssertionError ``` I've put all the code above in a single file [here](http://paste.pocoo.org/show/125955/), for easy testing of anyone that wants to help. Now for the question: I want python code to insert an image file into mssql. I want to query the image back and show it to the user. I don't care about the column type in mssql. I am using the "`IMAGE`" column type on the example, but any binary/blob type would do, as long as I get the binary data for the file I inserted back unspoiled. Vinay Sajip said below that this is the preferred data type for this in SQL SERVER 2000. The data is now being inserted without errors, however when I retrieve the data, only 4k are returned. (Data is truncated on 4096). How can I make that work? --- **EDITS**: Vinay Sajip's answer below gave me a hint to use pyodbc.Binary on the field. I have updated the question accordingly. Thanks Vinay Sajip! Alex Martelli's comment gave me the idea of using the `DATALENGTH` MS SQL function to test if the data is fully loaded on the column. Thanks Alex Martelli !
Huh, just after offering the bounty, I've found out the solution. You have to use `SET TEXTSIZE 2147483647` on the query, in addition of text size configuration option in `/etc/freetds/freetds.conf`. I have used ``` cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1') ``` And everything worked fine. Strange is what [FreeTDS documentation says](http://www.freetds.org/userguide/freetdsconf.htm) about the text size configuration option: > *default value of `TEXTSIZE`, in bytes. For `text` and `image` datatypes, sets the maximum width of any returned column. Cf. `set TEXTSIZE` in the `T-SQL` documentation for your server.* The configuration also says that the maximum value (and the default) is 4,294,967,295. However when trying to use that value in the query I get an error, the max number I could use in the query is 2,147,483,647 (half). From that explanation I thought that only setting this configuration option would be enough. It turns out that I was wrong, setting TEXTSIZE in the query fixed the issue. Below is the complete working code: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import pyodbc import urllib2 odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS" con = pyodbc.connect(odbcstring) cur = con.cursor() cur.execute(""" IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'testing') DROP TABLE testing """) cur.execute(''' CREATE TABLE testing ( id INTEGER NOT NULL IDENTITY(1,1), myimage IMAGE NULL, PRIMARY KEY (id) ) ''') con.commit() cur = con.cursor() url = 'http://www.forestwander.com/wp-content/original/2009_02/west-virginia-mountains.jpg' data = urllib2.urlopen(url).read() sql = "INSERT INTO testing (myimage) VALUES (?)" cur.execute(sql, (pyodbc.Binary(data),)) con.commit() cur.execute('SELECT DATALENGTH(myimage) FROM testing WHERE id = 1') data_inside = cur.fetchone()[0] assert data_inside == len(data) cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1') result = cur.fetchone() returned_data = str(result[0]) print 'Original: %d; Returned; %d' % (len(data), len(returned_data)) assert data == returned_data ```
I think you should be using a `pyodbc.Binary` instance to wrap the data: ``` cur.execute('INSERT INTO testing (myimage) VALUES (?)', (pyodbc.Binary(data),)) ``` Retrieving should be ``` cur.execute('SELECT myimage FROM testing') print "image bytes: %r" % str(cur.fetchall()[0][0]) ``` **UPDATE:** The problem is in insertion. Change your insertion SQL to the following: ``` """DECLARE @txtptr varbinary(16) INSERT INTO testing (myimage) VALUES ('') SELECT @txtptr = TEXTPTR(myimage) FROM testing WRITETEXT testing.myimage @txtptr ? """ ``` I've also updated the mistake I made in using the value attribute in the retrieval code. With this change, I'm able to insert and retrieve a 320K JPEG image into the database (retrieved data is identical to inserted data). N.B. The `image` data type is deprecated, and is replaced by `varbinary(max)` in later versions of SQL Server. The same logic for insertion/retrieval should apply, however, for the newer column type.
using pyodbc on ubuntu to insert a image field on SQL Server
[ "", "python", "sql-server", "image", "pyodbc", "freetds", "" ]
I am getting into C# and I am having this issue: ``` namespace MyDataLayer { namespace Section1 { public class MyClass { public class MyItem { public static string Property1{ get; set; } } public static MyItem GetItem() { MyItem theItem = new MyItem(); theItem.Property1 = "MyValue"; return theItem; } } } } ``` I have this code on a UserControl: ``` using MyDataLayer.Section1; public class MyClass { protected void MyMethod { MyClass.MyItem oItem = new MyClass.MyItem(); oItem = MyClass.GetItem(); someLiteral.Text = oItem.Property1; } } ``` Everything works fine, except when I go to access `Property1`. The intellisense only gives me "`Equals`, `GetHashCode`, `GetType`, and `ToString`" as options. When I mouse over the `oItem.Property1`, Visual Studio gives me this explanation: > `Member`MyDataLayer.Section1.MyClass.MyItem.Property1.get`cannot be accessed with an instance reference, qualify it with a type name instead` I am unsure of what this means, I did some googling but wasn't able to figure it out.
In C#, unlike VB.NET and Java, you can't access `static` members with instance syntax. You should do: ``` MyClass.MyItem.Property1 ``` to refer to that property or remove the `static` modifier from `Property1` (which is what you probably want to do). For a conceptual idea about what [`static` is, see my other answer](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-java/413904#413904).
You can only access static members using the name of the type. Therefore, you need to either write, ``` MyClass.MyItem.Property1 ``` Or (this is probably what you need to do) make `Property1` an instance property by removing the `static` keyword from its definition. Static properties are shared between all instances of their class, so that they only have one value. The way it's defined now, there is no point in making any instances of your MyItem class.
Member '<member name>' cannot be accessed with an instance reference
[ "", "c#", "asp.net", "" ]
So I have a custom ListView object. The list items have two textviews stacked on top of each other, plus a horizontal progress bar that I want to remain hidden until I actually do something. To the far right is a checkbox that I only want to display when the user needs to download updates to their database(s). When I disable the checkbox by setting the visibility to Visibility.GONE, I am able to click on the list items. When the checkbox is visible, I am unable to click on anything in the list except the checkboxes. I've done some searching but haven't found anything relevant to my current situation. I found [this question](https://stackoverflow.com/questions/895341/custom-list-clicking-with-checkboxes-in-android) but I'm using an overridden ArrayAdapter since I'm using ArrayLists to contain the list of databases internally. Do I just need to get the LinearLayout view and add an onClickListener like Tom did? I'm not sure. Here's the listview row layout XML: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="6dip"> <LinearLayout android:orientation="vertical" android:layout_width="0dip" android:layout_weight="1" android:layout_height="fill_parent"> <TextView android:id="@+id/UpdateNameText" android:layout_width="wrap_content" android:layout_height="0dip" android:layout_weight="1" android:textSize="18sp" android:gravity="center_vertical" /> <TextView android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:id="@+id/UpdateStatusText" android:singleLine="true" android:ellipsize="marquee" /> <ProgressBar android:id="@+id/UpdateProgress" android:layout_width="fill_parent" android:layout_height="wrap_content" android:indeterminateOnly="false" android:progressDrawable="@android:drawable/progress_horizontal" android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal" android:minHeight="10dip" android:maxHeight="10dip" /> </LinearLayout> <CheckBox android:text="" android:id="@+id/UpdateCheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> ``` And here's the class that extends the ListActivity. Obviously it's still in development so forgive the things that are missing or might be left laying around: ``` public class UpdateActivity extends ListActivity { AccountManager lookupDb; boolean allSelected; UpdateListAdapter list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); lookupDb = new AccountManager(this); lookupDb.loadUpdates(); setContentView(R.layout.update); allSelected = false; list = new UpdateListAdapter(this, R.layout.update_row, lookupDb.getUpdateItems()); setListAdapter(list); Button btnEnterRegCode = (Button)findViewById(R.id.btnUpdateRegister); btnEnterRegCode.setVisibility(View.GONE); Button btnSelectAll = (Button)findViewById(R.id.btnSelectAll); btnSelectAll.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { allSelected = !allSelected; for(int i=0; i < lookupDb.getUpdateItems().size(); i++) { lookupDb.getUpdateItem(i).setSelected(!lookupDb.getUpdateItem(i).isSelected()); } list.notifyDataSetChanged(); // loop through each UpdateItem and set the selected attribute to the inverse } // end onClick }); // end setOnClickListener Button btnUpdate = (Button)findViewById(R.id.btnUpdate); btnUpdate.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { } // end onClick }); // end setOnClickListener lookupDb.close(); } // end onCreate @Override protected void onDestroy() { super.onDestroy(); for (UpdateItem item : lookupDb.getUpdateItems()) { item.getDatabase().close(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); UpdateItem item = lookupDb.getUpdateItem(position); if (item != null) { item.setSelected(!item.isSelected()); list.notifyDataSetChanged(); } } private class UpdateListAdapter extends ArrayAdapter<UpdateItem> { private List<UpdateItem> items; public UpdateListAdapter(Context context, int textViewResourceId, List<UpdateItem> items) { super(context, textViewResourceId, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = null; if (convertView == null) { LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = li.inflate(R.layout.update_row, null); } else { row = convertView; } UpdateItem item = items.get(position); if (item != null) { TextView upper = (TextView)row.findViewById(R.id.UpdateNameText); TextView lower = (TextView)row.findViewById(R.id.UpdateStatusText); CheckBox cb = (CheckBox)row.findViewById(R.id.UpdateCheckBox); upper.setText(item.getName()); lower.setText(item.getStatusText()); if (item.getStatusCode() == UpdateItem.UP_TO_DATE) { cb.setVisibility(View.GONE); } else { cb.setVisibility(View.VISIBLE); cb.setChecked(item.isSelected()); } ProgressBar pb = (ProgressBar)row.findViewById(R.id.UpdateProgress); pb.setVisibility(View.GONE); } return row; } } // end inner class UpdateListAdapter } ``` edit: I'm still having this problem. I'm cheating and adding onClick handlers to the textviews but it seems extremely stupid that my onListItemClick() function is not being called at all when I am not clicking on my checkbox.
The issue is that Android doesn't allow you to select list items that have elements on them that are focusable. I modified the checkbox on the list item to have an attribute like so: ``` android:focusable="false" ``` Now my list items that contain checkboxes (works for buttons too) are "selectable" in the traditional sense (they light up, you can click anywhere in the list item and the "onListItemClick" handler will fire, etc). EDIT: As an update, a commenter mentioned "Just a note, after changing the visibility of the button I had to programmatically disable the focus again."
In case you have ImageButton inside the list item you should set the `descendantFocusability` value to 'blocksDescendants' in the root list item element. ``` android:descendantFocusability="blocksDescendants" ``` And the `focusableInTouchMode` flag to `true` in the `ImageButton` view. ``` android:focusableInTouchMode="true" ```
Custom ListView click issue on items in Android
[ "", "java", "android", "android-listview", "" ]
I have found the `Form.TopMost` property but it puts the form on top of everything, including stuff that isn't part of my app. I've got a suspicion that I'm missing something obvious here. (Is `Form` the proper bases class for a non modal dialog box?)
Use the Form.Owner property of your dialog form and set it to the main Form. Read more here <http://msdn.microsoft.com/en-us/library/system.windows.forms.form.owner.aspx> The Owned form will never be displayed behind the Owner Form.
It is very simple; You just have to pass the owner when you call the `Show()` method ``` YourForm.Show(parentForm); ```
How do a make one form stay on top of another?
[ "", "c#", "winforms", "" ]
Is there a way to check if my hosting provider has mod\_gzip enabled? It's not mentioned in any info on the web site, nor there is a forum to contact other people about this problem. Thanks.
You can check that with either PHP’s [`apache_get_modules`](http://docs.php.net/php_get_modules) or [`phpinfo`](http://docs.php.net/phpinfo). If you want to compress your output, you might want to try the [output buffer handler `ob_gzhandler`](http://docs.php.net/ob_gzhandler). It automatically determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. Just put `ob_start('ob_gzhandler')` at the start of your script file (before anything is put out) and it does the rest. Or you simply use [Apache’s mod\_deflate](http://httpd.apache.org/docs/2.2/mod/mod_deflate.html) that even can compress static files that are directly passed through to the client.
If you upload a tiny little PHP file to your server containing the following you can see all the output from phpinfo. Lots of interesting details. ``` <?php phpinfo(); ?> ``` Searching the page for "Loaded Modules" should show all the modules that are loaded. Look for [mod\_deflate](http://httpd.apache.org/docs/2.0/mod/mod_deflate.html) also as that seems to be more common (comes with Apache 2.0 installs anyway). Performance? gzip might be more compress, deflate might be faster.
How to check if my shared hosting provider has mod_gzip installed?
[ "", "php", "apache", "gzip", "" ]
I just wrote a PHP login script, and what I'm trying to accomplish is that when the user click to the log out link, after they log out, regardless clicking the back button of the browser, they cannot access the page. Here is the logout function: ``` //Start the Session session_start(); session_destroy(); header("location:login.php"); exit(); ``` I did place the following code on all the pages, and this seems not do the job: ``` header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); //Start the Session session_start(); ``` Any suggestions?
Check when the user is logged out if the session global is still set with the correct value. ``` print_r($_SESSION); ``` The reason for this is that you are doing a session\_destroy and then a header redirect, what happens is that you force a redirect and the destroying of the session isnt written to the server that way.
You can't control the workings of the client-side back button on the server. You could destroy the history data using javascript on the client. The client can completely ignore the no-cache headers.
How can I not allow a user to go back after logout in PHP?
[ "", "php", "" ]
For a TCP blocking socket, is it safe to call: ``` if(SOCKET_ERROR != recv(s, NULL, 0, 0)) //... ``` to detect errors? I thought it was safe, then I had a situation on a computer that it was hanging on this statement. (was with an ssl socket if that matters). I also tried passing in the MSG\_PEEK flag with a buffer specified but I also had a hang there. What is the alternative?
In addition to other answers - here's a handy little function to get the pending socket error: ``` /* Retrives pending socket error. */ int get_socket_error( int sockfd ) { int error; socklen_t len( sizeof( error )); if ( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) < 0 ) error = errno; return error; } ```
You did say you were using a blocking socket, but you should use select instead (even if you set it unblocking before the select call). It allows you to poll a file descriptor and see if there is data waiting, or if there is an error.
is it safe to recv passing in 0 to detect a socket error?
[ "", "c++", "sockets", "" ]
I have a partly inherited web application in PHP and after poking around with Fiddler I have a little more data than before. The problem I'm trying to solve is unwanted logouts on IE6/8 but not FF/Chrome. If a user clicks between different pages, the login data cookies vanish. The behavior is different in FF vs. IE, and the reported information is different in almost exactly the same way between Fiddler(/IE) and Live HTTP Headers(/FF). In Firefox the cookies appear to be treated like the PHP specifies: they are created when the user logs in and checks "Remember me", and they are only deleted if the user visits the logout page, and they have a two week expiration date. Live HTTP Headers report nothing different: the cookies are never reported as being changed or deleted when the user clicks between pages. But with IE, they disappear when the user clicks between different pages, and Fiddler reports, ``` Cookies / Login Set-Cookie: *******=deleted; expires=Sun, 29-Jun-2008 21:07:46 GMT; path=; domain=.********.com Set-Cookie: *******=deleted; expires=Sun, 29-Jun-2008 21:07:46 GMT; path=; domain=.********.com ``` ('deleted' is literally quoted from Fiddler's output. I do not have any place in my code where either value is set to a magic string of 'deleted'.) Not only do IE and Firefox have different interpretations of how the site is saying but Fiddler and HTTP Live Headers report correspondingly different versions of what the site does. Is there something special about IE and 'deleted'? This may sound strange, but does IE want cookies to be re-enabled with each page view or something like that? And how can I appease IE to bless the cookies in question as not deleted by the server unless the user requests it by visiting the logout URL?
What I eventually found was as follows: Firefox and IE were behaving differently because they were treating caching differently when a missing document was within the 14 day Expires: headers that had been set. Firefox was apparently checking once for missing data, and then not requesting it again. IE, on the other hand, kept on checking for an item a stylesheet gave the wrong path for, got 404 pages, and the custom 404 page did a boilerplate invitation to log in that triggered the user being logged out (perhaps not the best boilerplate). I guess the stylesheet was cached, but IE kept on asking for items that were missing. So it was caching differences plus indirect inclusion plus 404 page behavior. I still don't know what "deleted" came from. (Does PHP supply the word "deleted" if you set a cookie string to an empty value?)
IE won't set a cookie if the host has an underscore in it, but that's not the problem here. Fiddler doesn't "invent" anything-- if it says that it got a HTTP header setting the cookie to the value "deleted", that means that the server literally sent that. You might want to take a look at whether or not you have any errant requests going out on the wire that are causing the server to delete the cookies. For instance, in another thread, someone noted that an IMG tag with a source of "" (empty string) would cause IE to send a request for the root of the site, and their homepage deleted the login cookies if visited. IE6/7/8 currently have a limit of 50 cookies per host, but that's not what you're hitting here either.
Why would IE/Fiddler see different cookie setting/deletion from Chrome and FF/Live HTTP Headers?
[ "", "php", "internet-explorer", "session", "cookies", "fiddler", "" ]
I have a class that currently has several methods that take integer parameters. These integers map to operations that the application can perform. I'd like to make the class generic so that the consumers of the class can provide an enum type that they have with all the operations in it, then the methods will take parameters of that enum type. However, I want them to be able to not specify a generic type at all, and have it default back to integers with no change in syntax from the current way. Is this possible?
You can't do it in the definition of the class: ``` var foo = new MyGenericClass(); // defaults to integer... this doesn't work var bar = new MyGenericClass<MyEnum>(); // T is a MyEnum ``` If really value the implicitness of the default type being int, you'll have to do it with a static factory method, although I don't see the value of it. ``` public class MyGenericClass<T> { public static MyGenericClass<T> Create() { return new MyGenericClass<T>(); } public static MyGenericClass<int> CreateDefault() { return new MyGenericClass<int>(); } } ``` See below for how you really don't benefit from the above. ``` var foo = MyGenericClass<MyEnum>.Create(); var bar1 = MyGenericClass.CreateDefault(); // doesn't work var bar2 = MyGenericClass<int>.CreateDefault(); // works, but what's the point ``` If you want to take it even farther, you can create a static factory class that will solve this, but that's an even more ridiculous solution if you're doing it for no other reason than to provide a default type: ``` public static class MyGenericClassFactory { public static MyGenericClass<T> Create<T>() { return new MyGenericClass<T>(); } public static MyGenericClass<int> Create() { return new MyGenericClass<int>(); } } var foo = MyGenericClassFactory.Create(); // now we have an int definition var bar = MyGenericClassFactory.Create<MyEnum>(); ```
So... why not use simple inheritance? Like: ``` class MyGenericClass<T> { } class MyGenericClass : MyGenericClass<int> { } ``` This way you can write both ways: ``` var X = new MyGenericClass<string>(); var Y = new MyGenericClass(); // Is now MyGenericClass<int> ```
How do you provide a default type for generics?
[ "", "c#", ".net", "generics", ".net-2.0", "" ]
I'm finishing up some of my first C# classes and even though the original code I inherited is completely void of comments, I always put javadoc comments on my methods when I was writing java and my code currently looks strange without those blocks. I normally formatted my comments by using the "Insert JavaDoc" command in Eclipse, which simply laid out the template and pulled in the parameters, method name, etc...from the method the command was run on. Then I could add more detail from there. Is there a similar command in Visual Studio 2008? I couldn't find one when I was poking around the menus. Additionally, is there a standard convention of commenting style (similar to JavaDoc) that is used in the C# world?
If you type `///` the IDE editor will automatically generate an empty XML comment for you. This: ``` /// public QName(String qName, XmlNode contextNode) { ``` Becomes this: ``` /// <summary> /// /// </summary> /// <param name="qName"></param> /// <param name="contextNode"></param> public QName(String qName, XmlNode contextNode) { ``` If your method throws any exceptions you'll have to manually add tags since .NET does not have declared exceptions. Final comment: ``` /// <summary>Creates a new QName from a string with the format /// <c>prefix:local-name</c> or <c>local-name</c>.</summary> /// /// <param name="qName">A QName string.</param> /// <param name="contextNode">An XML node from which to lookup the namespace /// prefix, or <c>null</c>.</param> /// /// <exception cref="XmlInvalidPrefixException">Thrown if the prefix cannot be /// resolved from the lookup node. If <paramref name="contextNode"/> is /// <c>null</c>, then the only prefix that can be resolved is <c>xml</c>. /// </exception> public QName(String qName, XmlNode contextNode) { ```
Type three forward slashes before any method: ``` /// ``` This will generate an XML comment block.
Commenting Style (i.e. Javadocing C# Version) - (Java Developer Learning C#)
[ "", "c#", "visual-studio-2008", "comments", "" ]
My scenario: * I have one color background image JPG. * I have one black text on white background JPG. * Both images are the same size (height and width) I want to overlay the image with black text and white background over the color background image, i.e. the white background becomes transparent to see the color background beneath it. How can I do this with GDI in C#? Thanks!
Thanks to [GalacticCowboy](https://stackoverflow.com/questions/1071374/merging-jpgs-with-gdi-in-c/1071394#1071394) I was able to come up with this solution: ``` using (Bitmap background = (Bitmap)Bitmap.FromFile(backgroundPath)) { using (Bitmap foreground = (Bitmap)Bitmap.FromFile(foregroundPath)) { // check if heights and widths are the same if (background.Height == foreground.Height & background.Width == foreground.Width) { using (Bitmap mergedImage = new Bitmap(background.Width, background.Height)) { for (int x = 0; x < mergedImage.Width; x++) { for (int y = 0; y < mergedImage.Height; y++) { Color backgroundPixel = background.GetPixel(x, y); Color foregroundPixel = foreground.GetPixel(x, y); Color mergedPixel = Color.FromArgb(backgroundPixel.ToArgb() & foregroundPixel.ToArgb()); mergedImage.SetPixel(x, y, mergedPixel); } } mergedImage.Save("filepath"); } } } } ``` Works like a charm. Thanks!
There exist easier and faster way. You should use ImageAttributes when you draw image that must be partially visible. ``` Image BackImage = Image.FromFile(backgroundPath); using (Graphics g = Graphics.FromImage(BackImage)) { using (ForeImage = Image.FromFile(foregroundPath)) { ImageAttributes imageAttr = new ImageAttributes(); imageAttr.SetColorKey(Color.FromArgb(245, 245, 245), Color.FromArgb(255, 255, 255), ColorAdjustType.Default); g.DrawImage(ForeImage, new Rectangle(0, 0, BackImage.Width, BackImage.Height), 0, 0, BackImage.Width, BackImage.Height, GraphicsUnit.Pixel, imageAttr); } } ``` SetColorKey method will make color from specified range transparent, so you can make your white bitmap pixels transparent, including all pixels that are affected to jpeg compression artefacts.
Merging JPGs with GDI in C#
[ "", "c#", "transparency", "gdi", "jpeg", "" ]
C# will not allow to write non-member functions and every method should be part of a class. I was thinking this as a restriction in all CLI languages. But I was wrong and I found that C++/CLI supports non-member functions. When it is compiled, compiler will make the method as member of some unnamed class. Here is what C++/CLI standard says, > [Note: Non-member functions are treated by the CLI as members of some unnamed class; however, in C++/CLI source code, such functions cannot be qualified explicitly with that class name. end note] > > The encoding of non-member functions in metadata is unspecified. [Note: This does not cause interop problems because such functions cannot have public visibility. end note] So my question is why don't C# implement something like this? Or do you think there should not be non-member functions and every method should belong to some class? My opinion is to have non-member function support and it helps to avoid polluting class's interface. Any thoughts..?
UPDATE: This question from 2009 has been rather overtaken by language evolution. Since C# 10, the language has supported top-level statements outside of class declarations, rendering the "why not" question nonsensical. --- See this blog posting: <https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-doesnt-c-implement-top-level-methods> > (...) > > I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money. Features are not cheap, and we try very hard to make sure that we are only shipping those features which give the best possible benefits to our users given our constrained time, effort and money budgets. > > I understand that such a general answer probably does not address the specific question. > > In this particular case, the clear user benefit was in the past not large enough to justify the complications to the language which would ensue. By stricting how different language entities nest inside each other we (1) restrict legal programs to be in a common, easily understood style, and (2) make it possible to define "identifier lookup" rules which are comprehensible, specifiable, implementable, testable and documentable. > > By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified identifier used in an invocation context; such a thing is always an invocable member of the current type (or a base type). > > (...) and this follow-up posting: [http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx](https://web.archive.org/web/20100316193329/http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx) > (...) > > Like all design decisions, when we're faced with a number of competing, compelling, valuable and noncompossible ideas, we've got to find a workable compromise. We don't do that except by **considering all the possibilites**, which is what we're doing in this case. *(emphasis from original text)*
C# doesn't allow it because Java didn't allow it. I can think of several reasons why the designers of Java probably didn't allow it * Java was designed to be simple. They attempted to make a language without random shortcuts, so that you generally have just one simple way to do everything, even if other approaches would have been cleaner or more concise. They wanted to minimize the learning curve, and learning "a class may contain methods" is simpler than "a class may contain methods, and functions may exist outside classes". * Superficially, it looks less object-oriented. (Anything that isn't part of an object obviously can't be object-oriented? Can it? of course, C++ says yes, but C++ wasn't involved in this decision) As I already said in comments, I think this is a good question, and there are plenty of cases where non-member functions would've been preferable. (this part is mostly a response to all the other answers saying "you don't need it") In C++, where non-member functions are allowed, they are often preferred, for several reasons: * It aids encapsulation. The fewer methods have access to the private members of a class, the easier that class will be to refactor or maintain. Encapsulation is an important part of OOP. * Code can be reused much easier when it is not part of a class. For example, the C++ standard library defines `std::find` or std::sort` as non-member functions, so that they can be reused on any type of sequences, whether it is arrays, sets, linked lists or (for std::find, at least) streams. Code reuse is also an important part of OOP. * It gives us better decoupling. The `find` function doesn't need to know about the LinkedList class in order to be able to work on it. If it had been defined as a member function, it would be a member of the LinkedList class, basically merging the two concepts into one big blob. * Extensibility. If you accept that the interface of a class is not just "all its public members", but also "all non-member functions that operate on the class", then it becomes possible to extend the interface of a class without having to edit or even recompile the class itself. The ability to have non-member functions may have originated with C (where you had no other choice), but in modern C++, it is a vital feature in its own right, not just for backward-comparibility purposes, but because of the simpler, cleaner and more reusable code it allows. In fact, C# seems to have realized much the same things, much later. Why do you think extension methods were added? They are an attempt at achieving the above, while preserving the simple Java-like syntax. Lambdas are also interesting examples, as they too are essentially small functions defined freely, not as members of any particular class. So yes, the concept of non-member functions is useful, and C#'s designers have realized the same thing. They've just tried to sneak the concept in through the back door. <http://www.ddj.com/cpp/184401197> and <http://www.gotw.ca/publications/mill02.htm> are two articles written by C++ experts on the subject.
Why C# is not allowing non-member functions like C++
[ "", "c#", ".net", "function", "c++-cli", "clr", "" ]
What are the `?` and `:` operators in PHP? For example: ``` (($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER) ```
This is the **conditional operator**. ``` $x ? $y : $z ``` means "if `$x` is true, then use `$y`; otherwise use `$z`". It also has a short form. ``` $x ?: $z ``` means "if `$x` is true, then use `$x`; otherwise use `$z`". People will tell you that `?:` is "the ternary operator". This is wrong. `?:` is *a* ternary operator, which means that it has three operands. People wind up thinking its name is "the ternary operator" because it's often the only ternary operator a given language has.
> I'm going to write a little bit on ternaries, what they are, how to use them, when and why to use them and when not to use them. **What is a ternary operator?** A ternary `? :` is shorthand for `if` and `else`. That's basically it. See "Ternary Operators" half way down [this page](http://php.net/manual/en/language.operators.comparison.php) for more of an official explanation. **As of PHP 5.3**: > Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. **As of PHP 7.0** > PHP 7 has new Null Coalesce Operator. This is the same as a ternary but is also called an "[isset ternary](https://wiki.php.net/rfc/isset_ternary)". This also allows a set of chained ternaries that remove the need for isset() checks. In PHP 5, if you wanted to use a ternary with a potentially non-existent variable then you would have to perform an isset() at the beginning of the ternary statement: ``` $result = isset($nonExistentVariable) ? $nonExistentVariable : ‘default’; ``` In PHP 7, you can now do this instead: ``` $result = $nonExistentVariable ?? ‘default’; ``` The Null Coalesce Operator does not work with an empty string, however, so bear that in mind. The great thing about this is you can also chain the operators for multiple checks for multiple variables, providing a sort of backup depending on whether or not each variable in the chain exists: ``` $user = $userImpersonatingAnotherUser ?? $loggedInUser ?? “Guest”; ``` In PHP, with systems where a user can login, it is not uncommon for an administrator to be able to impersonate another user for testing purposes. With the above example, if the user is not impersonating another user, and also a logged in user does not exist, then the user will be a guest user instead. Read on more if you don't understand this yet to see what ternaries are and how they are used, and then come back to this bit to see how the new PHP **How are ternaries used?** Here's how a normal `if` statement looks: ``` if (isset($_POST['hello'])) { $var = 'exists'; } else { $var = 'error'; } ``` Let's shorten that down into a ternary. ``` $var = isset($_POST['hello']) ? 'exists' : 'error'; ^ ^ ^ ^ | | then | else | | | | if post isset $var=this $var=this ``` Much shorter, but maybe harder to read. Not only are they used for setting variables like `$var` in the previous example, but you can also do this with `echo`, and to check if a variable is false or not: ``` $isWinner = false; // Outputs 'you lose' echo ($isWinner) ? 'You win!' : 'You lose'; // Same goes for return return ($isWinner) ? 'You win!' : 'You lose'; ``` **Why do people use them?** I think ternaries are sexy. Some developers like to show off, but sometimes ternaries just **look nice** in your code, *especially* when combined with other features like PHP 5.4's latest [short echos](https://stackoverflow.com/questions/14188397/why-are-echo-short-tags-permanently-enabled-as-of-php-5-4). ``` <?php $array = array(0 => 'orange', 1 => 'multicoloured'); ?> <div> <?php foreach ($array as $key => $value) { ?> <span><?=($value==='multicoloured')?'nonsense':'pointless'?></span> <?php } ?> </div> <!-- Outputs: <span> pointless </span> <span> nonsense </span> --> ``` Going off-topic slightly, when you're in a 'view/template' (if you're seperating your concerns through the [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) paradigm), you want as little server-side logic in there as possible. So, using ternaries and other short-hand code is sometimes the best way forward. By "other short-hand code", I mean: ``` if ($isWinner) : // Show something cool endif; ``` *Note, I personally do not like this kind of shorthand if / endif nonsense* **How fast is the ternary operator?** People LIKE micro-optimisations. They just do. So for some, it's important to know how much faster things like ternaries are when compared with normal `if` / `else` statements. Reading [this post](http://fabien.potencier.org/article/48/the-php-ternary-operator-fast-or-not), the differences are about 0.5ms. That's a lot! Oh wait, no it's not. It's only a lot if you're doing thousands upon thousands of them in a row, repeatedly. Which you won't be. So don't worry about speed optimisation at all, it's absolutely pointless here. **When not to use ternaries** Your code should be: * Easy to read * Easy to understand * Easy to modify Obviously this is subject to the persons intelligence and coding knowledge / general level of understanding on such concepts when coming to look at your code. A single simple ternary like the previous examples are okay, something like the following, however, is **not** what you should be doing: ``` echo ($colour === 'red') ? "Omg we're going to die" : ($colour === 'blue' ? "Ah sunshine and daisies" : ($colour === 'green' ? "Trees are green" : "The bloody colour is orange, isn't it? That was pointless.")); ``` That was pointless for three reasons: * Ridiculously long ternary embedding * Could've just used a `switch` statement * It was orange in the first place **Conclusion** Ternaries really are simple and nothing to get too worked up about. Don't consider **any** speed improvements, it really won't make a difference. Use them when they are **simple** and **look nice**, and always make sure your code will be readable by others in the future. If that means no ternaries, then don't use ternaries.
What are the PHP operators "?" and ":" called and what do they do?
[ "", "php", "syntax", "conditional-statements", "conditional-operator", "" ]
I'm trying to query a MySQL database using an array but I'm having trouble! I have a table called clients, I want to be able to select 'name' from all rows whose 'sector' column is equal to $sectorlink. I then want to put all the names into an array so I can perform my next query: select all rows from another table whose 'client' column is equal to one of the names returned from the first query. I'm doing something wrong because it returns a fatal SQL error. I'm getting confused with all the variables! $sectorlink and $connection are the only variables that are defined outside of this code Any suggestions? ``` $query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'"; $clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR); while($row = mysql_fetch_array($clientresult)){ foreach($row AS $key => $value){$temp[] = '"'.$value.'"';} $thelist = implode(",",$temp); $query = "SELECT count(*) FROM studies WHERE client IN ($row) ORDER BY (date) desc"; $result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR); } ```
The second query should use `$thelist` not `$row`, and it should be outside of the `while` loop. The `foreach` loop is unnecessary when processing a single row. You can access the name in `$row` with a simple `$row[0]`. Something like this (untested): ``` $query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'"; $clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR); while($row = mysql_fetch_array($clientresult)){ $temp[] = '"'.$row[0].'"'; } $thelist = implode(",",$temp); $query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY (date) desc"; $result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR); ``` **Caution:** Please be aware that your code is highly vulnerable to [SQL injection attacks](https://www.php.net/manual/en/security.database.sql-injection.php). It's fine for testing or internal development but if this code is going to be running the Fort Knox web site you're going to want to fix it up quite a bit. Just an FYI. :-)
Couple of things. First you have an unnecessary loop there. Try: ``` while (list($name) = mysql_fetch_row($clientresult)) { $temp[] = $name; } ``` To build your temporary array. Second, the parts of the `IN` clause are strings, so when you implode, you'll need to enclose each value in quotes: ``` $thelist = "'". implode("','", $temp) . "'"; ``` Lastly, in your query you are passing `$row` to the `IN` clause, you should be passing `$thelist`: ``` $query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc"; $result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR); ``` So altogether: ``` $query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'"; $clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR); while (list($name) = mysql_fetch_row($clientresult)) { $temp[] = $name; } $thelist = "'". implode("','", $temp) . "'"; $query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc"; $result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR); ```
MySQL query using an array
[ "", "php", "mysql", "arrays", "" ]
Why can't I use `setTimeout` in a javascript object? ``` Message = function () { ... ... this.messageFactory = ... this.feedbackTag = document.getElementById('feedbackMessages'); this.addInfo = function (message) { var info = this.messageFactory.createInfo(message); // create a div this.feedbackTag.appendChild(info); setTimeout('this.feedbackTag.removeChild(info)', 5000); // why in here, it complain this.feedbacktag is undefined ?????? }; } ``` Thanks for Steve`s Solution, now it will work if the code is as below... because the 'this' before was actually pointing to the function within setTimeOut, it cannot rearch Message. ``` Message = function () { ... ... this.messageFactory = ... this.feedbackTag = document.getElementById('feedbackMessages'); this.addInfo = function (message) { var info = this.messageFactory.createInfo(message); // create a div this.feedbackTag.appendChild(info); var _this = this; setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000); }; } ``` But why doesn`t it work if we do this: ``` Message = function () { ... ... this.messageFactory = ... this.feedbackTag = document.getElementById('feedbackMessages'); // public function this.addInfo = function (message) { var info = this.messageFactory.createInfo(message); // create a div this.feedbackTag.appendChild(info); delayRemove(info); }; // private function function delayRemove(obj) { var _this = this; setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000); } } ```
Try replacing this line: ``` setTimeout('this.feedbackTag.removeChild(info)', 5000); ``` with these two lines: ``` var _this = this; setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000); ``` **Note:** Never pass [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) a string, as this invokes `eval` (which you should only use when necessary). Instead, pass [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) a function reference (this can be an anonymous function). Finally, always check that the `this` keyword is pointing to what you think it points to (see <http://www.alistapart.com/articles/getoutbindingsituations>). **Addressing Question 2:** I believe that for normal functions, `this` is set to the `window` object—regardless of where they are declared. So moving the code into a separate function wouldn't fix the problem.
A neater way is to just pass *this* as an argument to the function being called in the timeout: ``` function delayRemove(obj) { setTimeout(function(_this) { _this.feedbackTag.removeChild(obj); }, 5000, this); } ``` You should really pass *obj* as an argument as well, just to make sure it is in scope (the number of parameters is unlimited): ``` function delayRemove(obj) { setTimeout(function(_this, removeObj) { _this.feedbackTag.removeChild(removeObj); }, 5000, this, obj); } ``` --- HTML5 and Node.js extended the `setTimeout` function to accept parameters which are passed to your callback function. It has the following method signature. `setTimeout(callback, delay, [param1, param2, ...])` As `setTimeout` [isn't actually a JavaScript feature](https://stackoverflow.com/a/8852244/155715) your results may vary across browsers. I couldn't find any concrete details of support, however as I said this is in the HTML5 spec.
How to use "setTimeout" to invoke object itself
[ "", "javascript", "settimeout", "" ]
I'm used to the old Winforms way of doing things. Apparently WPF ListViews are full of... XmlElements? How would I do something like disabling a `ListViewItem`? ``` foreach (XmlElement item in this.lvwSourceFiles.Items) { //disable? } ```
`ListView` is an `ItemsControl`. `ItemsControl.Items` does not return the child *controls* - it returns the *items* - that is, objects that you have added to the `ListView`, either directly, or via data binding. I guess in this case you have bound your `ListView` to some XML, right? `ListViewItem` (and other classes like it - e.g. `ListBoxItem` for `ListBox`) is called an "item container". To retrieve an item container for a given item, you should do this: ``` ListView lv; ... foreach (object item in lv.Items) { ListViewItem lvi = (ListViewItem)lv.ItemContainerGenerator.ContainerFromItem(item); } ```
You need to access the `ListViewItem` that represents the data item. You can achieve that through the `ItemContainerGenerator` ``` foreach (object item in this.lvwSourceFiles.Items) { UIElement ui = lvwSourceFiles.ItemContainerGenerator.ContainerFromItem(item) as UIElement; if (ui != null) ui.IsEnabled = false; } ```
How do you disable a WPF ListViewItem in C# code?
[ "", "c#", "wpf", "listview", "" ]
I'm using IIS 6 on Windows Server 2003. The vision is to create a directory of those applications, showing their urls (ports on Server) and names.
I haven't done it, but I believe you need to use the following WMI object: ``` DirectoryEntry w3svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", serverName)); foreach (DirectoryEntry site in w3svc.Children) { //these are the web sites, lookup their properties to see how to extract url } ```
C# example: [link text](http://chiragrdarji.wordpress.com/2007/06/20/createdeleteview-virtual-directory-or-website-in-iis-using-c/) or This is a VB example, but I think you will use this idea: [link text](http://www.cruto.com/resources/vbscript/vbscript-examples/iis/iis6/web/List-Virtual-Directories.asp) ``` strComputer = "." Set objWMIService = GetObject _ ("winmgmts:{authenticationLevel=pktPrivacy}\\" _ & strComputer & "\root\microsoftiisv2") Set colItems = objWMIService.ExecQuery("Select * from IIsWebVirtualDir") For Each objItem in colItems Wscript.Echo "Application Isolated: " & objItem.AppIsolated Wscript.Echo "Application Package ID: " & objItem.AppPackageID Wscript.Echo "Application Package Name: " & objItem.AppPackageName Wscript.Echo "Application Root: " & objItem.AppRoot Wscript.Echo "Installation Date: " & objItem.InstallDate Wscript.Echo "Name: " & objItem.Name Next ```
How do you list all the web sites (not applications) being hosted by an IIS server?
[ "", "c#", "iis", "" ]