Search Results

Search found 149 results on 6 pages for 'tf idf'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • create TableModel and populate jTable dynamically

    - by Julia
    Hi all! I want to store the results of reading lucene index into jTable, so that I can make it sortable by different columns. From index I am reading terms with different measures of their frequencies. Table columns are these : [string term][int absFrequency][int docFrequency][double invFrequency] So i in AbstractTableModel I can define column names, but i dont know how to get the Object[][]data with results from the following method: public static void FrequencyMap(Directory indexDir) throws Exception { List<Object>redoviLista = new ArrayList<Object>(); //final Map<String,TermRow> map = new TreeMap<String,TermRow>(); List<String>termList = new ArrayList<String>(); IndexReader iReader = IndexReader.open(indexDir); FilterIndexReader fReader = new FilterIndexReader(iReader); int numOfDocs = fReader.numDocs(); TermEnum terms = fReader.terms(); while (terms.next()){ Term term = terms.term(); String termText = term.text(); termList.add(termText); //Calculating the frequencies int df = iReader.docFreq(term); double idf = 0.0F; idf = Math.log10((double) numOfDocs / df); double tfidf = (df*idf); //Here comes important part Object oneTableRow[] = {termText, df, idf, tfidf}; redoviLista.add(jedanRed); // So i thaught to store them into list, and then later to copy into table, but didnt manage } iReader.close(); // So I need something like this, and i Neeed this array to be stored out of this method Object[][]data = new Object[redoviLista.size()][]; for (int i = 0; i < data.length; i++) { data[i][0] = redoviLista.get(i); } So I am kindda stuck here to proceed to implement AbstractTableModel and populate and display this table .... :/ Please help!

    Read the article

  • Positioning / Scrolling problem with Flex popup.

    - by user284163
    Hi all, I'm trying to work out a specific problem I'm having with positioning in Flex using the PopUpManager. Basically I'm wanting to create a popup which will scroll with the parent container - this is necessary because the parent container is large and if the user's browser window isn't large enough (this will be the case the majority of the time) - they will have to use the scrollbar of the container to scroll down. The problem is that the popup is positioned relative to another component, and it needs to stay by that component. <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.core.UITextField; import mx.containers.TitleWindow; import mx.managers.PopUpManager; private function clickeroo(event:MouseEvent):void { var popup:TitleWindow = new TitleWindow(); popup.width = 250; popup.height = 300; popup.title = "Example"; var tf:UITextField = new UITextField(); tf.wordWrap = true; tf.width = popup.width - 30; tf.text = "This window stays put and doesn't scroll when the hbox is scrolled (even with using the hbox as parent in the addPopUp method), I need the popup to be local to the HBox."; popup.addChild(tf); PopUpManager.addPopUp(popup, hbox, false); PopUpManager.centerPopUp(popup); } ]]> </mx:Script> <mx:HBox width="100%" height="2000" id="hbox"> <mx:Button label="Click Me" click="clickeroo(event)"/> </mx:HBox> </mx:Application> Could anyone give me any pointers in the right direction? Thanks.

    Read the article

  • Template with constant expression: error C2975 with VC++2008

    - by Arman
    Hello, I am trying to use elements of meta programming, but hit the wall with the first trial. I would like to have a comparator structure which can be used as following: intersect_by<ID>(L1.data, L2.data, "By ID: "); intersect_by<IDf>(L1.data, L2.data, "By IDf: "); Where: struct ID{};// Tag used for original IDs struct IDf{};// Tag used for the file position //following Boost.MultiIndex examples template<typename Tag,typename MultiIndexContainer> void intersect_by( const MultiIndexContainer& L1,const MultiIndexContainer& L2,std::string msg, Tag* =0 /* fixes a MSVC++ 6.0 bug with implicit template function parms / ) { / obtain a reference to the index tagged by Tag */ const typename boost::multi_index::index<MultiIndexContainer,Tag>::type& L1_ID_index= get<Tag>(L1); const typename boost::multi_index::index<MultiIndexContainer,Tag>::type& L2_ID_index= get<Tag>(L2); std::set_intersection( L1_ID_index.begin(), L1_ID_index.end(), L2_ID_index.begin(), L2_ID_index.end(), std::inserter(s, s.begin()), strComparator() // Here I get the C2975 error ); } template<int N> struct strComparator; template<> struct strComparator<0>{ bool operator () (const particleID& id1, const particleID& id2) const { return id1.ID struct strComparator<1{ bool operator () (const particleID& id1, const particleID& id2) const { return id1.IDf }; What I am missing? kind regards Arman.

    Read the article

  • Error in rounding off values using .round in Ruby

    - by Shreyas Satish
    The following piece of code works perfectly in script/console but returns the following error when i compile the same in a ruby script.: :in `round': wrong number of arguments (1 for 0) (ArgumentError) tf={"ph"={0=1.33333333333333, 1=1.5}, "fee"={0=1.66666666666667}, "test"={0=1.16666666666667, 1=1.25}, "what"={0=2.0, 1=2.0}, "for"={0=1.5}, "is"={0=1.83333333333333, 1=1.75}} tf.each{|k,v| v.each{|k1,v1| tf[k][k1]=(v1.round(5))}} Any Ideas ? Cheers !

    Read the article

  • Adding JTextField to a JPanel and showing them

    - by Davide Gualano
    I'm building a little app using Java and Swing in NetBeans. Using NetBeans design window, I created a JFrame with a JPanel inside. Now I want to dynamically add some jTextFields to the JPanel. I wrote something like that: Vector textFieldsVector = new Vector(); JTextField tf; int i = 0; while (i < 3) { tf = new JTextField(); textFieldVector.add(tf); myPanel.add(tf); //myPanel is the JPanel where I want to put the JTextFields i++; } myPanel.validate(); myPanel.repaint(); But nothing happens: when I run the app, the JFrame shows with the JPanel inside, but the JTextFields don't. I'm a total newbie in writing graphical Java apps, so I'm surely missing something very simple, but I can't see what.

    Read the article

  • Using a "white list" for extracting terms for Text Mining, Part 2

    - by [email protected]
    In my last post, we set the groundwork for extracting specific tokens from a white list using a CTXRULE index. In this post, we will populate a table with the extracted tokens and produce a case table suitable for clustering with Oracle Data Mining. Our corpus of documents will be stored in a database table that is defined as create table documents(id NUMBER, text VARCHAR2(4000)); However, any suitable Oracle Text-accepted data type can be used for the text. We then create a table to contain the extracted tokens. The id column contains the unique identifier (or case id) of the document. The token column contains the extracted token. Note that a given document many have many tokens, so there will be one row per token for a given document. create table extracted_tokens (id NUMBER, token VARCHAR2(4000)); The next step is to iterate over the documents and extract the matching tokens using the index and insert them into our token table. We use the MATCHES function for matching the query_string from my_thesaurus_rules with the text. DECLARE     cursor c2 is       select id, text       from documents; BEGIN     for r_c2 in c2 loop        insert into extracted_tokens          select r_c2.id id, main_term token          from my_thesaurus_rules          where matches(query_string,                        r_c2.text)>0;     end loop; END; Now that we have the tokens, we can compute the term frequency - inverse document frequency (TF-IDF) for each token of each document. create table extracted_tokens_tfidf as   with num_docs as (select count(distinct id) doc_cnt                     from extracted_tokens),        tf       as (select a.id, a.token,                            a.token_cnt/b.num_tokens token_freq                     from                        (select id, token, count(*) token_cnt                        from extracted_tokens                        group by id, token) a,                       (select id, count(*) num_tokens                        from extracted_tokens                        group by id) b                     where a.id=b.id),        doc_freq as (select token, count(*) overall_token_cnt                     from extracted_tokens                     group by token)   select tf.id, tf.token,          token_freq * ln(doc_cnt/df.overall_token_cnt) tf_idf   from num_docs,        tf,        doc_freq df   where df.token=tf.token; From the WITH clause, the num_docs query simply counts the number of documents in the corpus. The tf query computes the term (token) frequency by computing the number of times each token appears in a document and divides that by the number of tokens found in the document. The doc_req query counts the number of times the token appears overall in the corpus. In the SELECT clause, we compute the tf_idf. Next, we create the nested table required to produce one record per case, where a case corresponds to an individual document. Here, we COLLECT all the tokens for a given document into the nested column extracted_tokens_tfidf_1. CREATE TABLE extracted_tokens_tfidf_nt              NESTED TABLE extracted_tokens_tfidf_1                  STORE AS extracted_tokens_tfidf_tab AS              select id,                     cast(collect(DM_NESTED_NUMERICAL(token,tf_idf)) as DM_NESTED_NUMERICALS) extracted_tokens_tfidf_1              from extracted_tokens_tfidf              group by id;   To build the clustering model, we create a settings table and then insert the various settings. Most notable are the number of clusters (20), using cosine distance which is better for text, turning off auto data preparation since the values are ready for mining, the number of iterations (20) to get a better model, and the split criterion of size for clusters that are roughly balanced in number of cases assigned. CREATE TABLE km_settings (setting_name  VARCHAR2(30), setting_value VARCHAR2(30)); BEGIN  INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.clus_num_clusters, 20);  INSERT INTO km_settings (setting_name, setting_value)     VALUES (dbms_data_mining.kmns_distance, dbms_data_mining.kmns_cosine);   INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.prep_auto,dbms_data_mining.prep_auto_off);   INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.kmns_iterations,20);   INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.kmns_split_criterion,dbms_data_mining.kmns_size);   COMMIT; END; With this in place, we can now build the clustering model. BEGIN     DBMS_DATA_MINING.CREATE_MODEL(     model_name          => 'TEXT_CLUSTERING_MODEL',     mining_function     => dbms_data_mining.clustering,     data_table_name     => 'extracted_tokens_tfidf_nt',     case_id_column_name => 'id',     settings_table_name => 'km_settings'); END;To generate cluster names from this model, check out my earlier post on that topic.

    Read the article

  • Existential CAML - does an item exist?

    - by PointsToShare
    © 2011 By: Dov Trietsch. All rights reserved More CAML and existence. In “SharePoint List Issues” and “Passing the CAML thru the EY of the NEEDL we saw how to use CAML to return a subset of a list and also how to check the existence of lists, fields, defaults, and values.   Here is a general function that may be used to get a subset of a list by comparing a “text” type field to a given value.  The function is pretty smart. It can be used to check existence or to return a collection of items that may be further processed. It handles non existing fields and replaces them with the ubiquitous “Title”, but only once!  /// Build an SPQuery that returns a selected set of columns from a List /// titleField must be a "Text" type field /// When the titleField parameter is empty ("") "Title" is assumed /// When the title parameter is empty ("") All is assumed /// When the columnNames parameter is null, the query returns all the fields /// When the rowLimit parameter is 0, the query return all the items. /// with a non-zero, the query returns at most rowLimits /// /// usage: to check if an item titled "Blah" exists in your list, do: /// colNames = {"Title"} /// col = GetListItemColumnByTitle(myList, "", "Blah", colNames, 1) /// Check the col.Count. if > 0 the item exists and is in the collection private static SPListItemCollection GetListItemColumnByTitle(SPList list, string titleField, string title, string[] columnNames, uint rowLimit) {   try   {     char QT = Convert.ToChar((int)34);     SPQuery query = new SPQuery();     if (title != "")     {       string tf = titleField;       if (titleField == "") tf = "Title";       tf = CAMLThisName(list, tf, "Title");        StringBuilder titleQuery = new StringBuilder  ("<Where><Eq><FieldRef Name=");       titleQuery.Append(QT);       titleQuery.Append(tf);       titleQuery.Append(QT);       titleQuery.Append("/><Value Type=");       titleQuery.Append(QT);       titleQuery.Append("Text");       titleQuery.Append(QT);       titleQuery.Append(">");       titleQuery.Append(title);       titleQuery.Append("</Value></Eq></Where>");       query.Query = titleQuery.ToString();     }     if (columnNames.Length != 0)     {       StringBuilder sb = new StringBuilder("");       bool TitleAlreadyIncluded = false;       foreach (string columnName in columnNames)       {         string tst = CAMLThisName(list, columnName, "Title");         //Allow Title only once         if (tst != "Title" || !TitleAlreadyIncluded)         {           sb.Append("<FieldRef Name=");           sb.Append(QT);           sb.Append(tst);           sb.Append(QT);           sb.Append("/>");           if (tst == "Title") TitleAlreadyIncluded = true;         }       }       query.ViewFields = sb.ToString();     }     if (rowLimit > 0)     {        query.RowLimit = rowLimit;     }     SPListItemCollection col = list.GetItems(query);     return col;   }   catch (Exception ex)   {     //Console.WriteLine("GetListItemColumnByTitle" + ex.ToString());     //sw.WriteLine("GetListItemColumnByTitle" + ex.ToString());     return null;   } } Here I called it for a list in which “Author” (it is the internal name for “Created”) and “Blah” do not exist. The list of column names is:  string[] columnNames = {"Test Column1", "Title", "Author", "Allow Multiple Ratings", "Blah"};  So if I use this call, I get all the items for which “01-STD MIL_some” has the value of 1. the fields returned are: “Test Column1”, “Title”, and “Allow Multiple Ratings”. Because “Title” was already included and the default for non exixsting is “Title”, it was not replicated for the 2 non-existing fields.  SPListItemCollection col = GetListItemColumnByTitle(masterList, "01-STD MIL_some", "1", columnNames, 0); The following call checks if there are any items where “01-STD MIL_some” has the value of “1”. Note that I limited the number of returned items to 1.  SPListItemCollection col = GetListItemColumnByTitle(masterList, "01-STD MIL_some", "1", columnNames, 1); The code also uses the CAMLThisName function that checks for an existence of a field and returns its InternalName. This is yet another useful function that I use again and again.  /// <summary> /// return a fields internal name (CAMLName)  /// or the "default" name that you passed. /// To check existence pass "" or some funny name like "mud in your eye" /// </summary> public static string CAMLThisName(SPList list, string name, string def) {   String CAMLName = def;   SPField fld = GetFieldByName(list, name);   if (fld != null)   {      CAMLName = fld.InternalName;   }   return CAMLName; } That’s all folks?!

    Read the article

  • Managing TFS Workspaces

    - by Enrique Lima
    You are the administrator (or since you may be the one that knows the most about it) and you need to do some cleanup on what is connected and perhaps even cleanup after people that have left the organization and left some code checked out in their workspace. What permissions do I need? You will need to have Administer Workspaces permission to perform the following tasks. The commands. In order to execute the commands, you will need to open a Visual Studio Command Prompt, once there you will be able to use the tf command.  This has a nice set of options, which I will be providing a listing for later on in another post. To list all workspaces registered: tf workspaces /collection:<url to your TPC> <workspace>;<owner> To delete a specific workspace: tf workspace /delete /server:<url to your TPC> <workspace>;<owner> If for any reason a workspace has embedded spaces, then surround that with “” (double quotes).

    Read the article

  • argv Memory Allocation

    - by Joshua Green
    I was wondering if someone could tell me what I am doing wrong that I get this Unhandled Exception error message: 0xC0000005: Access violation reading location 0x0000000c. with a green pointer pointing at my first Prolog code (fid_t): Here is my header file: class UserTaskProlog { public: UserTaskProlog( ArRobot* r ); ~UserTaskProlog( ); protected: int cycles; char* argv[ 1 ]; term_t tf; term_t tx; term_t goal_term; functor_t goal_functor; ArRobot* robot; void logTask( ); }; And here is my main code: UserTaskProlog::UserTaskProlog( ArRobot* r ) : robot( r ), robotTaskFunc( this, &UserTaskProlog::logTask ) { cycles = 0; argv[ 0 ] = "libpl.dll"; argv[ 1 ] = NULL; PL_initialise( 1, argv ); PlCall( "consult( 'myPrologFile.pl' )" ); robot->addSensorInterpTask( "UserTaskProlog", 50, &robotTaskFunc ); } UserTaskProlog::~UserTaskProlog( ) { robot->remSensorInterpTask( &robotTaskFunc ); } void UserTaskProlog::logTask( ) { cycles++; fid_t fid = PL_open_foreign_frame( ); tf = PL_new_term_ref( ); PL_put_integer( tf, 5 ); tx = PL_new_term_ref( ); goal_term = PL_new_term_ref( ); goal_functor = PL_new_functor( PL_new_atom( "factorial" ), 2 ); PL_cons_functor( goal_term, goal_functor, tf, tx ); int fact; if ( PL_call( goal_term, NULL ) ) { PL_get_integer( tx, &fact ); cout << fact << endl; } PL_discard_foreign_frame( fid ); } int main( int argc, char** argv ) { ArRobot robot; ArArgumentParser argParser( &argc, argv ); UserTaskProlog talk( &robot ); } Thank you,

    Read the article

  • mtl, transformers, monads-fd, monadLib, and the paradox of choice

    - by yairchu
    Hackage has several packages for monad transformers: mtl: Monad transformer library transformers: Concrete functor and monad transformers monads-fd: Monad classes, using functional dependencies monads-tf: Monad classes, using type families monadLib: A collection of monad transformers. mtl-tf: Monad transformer library using type families mmtl: Modular Monad transformer library mtlx: Monad transformer library with type indexes, providing 'free' copies. compose-trans: Composable monad transformers (and maybe I missed some) Which one shall we use? mtl is the one in the Haskell Platform, but I keep hearing on reddit that it's uncool. But what's bad about choice anyway, isn't it just a good thing? Well, I saw how for example the authors of data-accessor had to make all these to cater to just the popular choices: data-accessor-monadLib library: Accessor functions for monadLib's monads data-accessor-monads-fd library: Use Accessor to access state in monads-fd State monad class data-accessor-monads-tf library: Use Accessor to access state in monads-tf State monad type family data-accessor-mtl library: Use Accessor to access state in mtl State monad class data-accessor-transformers library: Use Accessor to access state in transformers State monad I imagine that if this goes on and for example several competing Arrow packages evolve, we might see something like: spoonklink-arrows-transformers, spoonklink-arrows-monadLib, spoonklink-tfArrows-transformers, spoonklink-tfArrows-monadLib, ... And then I worry that if spoonklink gets forked, Hackage will run out of disk space. :) Questions: Why are there so many monad transformer packages? Why is mtl [considered] uncool? What are the key differences? Most of these seemingly competing packages were written by Andy Gill and are maintained by Ross Paterson. Does this mean that these packages are not competing but rather work together in some way? And do Andy and Ross consider any of their own packages as obsolete? Which one should me and you use?

    Read the article

  • Is there a way to do this with basic JS DOM?

    - by Thomas
    I need to apply/remove to an input field according to a user's selection in a separate drop down form - but I can't figure out how to target the input's class. I need to add/remove the 'pageRequired' class from this input: <input type="text" title="Company Required" name="customfields-tf-2-tf" class="inputclass pageRequired textInput" id="customfields-tf-2-tf" /> When the user selects one of two options from a drop down field. For example: <select class="dropdown" name="customfields-s-1-s" id="customfields-s-1-s" > <option value="Owner"<?php if(in_array("Owner",$temp_values)) { ?> selected='selected'<?php } ?>> Owner</option> <option value="Broker"<?php if(in_array("Broker",$temp_values)) { ?> selected='selected'<?php } ?>> Broker</option> </select> If the user selects broker than I want to add the pageRequired class to the first input field and remove it if the user selects Owner.

    Read the article

  • How to keep track of call statistics? C++

    - by tf.rz
    I'm working on a project that delivers statistics to the user. I created a class called Dog, And it has several functions. Speak, woof, run, fetch, etc. I want to have a function that spits out how many times each function has been called. I'm also interested in the constructor calls and destructor calls as well. I have a header file which defines all the functions, then a separate .cc file that implements them. My question is, is there a way to keep track of how many times each function is called? I have a function called print that will fetch the "statistics" and then output them to standard output. I was considering using static integers as part of the class itself, declaring several integers to keep track of those things. I know the compiler will create a copy of the integer and initialize it to a minimum value, and then I'll increment the integers in the .cc functions. I also thought about having static integers as a global variable in the .cc. Which way is easier? Or is there a better way to do this? Any help is greatly appreciated!

    Read the article

  • iphone keyboard won't appear

    - by d_CFO
    I can click on the field, and it momentarily turns blue, but those events plus makeFirstResponder together do not cause the keyboard to show on a UITextField. Plain vanilla code follows; I include it so others can discern what is NOT there and therefore what, presumably, with solve the problem. I put in leading spaces to format this question more like code, but the parser seems to have stripped them, thus leaving left-justified code. Sorry! UITextFieldDelete, check: @interface RevenueViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> { UILabel *sgmntdControlLabel; UISegmentedControl *sgmntdControl; UITableView *theTableView; } @property(nonatomic,retain) UISegmentedControl *sgmntdControl; @property(nonatomic,retain) UILabel *sgmntdControlLabel; Delegate and source, check. -(void)loadView; // code CGRect frameTable = CGRectMake(10,0,300,260); theTableView = [[UITableView alloc] initWithFrame:frameTable style:UITableViewStyleGrouped]; [theTableView setDelegate:self]; [theTableView setDataSource:self]; // code [self.view addSubview:theTableView]; [super viewDidLoad]; } Insert UITextField to cell, check. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger sectionNmbr = [indexPath section]; NSInteger rowNmbr = [indexPath row]; NSLog(@"cellForRowAtIndexPath=%d, %d",sectionNmbr,rowNmbr); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. switch (sectionNmbr) { case 0: if (rowNmbr == 0) { cell.tag = 1; cell.textLabel.text = @"Label for sctn 0, row 0"; UITextField *tf = [[UITextField alloc] init]; tf.keyboardType = UIKeyboardTypeNumberPad; tf.returnKeyType = UIReturnKeyDone; tf.delegate = self; [cell.contentView addSubview:tf]; } if (rowNmbr == 1) { cell.tag = 2; cell.textLabel.text = @"Label for sctn 0, row 1"; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; } break; } } Successfully end up where we want to be (?), no check, (and no keyboard!): - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"didSelectRowAtIndexPath"); switch (indexPath.section) { case 0: NSLog(@" section=0, rowNmbr=%d",indexPath.row); switch (indexPath.row) { case 0: UITableViewCell *cellSelected = [tableView cellForRowAtIndexPath: indexPath]; UITextField *textField = [[cellSelected.contentView subviews] objectAtIndex: 0]; [ textField setEnabled: YES ]; [textField becomeFirstResponder]; // here is where keyboard will appear? [tableView deselectRowAtIndexPath: indexPath animated: NO]; break; case 1: // code break; default: break; } break; case 1: // code break; default: // handle otherwise un-handled exception break; } } Thank you for your insights!

    Read the article

  • Python Memory leak - Solved, but still puzzled

    - by disappearedng
    Dear everyone, I have successfully debugged my own memory leak problems. However, I have noticed some very strange occurence. for fid, fv in freqDic.iteritems(): outf.write(fid+"\t") #ID for i, term in enumerate(domain): #Vector tfidf = self.tf(term, fv) * self.idf( term, docFreqDic) if i == len(domain) - 1: outf.write("%f\n" % tfidf) else: outf.write("%f\t" % tfidf) outf.flush() print "Memory increased by", int(self.memory_mon.usage()) - startMemory outf.close() def tf(self, term, freqVector): total = freqVector[TOTAL] if total == 0: return 0 if term not in freqVector: ## When you don't have these lines memory leaks occurs return 0 ## return float(freqVector[term]) / freqVector[TOTAL] def idf(self, term, docFrequencyPerTerm): if term not in docFrequencyPerTerm: return 0 return math.log( float(docFrequencyPerTerm[TOTAL])/docFrequencyPerTerm[term]) Basically let me describe my problem: 1) I am doing tfidf calculations 2) I traced that the source of memory leaks is coming from defaultdict. 3) I am using the memory_mon from http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python 4) The reason for my memory leaks is as follows: a) in self.tf, if the lines: if term not in freqVector: return 0 are not added that will cause the memory leak. (I verified this myself using memory_mon and noticed a sharp increase in memory that kept on increasing) The solution to my problem was 1) since fv is a defaultdict, any reference to it that are not found in fv will create an entry. Over a very large domain, this will cause memory leaks. I decided to use dict instead of default dict and the memory problem did go away. My only puzzle is: since fv is created in "for fid, fv in freqDic.iteritems():" shouldn't fv be destroyed at the end of every for loop? I tried putting gc.collect() at the end of the for loop but gc was not able to collect everything (returns 0). Yes, the hypothesis is right, but the memory should stay fairly consistent with ever for loop if for loops do destroy all temp variables. This is what it looks like with that two line in self.tf: Memory increased by 12 Memory increased by 948 Memory increased by 28 Memory increased by 36 Memory increased by 36 Memory increased by 32 Memory increased by 28 Memory increased by 32 Memory increased by 32 Memory increased by 32 Memory increased by 40 Memory increased by 32 Memory increased by 32 Memory increased by 28 and without the the two line: Memory increased by 1652 Memory increased by 3576 Memory increased by 4220 Memory increased by 5760 Memory increased by 7296 Memory increased by 8840 Memory increased by 10456 Memory increased by 12824 Memory increased by 13460 Memory increased by 15000 Memory increased by 17448 Memory increased by 18084 Memory increased by 19628 Memory increased by 22080 Memory increased by 22708 Memory increased by 24248 Memory increased by 26704 Memory increased by 27332 Memory increased by 28864 Memory increased by 30404 Memory increased by 32856 Memory increased by 33552 Memory increased by 35024 Memory increased by 36564 Memory increased by 39016 Memory increased by 39924 Memory increased by 42104 Memory increased by 42724 Memory increased by 44268 Memory increased by 46720 Memory increased by 47352 Memory increased by 48952 Memory increased by 50428 Memory increased by 51964 Memory increased by 53508 Memory increased by 55960 Memory increased by 56584 Memory increased by 58404 Memory increased by 59668 Memory increased by 61208 Memory increased by 62744 Memory increased by 64400 I look forward to your answer

    Read the article

  • Active Directory validate service account and user accounts

    - by Padur
    Hello folks I have an issue here, I guess you all know what is AD service account and why it is used for, if not please see the below description ? SSL-Explorer requires a dedicated Active Directory account to use for authenticating AD users. This account serves as a link to your Active Directory database. If the Service Account is not found on your AD database then the SSL-Explorer service will not start. Well I have Active Directory service account details and user submitted login/password details.In the code below I validated service account by giving MEMBER_GRPUP and adminPassword and I check whether the user exists in Active Directory by submitting samaaccountname but my question here is how do I validate the password submitted for that user? I am not sure how to do this, I appreciate if anybody has any suggestions on this. Thanks for your time. public boolean validateUserFromActiveDirectory(String userId) { final String MEMBER_GROUP = "CN=asdadasd,OU=asdasdasd Accounts,OU=adasdas,OU=asdasdas,DC=asdasdas,DC=asdasdas,DC=adasdasd,DC=asdasdasd"; String employeeNumber = ""; final String LDAP_INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory"; final String LDAP_URL = "ldap://xx-ssssssss.eee.eee.eeeee.eeeee:636"; final String MY_ATTRS[] = { "employeeNumber" }; String adminPassword = "somepassword"; String securityProtocol = "ssl"; boolean isValidUser = false; try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_INIT_CTX); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.REFERRAL, "follow"); env.put(Context.SECURITY_PRINCIPAL, MEMBER_GROUP); env.put(Context.SECURITY_CREDENTIALS, adminPassword); env.put(Context.SECURITY_PROTOCOL, securityProtocol); //C:\Documents and Settings\yourusername\Local Settings\Temp File tf = File.createTempFile("adentTruststore", ".jks"); tf.deleteOnExit(); byte buffer[] = new byte[0x1000]; ClassLoader cl = JNDI.class.getClassLoader(); InputStream in = cl.getResourceAsStream( "someTruststore.jks"); FileOutputStream out = new FileOutputStream(tf); int cnt; while ((cnt = in.read(buffer)) != -1) out.write(buffer, 0, cnt); in.close(); out.close(); System.setProperty("javax.net.ssl.trustStore", tf .getAbsolutePath()); DirContext context = new InitialLdapContext(env, null); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration results = context.search( "XX=ent,XX=abc,XX=aaaaa,XX=aaaa", "(sAMAccountName=" + userId + ")", searchControls); if (results != null && results.hasMore()) { //some logic } } } catch (Exception e) { e.printStackTrace(); } return isValidUser; }

    Read the article

  • Distinguishing between failure and end of file in read loop

    - by celtschk
    The idiomatic loop to read from an istream is while (thestream >> value) { // do something with value } Now this loop has one problem: It will not distinguish if the loop terminated due to end of file, or due to an error. For example, take the following test program: #include <iostream> #include <sstream> void readbools(std::istream& is) { bool b; while (is >> b) { std::cout << (b ? "T" : "F"); } std::cout << " - " << is.good() << is.eof() << is.fail() << is.bad() << "\n"; } void testread(std::string s) { std::istringstream is(s); is >> std::boolalpha; readbools(is); } int main() { testread("true false"); testread("true false tr"); } The first call to testread contains two valid bools, and therefore is not an error. The second call ends with a third, incomplete bool, and therefore is an error. Nevertheless, the behaviour of both is the same. In the first case, reading the boolean value fails because there is none, while in the second case it fails because it is incomplete, and in both cases EOF is hit. Indeed, the program above outputs twice the same line: TF - 0110 TF - 0110 To solve this problem, I thought of the following solution: while (thestream >> std::ws && !thestream.eof() && thestream >> value) { // do something with value } The idea is to detect regular EOF before actually trying to extract the value. Because there might be whitespace at the end of the file (which would not be an error, but cause read of the last item to not hit EOF), I first discard any whitespace (which cannot fail) and then test for EOF. Only if I'm not at the end of file, I try to read the value. For my example program, it indeed seems to work, and I get TF - 0100 TF - 0110 So in the first case (correct input), fail() returns false. Now my question: Is this solution guaranteed to work, or was I just (un-)lucky that it happened to give the desired result? Also: Is there a simpler (or, if my solution is wrong, a correct) way to get the desired result?

    Read the article

  • asp.net how to add TemplateField programmatically for about 10 dropdownlist...

    - by dotnet-practitioner
    This is my third time asking this question. I am not getting good answers regarding this. I wish I could get some help but I will keep asking this question because its a good question and SO experts should not ignore this... So I have about 10 dropdownlist controls that I add manually in the DetailsView control manually like follows. I should be able to add this programmatically. Please help and do not ignore... <asp:DetailsView ID="dvProfile" runat="server" AutoGenerateRows="False" DataKeyNames="memberid" DataSourceID="SqlDataSource1" OnPreRender = "_onprerender" Height="50px" onm="" Width="125px"> <Fields> <asp:TemplateField HeaderText="Your Gender"> <EditItemTemplate> <asp:DropDownList ID="ddlGender" runat="server" DataSourceid="ddlDAGender" DataTextField="Gender" DataValueField="GenderID" SelectedValue='<%#Bind("GenderID") %>' > </asp:DropDownList> </EditItemTemplate> <ItemTemplate > <asp:Label Runat="server" Text='<%# Bind("Gender") %>' ID="lblGender"></asp:Label> </ItemTemplate> so on and so forth... <asp:CommandField ShowEditButton="True" ShowInsertButton="True" /> </Fields> </asp:DetailsView> ======================================================= Added on 5/3/09 This is what I have so far and I still can not add the drop down list programmatically. private void PopulateItemTemplate(string luControl) { SqlDataSource ds = new SqlDataSource(); ds = (SqlDataSource)FindControl("ddlDAGender"); DataView dvw = new DataView(); DataSourceSelectArguments args = new DataSourceSelectArguments(); dvw = (DataView)ds.Select(args); DataTable dt = dvw.ToTable(); DetailsView dv = (DetailsView)LoginView2.FindControl("dvProfile"); TemplateField tf = new TemplateField(); tf.HeaderText = "Your Gender"; tf.ItemTemplate = new ProfileItemTemplate("Gender", ListItemType.Item); tf.EditItemTemplate = new ProfileItemTemplate("Gender", ListItemType.EditItem); dv.Fields.Add(tf); } public class ProfileItemTemplate : ITemplate { private string ctlName; ListItemType _lit; private string _strDDLName; private string _strDVField; private string _strDTField; private string _strSelectedID; private DataTable _dt; public ProfileItemTemplate(string strDDLName, string strDVField, string strDTField, DataTable dt ) { _dt = dt; _strDDLName = strDDLName; _strDVField = strDVField; _strDTField = strDTField; } public ProfileItemTemplate(string strDDLName, string strDVField, string strDTField, string strSelectedID, DataTable dt ) { _dt = dt; _strDDLName = strDDLName; _strDVField = strDVField; _strDTField = strDTField; _strSelectedID = strSelectedID; } public ProfileItemTemplate(string ControlName, ListItemType lit) { ctlName = ControlName; _lit = lit; } public void InstantiateIn(Control container) { switch(_lit) { case ListItemType.Item : Label lbl = new Label(); lbl.DataBinding += new EventHandler(this.ddl_DataBinding_item); container.Controls.Add(lbl); break; case ListItemType.EditItem : DropDownList ddl = new DropDownList(); ddl.DataBinding += new EventHandler(this.lbl_DataBinding); container.Controls.Add(ddl); break; } } private void ddl_DataBinding_item(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; ddl.ID = _strDDLName; ddl.DataSource = _dt; ddl.DataValueField = _strDVField; ddl.DataTextField = _strDVField; } private void lbl_DataBinding(object sender, EventArgs e) { Label lbl = (Label)sender; lbl.ID = "lblGender"; DropDownList ddl = (DropDownList)sender; ddl.ID = _strDDLName; ddl.DataSource = _dt; ddl.DataValueField = _strDVField; ddl.DataTextField = _strDTField; for (int i = 0; i < _dt.Rows.Count; i++) { if (_strSelectedID == _dt.Rows[i][_strDVField].ToString()) { ddl.SelectedIndex = i; } } lbl.Text = ddl.SelectedValue; } } Please help me....

    Read the article

  • Intel fait durer le suspens sur Sandy Bridge en délivrant les informations au compte-gouttes sur la

    Intel fait durer le suspens sur Sandy Bridge En délivrant les informations au compte-gouttes sur la future micro-architecture de ses processeurs Sandy Bridge est le successeur de Nehalem, la micro-architecture utilisée par Intel pour ses processeurs. Bien qu'on en sache encore assez peu sur cette nouvelle technologie, elle fait d'ores et déjà couler beaucoup d'encre. La stratégie de communication d'Intel, qui délivre les informations au compte-gouttes, n'y est certainement pas pour rien. Lors des derniers Intel Developer Forum (IDF) qui vient de s'achever, David Perlmutter - Executive Vice President Intel Architecture Group - a néanmoins laissé filtrer quelques indices :

    Read the article

  • Intel : concours de développement et SDK pour le lancement français de l'AppUp Center, sa nouvelle galerie d'applications

    Participez au lancement de l'Intel AppUp Developer Program en France Intel sort un SDK et organise un concours pour sa nouvelle galerie d'applications Au cours de la deuxième journée de sa conférence dédiée aux développeurs à San Francisco (l'IDF), le 15 septembre dernier, Intel a inauguré officiellement l'AppUp Center, sa boutique d'applications en ligne. Une boutique qui diffusera des applications gratuites ou payantes adaptées aussi bien aux netbooks (en termes de taille d'écran et de mobili...

    Read the article

  • Intel : concours de développement et SDK pour le lancement français de l'AppUp Center, sa nouvelle galerie d'applications

    Participez au lancement de l'Intel AppUp Developer Program en France Intel sort un SDK et organise un concours pour sa nouvelle galerie d'applications Au cours de la deuxième journée de sa conférence dédiée aux développeurs à San Francisco (l'IDF), le 15 septembre dernier, Intel a inauguré officiellement l'AppUp Center, sa boutique d'applications en ligne. Une boutique qui diffusera des applications gratuites ou payantes adaptées aussi bien aux netbooks (en termes de taille d'écran et de mobili...

    Read the article

  • MinGW tar compression problem

    - by Shiftbit
    I am unable to get the Mingw tar to work with compress files. It does not filter through the proper compression utility. However, tar will work if I manually uncompress the file first. I have tried in both the MSYS shell and Windows cmd. Has anyone had this problem or is it a MinGW bug? For example, this does not work: C:\Users\home\Desktop>tar -tzf wdiff-0.5.tar.gz tar: Cannot use compressed or remote archives tar: Error is not recoverable: exiting now C:\Users\home\Desktop>tar -t -Zgzip -f wdiff-0.5.tar.gz tar: Cannot use compressed or remote archives tar: Error is not recoverable: exiting now C:\Users\home\Desktop>tar -tf wdiff-0.5.tar.gz tar: Hmm, this doesn't look like a tar archive tar: Skipping to next file header tar: Only read 6732 bytes from archive wdiff-0.5.tar.gz tar: Error is not recoverable: exiting now However, this works: gzip -d wdiff-0.5.tar.gz tar -tf wdiff-0.5.tar

    Read the article

  • Cannot set target directory when extracting an archive using tar

    - by palto
    I'm trying to extract a tar archive to a specific directory. I've tried using -C flag but it doesn't work as expected. Here is the commandline I'm using tar xvf myarchive.tar -C mydirectory/ This gives me a following error: tar: file -C: not present in archive tar: file mydirectory/: not present in archive I've also tried setting the -C flag before the archive file but it just says this: tar xvf -C mydirectory/ myarchive.tar tar: -C: No such file or directory What am I doing wrong? EDIT: tar -tf shows that the tar archive does not have full path names: tar -tf myarchive.tar herareport/ herareport/bin/ ...

    Read the article

  • Launching a file using ACTION_VIEW Intent Action

    - by Sneha
    I have the following code to launch a file : try { path = fileJsonObject.getString("filePath"); if (path.indexOf("/") == 0) { path = path.substring(1, path.length()); } path = root + path; final File fileToOpen = new File(path); if (fileToOpen.exists()) { if (fileToOpen.isFile()) { Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW); myIntent.setData(Uri.parse(path)); final String pathToCheck = new String(path); pathToCheck.toLowerCase(); if (pathToCheck.endsWith(".wav") || pathToCheck.endsWith(".ogg") || pathToCheck.endsWith(".mp3") || pathToCheck.endsWith(".mid") || pathToCheck.endsWith(".midi") || pathToCheck.endsWith(".amr")) { myIntent.setType("audio/*"); } else if (pathToCheck.endsWith(".mpg") || pathToCheck.endsWith(".mpeg") || pathToCheck.endsWith(".3gp") || pathToCheck.endsWith(".mp4")) { myIntent.setType("video/*"); } else if (pathToCheck.endsWith(".jpg") || pathToCheck.endsWith(".jpeg") || pathToCheck.endsWith(".gif") || pathToCheck.endsWith(".png") || pathToCheck.endsWith(".bmp")) { myIntent.setType("image/*"); } else if (pathToCheck.endsWith(".txt") || pathToCheck.endsWith(".csv") || pathToCheck.endsWith(".xml")) { Log.i("txt","Text fileeeeeeeeeeeeeeeeeeeeeeeeee"); myIntent.setType("text/*"); } else if (pathToCheck.endsWith(".gz") || pathToCheck.endsWith(".rar") || pathToCheck.endsWith(".zip")) { myIntent.setType("package/*"); } else if (pathToCheck.endsWith(".apk")) { myIntent.setType("application/vnd.android.package-archive"); } ((Activity) context).startActivityForResult(myIntent, RequestCodes.LAUNCH_FILE_CODE); } else { errUrl = resMsgHandler.errMsgResponse(fileJsonObject, "Incorrect path provided. please give correct path of file"); return errUrl; } } else { errUrl = resMsgHandler.errMsgResponse(fileJsonObject,"Incorrect path provided. please give correct path of file"); return errUrl; } } catch (Exception e) { e.printStackTrace(); Log.i("err","Unable to launch file" + " " + e.getMessage()); errUrl = resMsgHandler.errMsgResponse(fileJsonObject, "Unable to launch file" + " " + e.getMessage()); return errUrl; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); try { if (requestCode == RequestCodes.LAUNCH_FILE_CODE) { if (resultCode == RESULT_CANCELED) { Log.i("err","errrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); String errUrl = responseMsgHandler.errMsgResponse(FileHandler.fileJsonObject, "Unable to launch file"); mWebView.loadUrl(errUrl); } else if (resultCode == RESULT_OK) { String successUrl = responseMsgHandler.launchfileResponse(FileHandler.fileJsonObject); mWebView.loadUrl(successUrl); } Amd the result ctrl is at "if (resultCode == RESULT_CANCELED)". So how to successfully launch this? May be in short i am doing this: final File fileToOpen = new File(path); if (fileToOpen.exists()) { if (fileToOpen.isFile()) { Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW); myIntent.setData(Uri.parse(path)); if (pathToCheck.endsWith(".txt") || pathToCheck.endsWith(".csv") || pathToCheck.endsWith(".xml")) { Log.i("txt","Text fileeeeeeeeeeeeeeeeeeeeeeeeee"); myIntent.setType("text/*"); startActivityForResult(myIntent, RequestCodes.LAUNCH_FILE_CODE); and @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodes.LAUNCH_FILE_CODE) { if (resultCode == RESULT_CANCELED) { Log.i ("err","errrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); String errUrl = responseMsgHandler.errMsgResponse(FileHandler.fileJsonObject, "Unable to launch file"); mWebView.loadUrl(errUrl); } else if (resultCode == RESULT_OK) { String successUrl = responseMsgHandler.launchfileResponse(FileHandler.fileJsonObject); mWebView.loadUrl(successUrl); } My err log: 04-04 10:53:57.077: ERROR/AndroidRuntime(6861): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tf.thinkdroid.sstablet/com.tf.thinkdroid.write.editor.WriteEditorActivity}: java.lang.NullPointerException 04-04 10:53:57.077: ERROR/AndroidRuntime(6861): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 04-04 10:53:57.077: ERROR/AndroidRuntime(6861): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) ..... 04-04 10:53:57.077: ERROR/AndroidRuntime(6861): Caused by: java.lang.NullPointerException 04-04 10:53:57.077: ERROR/AndroidRuntime(6861): at com.tf.thinkdroid.common.app.TFActivity.storeDataToFileIfNecessary(Unknown Source) 04-04 10:53:57.077: ERROR/AndroidRuntime(6861): at com.tf.thinkdroid.common.app.TFActivity.onPostCreate(Unknown Source) ... Thanks Sneha

    Read the article

  • Do you have to recreate workspaces after upgrading a TFS 2008 server to TFS 2010?

    - by Clara Oscura
    I am just reposting this thread from a MSDN forum since it seems to be unavailable. It was very useful when I was having trouble with my folder mappings after migrating to TFS 2010. Question: I opened VS2008 and connected it to the upgraded 2010 TFS server.  Upon clicking any of our Team Projects in source control explorer I get "Team Foundation Error - The workspace MYWORKSPACE;DOMAIN\MYUsername already exists on computer MYPCNAME." Answer: The same local paths on your machine are mapped to 2 different workspaces, one on the preupgrade server and one on the postupgrade server.  It's not safe to have multiple workspaces on different servers mapped to the same local paths b/c you could pend some changes while connected to one server, and the other server would have no idea what you did.  You should either delete your conflicting workspaces from one of the servers (if you don't need them on both), or test the new TFS instance from a new workspace (on different machine). If you want to test an existing production workspace on both servers, then yes, you will have to mess around with the workspace cache. You don’t have to delete the entire cache, you just need to run "tf workspaces /remove:* /server:<serverurl>" to clear the cached workspaces from a server (the command won't delete the workspaces), and possibly "tf workspaces /server:<server>" to refresh the workspace cache for a given server.  You will also have to do back up and restore the workspace before switching servers or your local files could be inconsistent. From the “Microsoft Visual Studio Team Foundation Server 2010 Beta 1” forum (not available anymore?) Technorati Tags: TFS 2010,TFS Workspaces,Team System,Team Foundation Server 2010

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >