Search Results

Search found 3437 results on 138 pages for 'append'.

Page 17/138 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • How to convert datatable to json string using json.net?

    - by Pandiya Chendur
    How to convert datatable to json using json.net? Any suggestion... I ve downloaded the necessary binaries... Which class should i use to get the conversion of my datatable to json? Thus far used this method to get json string by passing my datatable... public string GetJSONString(DataTable table) { StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes for (int i = 0; i < table.Columns.Count; i++) { headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i); } headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last , StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space sb.Append("{\""); sb.Append(table.TableName); sb.Append("\" : ["); for (int i = 0; i < table.Rows.Count; i++) { string tempStr = headStrBuilder.ToString(); sb.Append("{"); for (int j = 0; j < table.Columns.Count; j++) { table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", ""); tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString()); } sb.Append(tempStr + "},"); } sb.Remove(sb.Length - 1, 1); // trim last , sb.Append("]}"); return sb.ToString(); } Now i thought of using json.net but dont know where to get started....

    Read the article

  • How to handle this string in json?

    - by Pandiya Chendur
    I am storing a multiline textbox value in my db table... When i converted this value to json it gives me an error Error: unterminated string literal... My sample data was , I am fetching the row to my datatable and then converting it to json, public string GetJSONString(DataTable table) { StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); for (int i = 0; i < table.Columns.Count; i++) { headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i); } headStrBuilder.Remove(headStrBuilder.Length - 1, 1); StringBuilder sb = new StringBuilder(table.Rows.Count * 5); sb.Append("{\""); sb.Append(table.TableName); sb.Append("\" : ["); for (int i = 0; i < table.Rows.Count; i++) { string tempStr = headStrBuilder.ToString(); sb.Append("{"); for (int j = 0; j < table.Columns.Count; j++) { table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", ""); tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString()); } sb.Append(tempStr + "},"); } sb.Remove(sb.Length - 1, 1); // trim last , sb.Append("]}"); return sb.ToString(); } The above method doen't seem to handle newline character... Any suggestion...

    Read the article

  • Web application creation in IIS7 via MS.Web.Admin

    - by Jon Ownbey
    I am attempting to create seperate workflow instances as applications in IIS7 using the Microsoft.Web.Administration dll. When it attempts to add the Application to the Site ApplicationsCollection I get a COM error: "Invalid application path\r\n" using (ServerManager manager = new ServerManager()) { var site = manager.Sites.Where(x => x.Name == Properties.Settings.Default.WorkflowWebsiteName).Single(); StringBuilder stringBuilder = new StringBuilder() .Append(m_workflowDefinition.AccountId) .Append("/") .Append(m_workflowDefinition.WorkflowDefinitionId) .Append("/") .Append(m_workflowDefinition.Version) .Append("/"); string virtualPath = stringBuilder.ToString(); string physicalPath = Properties.Settings.Default.ApplicationPoolString + virtualPath.Replace("/", "\\"); if (!Directory.Exists(physicalPath)) Directory.CreateDirectory(physicalPath); //Create the workflow service definition file using (StreamWriter writer = new StreamWriter(Path.Combine(physicalPath, m_workflowDefinition.WorkflowName + WORKFLOW_FILE_EXTENSION))) { writer.Write(m_workflowDefinition.Definition); } //Copy dependencies string dependencyPath = m_workflowDefinition.DependenciesPath; CopyAll(new DirectoryInfo(dependencyPath), new DirectoryInfo(physicalPath)); //Create a new IIS application for the workflow var apps = site.Applications.Where(x => x.Path == virtualPath); if (apps.Count() > 0) { site.Applications.Remove(apps.Single()); } Application app = site.Applications.Add(virtualPath, physicalPath); app.ApplicationPoolName = "Workflow AppPool"; app.EnabledProtocols = PROTOCOLS; manager.CommitChanges(); } The value assigned to virtualPath is like: "something/something/something" and for physicalPath it is "c:\inetpub\wwwroot\Workflow\something\something\something". Any ideas? Any help is greatly appreciated.

    Read the article

  • How can I combine several Expressions into a fast method?

    - by chillitom
    Suppose I have the following expressions: Expression<Action<T, StringBuilder>> expr1 = (t, sb) => sb.Append(t.Name); Expression<Action<T, StringBuilder>> expr2 = (t, sb) => sb.Append(", "); Expression<Action<T, StringBuilder>> expr3 = (t, sb) => sb.Append(t.Description); I'd like to be able to compile these into a method/delegate equivalent to the following: void Method(T t, StringBuilder sb) { sb.Append(t.Name); sb.Append(", "); sb.Append(t.Description); } What is the best way to approach this? I'd like it to perform well, ideally with performance equivalent to the above method. UPDATE So, whilst it appears that there is no way to do this directly in C#3 is there a way to convert an expression to IL so that I can use it with System.Reflection.Emit?

    Read the article

  • Python TypeError: an integer is required

    - by kartiku
    import scipy,array def try_read_file(): def line_reader(lines): for l in lines: i = l.find('#') if i != -1: l = l[:i] l = l.strip() if l: yield l def column_counter(): inputer = (line.split() for line in line_reader(file('/home/kartik/Downloads/yahoo_dataset/set1.train.txt'.strip()))) loopexit = 0 for line in inputer: feature_tokens = (token.split(':') for token in line[6:]) feature_ids = array.array('I') for t in feature_tokens: feature_ids.append(int (t[0])) tmpLength = feature_ids[-1] print feature_ids loopexit = loopexit + 1 if loopexit > 0: break return tmpLength def line_counter(): inputer = (line.split() for line in line_reader(file('/home/kartik/Downloads/yahoo_dataset/set1.train.txt'.strip()))) noOfRows = 0 for line in inputer: noOfRows = noOfRows + 1 return noOfRows inputer = (line.split() for line in line_reader(file('/home/kartik/Downloads/yahoo_dataset/set1.train.txt'.strip()))) feature_id_list = [] feature_value_list = [] relevance_list = [] noOfRows = line_counter() noOfCols = column_counter() print noOfRows print noOfCols # line 52 #Create the feature array feature_array = scipy.zeros((noOfRows,noOfCols), float) rowCounter = 1; for line in inputer: feature_tokens = (token.split(':') for token in line[6:]) feature_ids = array.array('I') feature_values = array.array('f') for t in feature_tokens: feature_ids.append(int(t[0])) if (t[0]!=colCounter): feature_array[rowCounter,colCounter] = 0 else: feature_array[rowCounter,colCounter] = t[1] feature_values.append(float(t[1])) colCounter = colCounter + 1; label = float(line[0]) assert(line[1].startswith('qid:')) query_id = int(line[1][4:]) feature_id_list.append(feature_ids) feature_value_list.append(feature_values) relevance_list.append(label) rowCounter = rowCounter + 1; return feature_array Error: Traceback (most recent call last): File "<pyshell#97>", line 1, in <module> try_read_file() File "/home/kartik/Python/prelim_read.py", line 52, in try_read_file print noOfCols TypeError: an integer is required What is the problem, i couldn't figure it out? I tried to debug it, but it doesnt really go inside those methods. It gives me an address in place of those variables.

    Read the article

  • Clustering on WebLogic exception on Failover

    - by Markos Fragkakis
    Hi all, I deploy an application on a WebLogic 10.3.2 cluster with two nodes, and a load balancer in front of the cluster. I have set the <core:init distributable="true" debug="true" /> My Session and Conversation classes implement Serializable. I start using the application being served by the first node. The console shows that the session replication is working. <Jun 17, 2010 11:43:50 AM EEST> <Info> <Cluster> <BEA-000128> <Updating 5903057688359791237S:xxx.yyy.gr:[7002,7002,-1,-1,-1,-1,-1]:xxx.yyy.gr:7002,xxx.yyy.gr:7002:prs_domain:PRS_Server_2 in the cluster.> <Jun 17, 2010 11:43:50 AM EEST> <Info> <Cluster> <BEA-000128> <Updating 5903057688359791237S:xxx.yyy.gr:[7002,7002,-1,-1,-1,-1,-1]:xxx.yyy.gr:7002,xxx.yyy.gr:7002:prs_domain:PRS_Server_2 in the cluster.> When I shutdown the first node from the Administration console, I get this in the other node: <Jun 17, 2010 11:23:46 AM EEST> <Error> <Kernel> <BEA-000802> <ExecuteRequest failed java.lang.NullPointerException. java.lang.NullPointerException at org.jboss.seam.intercept.JavaBeanInterceptor.callPostActivate(JavaBeanInterceptor.java:165) at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:73) at com.myproj.beans.SortingFilteringBean_$$_javassist_seam_2.sessionDidActivate(SortingFilteringBean_$$_javassist_seam_2.java) at weblogic.servlet.internal.session.SessionData.notifyActivated(SessionData.java:2258) at weblogic.servlet.internal.session.SessionData.notifyActivated(SessionData.java:2222) at weblogic.servlet.internal.session.ReplicatedSessionData.becomePrimary(ReplicatedSessionData.java:231) at weblogic.cluster.replication.WrappedRO.changeStatus(WrappedRO.java:142) at weblogic.cluster.replication.WrappedRO.ensureStatus(WrappedRO.java:129) at weblogic.cluster.replication.LocalSecondarySelector$ChangeSecondaryInfo.run(LocalSecondarySelector.java:542) at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201) at weblogic.work.ExecuteThread.run(ExecuteThread.java:173) > What am I doing wrong? This is the SortingFilteringBean: import java.util.HashMap; import java.util.LinkedHashMap; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import com.myproj.model.crud.Filtering; import com.myproj.model.crud.Sorting; import com.myproj.model.crud.SortingOrder; /** * Managed bean aggregating the sorting and filtering values for all the * application's lists. A light-weight bean to always keep in the session with * minimum impact. */ @Name("sortingFilteringBean") @Scope(ScopeType.SESSION) public class SortingFilteringBean extends BaseManagedBean { private static final long serialVersionUID = 1L; private Sorting applicantProductListSorting; private Filtering applicantProductListFiltering; private Sorting homePageSorting; private Filtering homePageFiltering; /** * Creates a new instance of SortingFilteringBean. */ public SortingFilteringBean() { // ********************** // Applicant Product List // ********************** // Sorting LinkedHashMap<String, SortingOrder> applicantProductListSortingValues = new LinkedHashMap<String, SortingOrder>(); applicantProductListSortingValues.put("applicantName", SortingOrder.ASCENDING); applicantProductListSortingValues.put("applicantEmail", SortingOrder.ASCENDING); applicantProductListSortingValues.put("productName", SortingOrder.ASCENDING); applicantProductListSortingValues.put("productEmail", SortingOrder.ASCENDING); applicantProductListSorting = new Sorting( applicantProductListSortingValues); // Filtering HashMap<String, String> applicantProductListFilteringValues = new HashMap<String, String>(); applicantProductListFilteringValues.put("applicantName", ""); applicantProductListFilteringValues.put("applicantEmail", ""); applicantProductListFilteringValues.put("productName", ""); applicantProductListFilteringValues.put("productEmail", ""); applicantProductListFiltering = new Filtering( applicantProductListFilteringValues); // ********* // Home page // ********* // Sorting LinkedHashMap<String, SortingOrder> homePageSortingValues = new LinkedHashMap<String, SortingOrder>(); homePageSortingValues.put("productName", SortingOrder.ASCENDING); homePageSortingValues.put("productId", SortingOrder.ASCENDING); homePageSortingValues.put("productAtcCode", SortingOrder.UNSORTED); homePageSortingValues.put("productEmaNumber", SortingOrder.UNSORTED); homePageSortingValues.put("productOrphan", SortingOrder.UNSORTED); homePageSortingValues.put("productRap", SortingOrder.UNSORTED); homePageSortingValues.put("productCorap", SortingOrder.UNSORTED); homePageSortingValues.put("applicationTypeDescription", SortingOrder.ASCENDING); homePageSortingValues.put("applicationId", SortingOrder.ASCENDING); homePageSortingValues .put("applicationEmaNumber", SortingOrder.UNSORTED); homePageSortingValues .put("piVersionImportDate", SortingOrder.ASCENDING); homePageSortingValues.put("piVersionId", SortingOrder.ASCENDING); homePageSorting = new Sorting(homePageSortingValues); // Filtering HashMap<String, String> homePageFilteringValues = new HashMap<String, String>(); homePageFilteringValues.put("productName", ""); homePageFilteringValues.put("productAtcCode", ""); homePageFilteringValues.put("productEmaNumber", ""); homePageFilteringValues.put("applicationTypeId", ""); homePageFilteringValues.put("applicationEmaNumber", ""); homePageFilteringValues.put("piVersionImportDate", ""); homePageFiltering = new Filtering(homePageFilteringValues); } /** * @return the applicantProductListFiltering */ public Filtering getApplicantProductListFiltering() { return applicantProductListFiltering; } /** * @param applicantProductListFiltering * the applicantProductListFiltering to set */ public void setApplicantProductListFiltering( Filtering applicantProductListFiltering) { this.applicantProductListFiltering = applicantProductListFiltering; } /** * @return the applicantProductListSorting */ public Sorting getApplicantProductListSorting() { return applicantProductListSorting; } /** * @param applicantProductListSorting * the applicantProductListSorting to set */ public void setApplicantProductListSorting( Sorting applicantProductListSorting) { this.applicantProductListSorting = applicantProductListSorting; } /** * @return the homePageSorting */ public Sorting getHomePageSorting() { return homePageSorting; } /** * @param homePageSorting * the homePageSorting to set */ public void setHomePageSorting(Sorting homePageSorting) { this.homePageSorting = homePageSorting; } /** * @return the homePageFiltering */ public Filtering getHomePageFiltering() { return homePageFiltering; } /** * @param homePageFiltering * the homePageFiltering to set */ public void setHomePageFiltering(Filtering homePageFiltering) { this.homePageFiltering = homePageFiltering; } /** * For convenience to view in the Seam Debug page. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(""); sb.append("\n\n"); sb.append("applicantProductListSorting"); sb.append(applicantProductListSorting); sb.append("\n\n"); sb.append("applicantProductListFiltering"); sb.append(applicantProductListFiltering); sb.append("\n\n"); sb.append("homePageSorting"); sb.append(homePageSorting); sb.append("\n\n"); sb.append("homePageFiltering"); sb.append(homePageFiltering); return sb.toString(); } } And this is the BaseManagedBean, inheriting the AbstractMutable. import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage.Severity; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.ArrayUtils; import org.jboss.seam.core.AbstractMutable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.myproj.common.exceptions.WebException; import com.myproj.common.util.FileUtils; import com.myproj.common.util.StringUtils; import com.myproj.web.messages.Messages; public abstract class BaseManagedBean extends AbstractMutable { private static final Logger logger = LoggerFactory .getLogger(BaseManagedBean.class); private FacesContext facesContext; /** * Set a message to be displayed for a specific component. * * @param resourceBundle * the resource bundle where the message appears. Either base or * id may be used. * @param summaryResourceId * the id of the resource to be used as summary. For the detail * of the element, the element to be used will be the same with * the suffix {@code _detail}. * @param parameters * the parameters, in case the string is parameterizable * @param severity * the severity of the message * @param componentId * the component id for which the message is destined. Note that * an appropriate JSF {@code <h:message for="myComponentId">} tag * is required for the to appear, or alternatively a {@code * <h:messages>} tag. */ protected void setMessage(String resourceBundle, String summaryResourceId, List<Object> parameters, Severity severity, String componentId, Messages messages) { FacesContext context = getFacesContext(); FacesMessage message = messages.getMessage(resourceBundle, summaryResourceId, parameters); if (severity != null) { message.setSeverity(severity); } context.addMessage(componentId, message); } /** * Copies a byte array to the response output stream with the appropriate * MIME type and content disposition. The response output stream is closed * after this method. * * @param response * the HTTP response * @param bytes * the data * @param filename * the suggested file name for the client * @param mimeType * the MIME type; will be overridden if the filename suggests a * different MIME type * @throws IllegalArgumentException * if the data array is <code>null</code>/empty or both filename * and mimeType are <code>null</code>/empty */ protected void printBytesToResponse(HttpServletResponse response, byte[] bytes, String filename, String mimeType) throws WebException, IllegalArgumentException { if (response.isCommitted()) { throw new WebException("HTTP response is already committed"); } if (ArrayUtils.isEmpty(bytes)) { throw new IllegalArgumentException("Data buffer is empty"); } if (StringUtils.isEmpty(filename) && StringUtils.isEmpty(mimeType)) { throw new IllegalArgumentException( "Filename and MIME type are both null/empty"); } // Set content type (mime type) String calculatedMimeType = FileUtils.getMimeType(filename); // not among the known ones String newMimeType = mimeType; if (calculatedMimeType == null) { // given mime type passed if (mimeType == null) { // none available put default mime-type newMimeType = "application/download"; } else { if ("application/octet-stream".equals(mimeType)) { // small modification newMimeType = "application/download"; } } } else { // calculated mime type has precedence over given mime type newMimeType = calculatedMimeType; } response.setContentType(newMimeType); // Set content disposition and other headers String contentDisposition = "attachment;filename=\"" + filename + "\""; response.setHeader("Content-Disposition", contentDisposition); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "max-age=30"); response.setHeader("Pragma", "public"); // Set content length response.setContentLength(bytes.length); // Write bytes to response OutputStream out = null; try { out = response.getOutputStream(); out.write(bytes); } catch (IOException e) { throw new WebException("Error writing data to HTTP response", e); } finally { try { out.close(); } catch (Exception e) { logger.error("Error closing HTTP stream", e); } } } /** * Retrieve a session-scoped managed bean. * * @param sessionBeanName * the session-scoped managed bean name * @return the session-scoped managed bean */ protected Object getSessionBean(String sessionBeanName) { Object sessionScopedBean = FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get(sessionBeanName); if (sessionScopedBean == null) { throw new IllegalArgumentException("No such object in Session"); } else { return sessionScopedBean; } } /** * Set a session-scoped managed bean * * @param sessionBeanName * the session-scoped managed bean name * @return the session-scoped managed bean */ protected boolean setSessionBean(String sessionBeanName, Object sessionBean) { Object sessionScopedBean = FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get(sessionBeanName); if (sessionScopedBean == null) { FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put(sessionBeanName, sessionBean); } else { throw new IllegalArgumentException( "This session-scoped bean was already initialized"); } return true; } /** * For testing (enables mock of FacesContext) * * @return the faces context */ public FacesContext getFacesContext() { if (facesContext == null) { return FacesContext.getCurrentInstance(); } return facesContext; } /** * For testing (enables mocking of FacesContext). * * @param aFacesContext * a - possibly mock - faces context. */ public void setFacesContext(FacesContext aFacesContext) { this.facesContext = aFacesContext; } }

    Read the article

  • Checking for Repeated Strings in 2d list

    - by Zach Santiago
    i have a program where i have a list of names and classes. i have the list in alphabetical order. now im trying to check if names repeat, add the classes to one single name. im trying to write some code like go through names if name is already in list, add the class to the one name. so an example would be, instead of having 'Anita ','phys 1443', and 'Anita','IE 3312' i would just have 'Anita','PHYS 1443','IE 3312'. How would i go about doing this in a logival way, WITHOUT using any sort of built in functions? i tried comparing indexe's like if list[i][0] == list[i+1][0], append list[i+1][1] to an emptylist. while that almost worked, it would screw up at some points along the way. here is my attempt size = len(c) i = 0 c = [['Anita', 'PHYS 1443'], ['Anita', 'IE 3312'], ['Beihuang', 'PHYS 1443'], ['Chiao-Lin', 'MATH 1426'], ['Chiao-Lin', 'IE 3312'], ['Christopher', 'CSE 1310'], ['Dylan', 'CSE 1320'], ['Edmund', 'PHYS 1443'], ['Ian', 'IE 3301'], ['Ian', 'CSE 1320'], ['Ian', 'PHYS 1443'], ['Isis', 'PHYS 1443'], ['Jonathan', 'MATH 2325'], ['Krishna', 'MATH 2325'], ['Michael', 'IE 3301'], ['Nang', 'MATH 2325'], ['Ram', 'CSE 1320'], ['Taesu', 'CSE 1320'], ["Tre'Shaun", 'IE 3312'], ["Tre'Shaun", 'MATH 2325'], ["Tre'Shaun", 'CSE 1310']] ## Check if any names repeat d.append(c[0][0]) while i < size - 1 : if c[i][0] == c[i+1][0] : d.append(c[i][1]) d.append(c[i+1][1]) else : d.append(c[i+1][0]) d.append(c[i+1][1]) i = i + 1 print d output was. ['Anita', 'PHYS 1443', 'IE 3312', 'Beihuang', 'PHYS 1443', 'Chiao-Lin', 'MATH 1426', 'MATH 1426', 'IE 3312', 'Christopher', 'CSE 1310', 'Dylan', 'CSE 1320', 'Edmund', 'PHYS 1443', 'Ian', 'IE 3301', 'IE 3301', 'CSE 1320', 'CSE 1320', 'PHYS 1443', 'Isis', 'PHYS 1443', 'Jonathan', 'MATH 2325', 'Krishna', 'MATH 2325', 'Michael', 'IE 3301', 'Nang', 'MATH 2325', 'Ram', 'CSE 1320', 'Taesu', 'CSE 1320', "Tre'Shaun", 'IE 3312', 'IE 3312', 'MATH 2325', 'MATH 2325', 'CSE 1310']

    Read the article

  • Problem: Sorting for GridView/ObjectDataSource changes depending on page

    - by user148298
    I have a GridView tied to an ObjectDataSource using paging. The paging works fine, except that the sort order changes depending on which page of the results is being viewed. This causes items to reappear on subsequent pages among other issues. I traced the problem to my DAL, which reads a page at a time and then sorts it. Obviously the sorting is going to change as the result set size changes. Is there an improvement to this algorithm. I would like to use a datareader if possible: [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)] public static WordsCollection LoadForCriteria(string sqlCriteria, int maximumRows, int startRowIndex, string sortExpression) { //DEFAULT SORT EXPRESSION if (string.IsNullOrEmpty(sortExpression)) sortExpression = "OrderBy"; //CREATE THE DYNAMIC SQL TO LOAD OBJECT StringBuilder selectQuery = new StringBuilder(); selectQuery.Append("SELECT"); if (maximumRows > 0) selectQuery.Append(" TOP " + (startRowIndex + maximumRows).ToString()); selectQuery.Append(" " + Words.GetColumnNames(string.Empty)); selectQuery.Append(" FROM sw_Words"); string whereClause = string.IsNullOrEmpty(sqlCriteria) ? string.Empty : " WHERE " + sqlCriteria; selectQuery.Append(whereClause); selectQuery.Append(" ORDER BY " + sortExpression); Database database = Token.Instance.Database; DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()); //EXECUTE THE COMMAND WordsCollection results = new WordsCollection(); int thisIndex = 0; int rowCount = 0; using (IDataReader dr = database.ExecuteReader(selectCommand)) { while (dr.Read() && ((maximumRows < 1) || (rowCount < maximumRows))) { if (thisIndex >= startRowIndex) { Words varWords = new Words(); Words.LoadDataReader(varWords, dr); results.Add(varWords); rowCount++; } thisIndex++; } dr.Close(); } return results; }

    Read the article

  • Using JQuery with dynamically added controls (MVC)

    - by Mario
    I have a set of radio buttons that are dynamically generated (via JSON call): StringBuilder sbEligAll = new StringBuilder(); sbEligAll.Append("<div id='currentselectiondepartment'>"); sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radCurrent' value='0' /><label for='radCurrent'>Current</label>"); sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radFuture' value='1' /><label for='radFuture'>Future</label>"); sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radCurrentAll' value='2' /><label for='radCurrentAll'>Current All</label>"); sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radFutureAll' value='3' /><label for='radFutureAll'>Future All</label>"); sbEligAll.Append("</div>"); Then: return Json(new { TableList = sbElig.ToString() }, JsonRequestBehavior.AllowGet); Is there a way to get jQuery to be able to interact with these? For example: $("input[name=selectalldepartment]").change(function() { var str = $('input[name=selectalldepartment]:checked').val(); $(".radiolist[value='" + str + "']").attr("checked", true); }); I've tried everything I know how to do, but the jQuery just doesnt fire. (I've added alerts to the jQuery code to see if it actually gets called, and it does not). Any thoughts?! Thanks!

    Read the article

  • Facebook app request in java not working

    - by Arpit Solanki
    I am trying to send a facebook app request to a user through the code below.But it gives an IO Exception and HTTP status code 400 in running.I dont see a any app request being sent to a user on running this. StringBuffer buffer = new StringBuffer(); buffer.append("access_token").append('=').append(this.app_access_token); buffer.append('&').append("message=").append("sent an app request!"); String content = buffer.toString(); try{ URLConnection connection = new URL("https://graph.facebook.com/me/apprequests").openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length",Integer.toString(content.length())); DataOutputStream outs = new DataOutputStream(connection.getOutputStream()); outs.writeBytes(content); outs.flush(); outs.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch(Exception e){ System.out.println(e); }

    Read the article

  • Exporting WPF DataGrid to a text file in a nice looking format. Text file must be easy to read.

    - by Andrew
    Hi, Is there a simple way to export a WPF DataGrid to a text file and a .csv file? I've done some searching and can't see that there is a simple DataGrid method to do so. I have got something working (barely) by making use of the ItemsSource of the DataGrid. In my case, this is an array of structs. I do something with StreamWriters and StringBuilders (details available) and basically have: StringBuilder destination = new StringBuilder(); destination.Append(row.CreationDate); destination.Append(seperator); // seperator is '\t' or ',' for csv file destination.Append(row.ProcId); destination.Append(seperator); destination.Append(row.PartNumber); destination.Append(seperator); I do this for each struct in the array (in a loop). This works fine. The problem is that it's not easy to read the text file. The data can be of different lengths within the same column. I'd like to see something like: 2007-03-03 234238423823 823829923 2007-03-03 66 99 And of course, I get something like: 2007-03-03 234238423823 823829923 2007-03-03 66 99 It's not surprising giving that I'm using Tab delimiters, but I hope to do better. It certainly is easy to read in the DataGrid! I could of course have some logic to pad short values with spaces, but that seems quite messy. I thought there might be a better way. I also have a feeling that this is a common problem and one that has probably been solved before (hopefully within the .NET classes themselves). Thanks.

    Read the article

  • Pygame Sprite/Font rendering issues

    - by Grimless
    Hey guys. Here's my problem: I have a game class that maintains a HUD overlay that has a bunch of elements, including header and footer background sprites. Everything was working fine until I added a 1024x128 footer sprite. Now two of my text labels will not render, despite the fact that they DO exist in my Group and self.elements array. Is there something I'm missing? When I take out the footerHUDImage line, all of the labels render correctly and everything works fine. When I add the footerHUDImage, two of the labels (the first two) no longer render and the third only sometimes renders. HELP PLEASE! Here is the code: class AoWHUD (object): def __init__(self, screen, delegate, dataSource): self.delegate = delegate self.dataSource = dataSource self.elements = [] headerHudImage = KJRImage("HUDBackground.png") self.elements.append(headerHudImage) headerHudImage.userInteractionEnabled = True footerHUDImage = KJRImage("ControlsBackground.png") self.elements.append(footerHUDImage) footerHUDImage.rect.bottom = screen.get_rect().height footerHUDImage.userInteractionEnabled = True lumberMessage = "Lumber: " + str(self.dataSource.lumber) lumberLabel = KJRLabel(lumberMessage, size = 48, color = (240, 200, 10)) lumberLabel.rect.topleft = (_kSpacingMultiple * 0, 0) self.elements.append(lumberLabel) stoneMessage = "Stone: " + str(self.dataSource.stone) stoneLabel = KJRLabel(stoneMessage, size = 48, color = (240, 200, 10)) stoneLabel.rect.topleft = (_kSpacingMultiple * 1, 0) self.elements.append(stoneLabel) metalMessage = "Metal: " + str(self.dataSource.metal) metalLabel = KJRLabel(metalMessage, size = 48, color = (240, 200, 10)) metalLabel.rect.topleft = (_kSpacingMultiple * 2, 0) self.elements.append(metalLabel) foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food) foodLabel = KJRLabel(foodMessage, size = 48, color = (240, 200, 10)) foodLabel.rect.topleft = (_kSpacingMultiple * 3, 0) self.elements.append(foodLabel) self.selectionSprites = {32 : pygame.image.load("Selected32.png").convert_alpha(), 64 : pygame.image.load("Selected64.png")} self._sprites_ = pygame.sprite.Group() for e in self.elements: self._sprites_.add(e) print self.elements def draw(self, screen): if self.dataSource.resourcesChanged: lumberMessage = "Lumber: " + str(self.dataSource.lumber) stoneMessage = "Stone: " + str(self.dataSource.stone) metalMessage = "Metal: " + str(self.dataSource.metal) foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food) self.elements[2].setText(lumberMessage) self.elements[2].rect.topleft = (_kSpacingMultiple * 0, 0) self.elements[3].setText(stoneMessage) self.elements[3].rect.topleft = (_kSpacingMultiple * 1, 0) self.elements[4].setText(metalMessage) self.elements[4].rect.topleft = (_kSpacingMultiple * 2, 0) self.elements[5].setText(foodMessage) self.elements[5].rect.topleft = (_kSpacingMultiple * 3, 0) self.dataSource.resourcesChanged = False self._sprites_.draw(screen) if self.delegate.selectedUnit: theSelectionSprite = self.selectionSprites[self.delegate.selectedUnit.rect.width] screen.blit(theSelectionSprite, self.delegate.selectedUnit.rect)

    Read the article

  • Printing a DataTable to textbox/textfile in .NET

    - by neodymium
    Is there a predefined or "easy" method of writing a datatable to a text file or TextBox Control (With monospace font) such as DataTable.Print(): Column1| Column2| --------|--------| v1| v2| v3| v4| v5| v6| Edit Here's an initial version (vb.net) - in case anyone is interested or wants to build their own: Public Function BuildTable(ByVal dt As DataTable) As String Dim result As New StringBuilder Dim widths As New List(Of Integer) Const ColumnSeparator As Char = "|"c Const HeadingUnderline As Char = "-"c ' determine width of each column based on widest of either column heading or values in that column For Each col As DataColumn In dt.Columns Dim colWidth As Integer = Integer.MinValue For Each row As DataRow In dt.Rows Dim len As Integer = row(col.ColumnName).ToString.Length If len > colWidth Then colWidth = len End If Next widths.Add(CInt(IIf(colWidth < col.ColumnName.Length, col.ColumnName.Length + 1, colWidth + 1))) Next ' write column headers For Each col As DataColumn In dt.Columns result.Append(col.ColumnName.PadLeft(widths(col.Ordinal))) result.Append(ColumnSeparator) Next result.AppendLine() ' write heading underline For Each col As DataColumn In dt.Columns Dim horizontal As String = New String(HeadingUnderline, widths(col.Ordinal)) result.Append(horizontal.PadLeft(widths(col.Ordinal))) result.Append(ColumnSeparator) Next result.AppendLine() ' write each row For Each row As DataRow In dt.Rows For Each col As DataColumn In dt.Columns result.Append(row(col.ColumnName).ToString.PadLeft(widths(col.Ordinal))) result.Append(ColumnSeparator) Next result.AppendLine() Next Return result.ToString() End Function

    Read the article

  • inserting unique date into txt document

    - by durian
    I'm trying this script to insert only a unique date into a text file, but it isn't working properly: $log_file_name = "logfile.txt"; $log_file_path = "log_files/$id/$log_file_name"; if(file_exists($log_file_path)){ $not = "not"; $todaydate = date('d,m,Y'); $today = "$todaydate;"; $strlength = strlen($today); $file_contents = file_get_contents($log_file_path); $file_contents_arry = explode(";",$file_contents); if(!in_array($todaytodaydate,$file_contents_arry)){ $append = fopen($log_file_path, 'a'); $write = fwrite($append,$today); //writes our string to our file. $close = fclose($append); //closes our file } else { $append = fopen($log_file_path, 'a'); $write = fwrite($append,$not); //writes our string to our file. $close = fclose($append); //closes our file } } else{ mkdir("log_files/$id", 0700); $todaydate = date('d,m,Y'); $today = "$todaydate;"; $strlength = strlen($today); $create = fopen($log_file_path, "w"); $write = fwrite($create, $today, $strlength); //writes our string to our file. $close = fclose($create); //closes our file } The problem is with the if else statement where it should be written if it's already in the array.

    Read the article

  • Manually wiring up unobtrusive jquery validation client-side without Model/Data Annotations, MVC3

    - by cmorganmcp
    After searching and experimenting for 2 days I relent. What I'd like to do is manually wire up injected html with jquery validation. I'm getting a simple string array back from the server and creating a select with the strings as options. The static fields on the form are validating fine. I've been trying the following: var dates = $("<select id='ShiftDate' data-val='true' data-val-required='Please select a date'>"); dates.append("<option value=''>-Select a Date-</option>"); for (var i = 0; i < data.length; i++) { dates.append("<option value='" + data[i] + "'>" + data[i] + "</option>"); } $("fieldset", addShift).append($("<p>").append("<label for='ShiftDate'>Shift Date</label>\r").append(dates).append("<span class='field-validation-valid' data-valmsg-for='ShiftDate' data-valmsg-replace='true'></span>")); // I tried the code below as well instead of adding the data-val attributes and span manually with no luck dates.rules("add", { required: true, messages: { required: "Please select a date" } }); // Thought this would do it when I came across several posts but it didn't $.validator.unobtrusive.parse(dates.closest("form")); I know I could create a view model ,decorate it with a required attribute, create a SelectList server-side and send that, but it's more of a "how would I do this" situation now. Can anyone shed light on why the above code wouldn't work as I expect? -chad

    Read the article

  • Working with Java using methods and arrays [closed]

    - by jordan
    Hi i'm a newb at java and for one of my labs I have to create a instant messenger client with these requirements: add buddyList instance variable add IMClient constructor to create ArrayList addBuddy method removeBuddy method findBuddy method printBuddyList method what's the best way to go about this? so far I have this: public class IMClient { private String userId; // User id private String password; // Password private int status; // Status code for user: 1 - Online, 2 - Off-line, 3 - Away public IMClient(String userId, String password, int status) { super(); this.userId = userId; this.password = password; this.status = status; } // Returns true if password as a parameter matches password instance variable. public boolean checkPassword(String password) { return this.password.equals(password); } public String toString() { StringBuffer buf = new StringBuffer(100); buf.append(" User id: "); buf.append(userId); buf.append(" Password: "); buf.append(password); buf.append(" Status: "); buf.append(status); return buf.toString(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public static void main(String[] args) { } }

    Read the article

  • Hiding Url for asp.net page

    - by user204588
    Hello, I'm creating an html page that is posted to another page for processing. I don't want users to see the weird URL they are redirected to and I was using FRAMES but I can't figure out how to add my HTML page dynamically because I need the variables and either add frames or try another way to accomplish this. So, based on how I'm creating the page below, how can I hide the URL and add something that I want. Here is how I'm creating the page. StringBuilder sb = new StringBuilder(); sb.Append("<html><head></head>"); sb.Append("<body onload=\"document.frmLaunch.submit();\">"); sb.Append("<form name=\"frmLaunch\" action=\"" + variableTargetURL + "\" method=\"post\">"); sb.Append("<input type=hidden name=\"testVariable\" value=\"" + variableTest + "\">"); sb.Append("</form>"); sb.Append("</body></html>"); HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Write(sb.ToString()); response.End();

    Read the article

  • get the right id of a record in database in each click on the edit button

    - by kawtousse
    hi every one, i am facing a big problem right now. I have a html table in each row i have a button called edit allowing user to relod the form with parameter that he has selected. for this i define a hidden type to get the id of the record in database to access to various colonne and to refresh the form with those parameters. My challenge now is how to get the right id in every click on the edit button to let me after to get the right record and to update it in the data base. I am preceeding like the following: retour.append("<td style=border-right:#FFF bordercolor=#FFFFFF>"); retour.append("<input type=\"hidden\" id=\"id_"+nomTab+"_"+compteur+"\" value=\""+object.getIdDailyTimeSheet()+"\" name=\"hd"+compteur+"\" />"); retour.append("<button id=edit name=edit type=button onClick= editarow()>"); retour.append("<img src=edit.gif />"); retour.append("</button>"); retour.append("</td>"); i realise the submit in javascript and i want to get the idDailyTimesheet everyonce the user click the submit button. thanks for help.

    Read the article

  • Disable button after submit

    - by Chris Philpotts
    I'm trying to disable a button when a user submits a payment form and the code to post the form is causing a double post in firefox. This problem does not occur when the code is removed, and does not occur in any browser other than firefox. Any idea how to prevent the double post here? System.Text.StringBuilder sb = new StringBuilder(); sb.Append("if (typeof(Page_ClientValidate) == 'function') { "); sb.Append("if (Page_ClientValidate() == false) { return false; }} "); sb.Append("this.value = 'Please wait...';"); sb.Append("this.disabled = true;"); sb.Append(Page.GetPostBackEventReference(btnSubmit )); sb.Append(";"); btnSubmit.Attributes.Add("onclick", sb.ToString()); it's the sb.Append(Page.GetPostBackEventReference(btnSubmit )) line that's causing the issue Thanks EDIT: Here's the c# of the button: <asp:Button ID="cmdSubmit" runat="server" Text="Submit" /> here's the html This code posts twice (and disables the submit button and verifies input): <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; }} this.value = 'Please wait...';this.disabled = true;document.getElementById('ctl00_MainContent_cmdBack').disabled = true;__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" /> This code posts twice (but doesn’t disable the submit button): <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" /> This code posts once (but doesn’t verify the user input and doesn’t disable the submit button): <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="ctl00_MainContent_cmdSubmit" /> This code posts once (but doesn’t disable submit button): <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$cmdSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_MainContent_cmdSubmit" /> This code doesn’t post at all: <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="this.disabled = true;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$cmdSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_MainContent_cmdSubmit" /> Obviously it’s the disabling of the submit button that’s posing the problem. Do you have any ideas how we can disable the submit to avoid multiple clicking?

    Read the article

  • xml appending issue - in ie, chrome browsers

    - by 3gwebtrain
    Hi, i am using this coding for my xml information to append in to html. As well it works fine. but in the ie7,ie8 as well chrome browser it's not propelry. This code work9ing well with firefox,opera, safari.. i unable to find, what is the mistake i made this.. any one help me please? $(function(){ var thisPage; var parentPage; $('ul.left-navi li a').each(function(){ $('ul.left-navi li a').removeClass('current'); var pathname = (window.location.pathname.match(/[^\/]+$/)[0]); var currentPage = $(this).attr('href'); var pathArr = new Array(); pathArr = pathname.split("."); var file = pathArr[pathArr.length - 2]; thisPage = file; if(currentPage==pathname){ $(this).addClass("active"); } }) $.get('career-utility.xml',function(myData){ var receivedData = myData; var myXml = $(myData).find(thisPage); parentPage = thisPage; var overviewTitle = myXml.find('overview').attr('title'); var description = myXml.find('discription').text(); var mainsublinkTitle = myXml.find('mainsublink').attr('title'); var thisTitle = myXml.find("intro").attr('title'); var thisIntro = myXml.find("introinfo").text(); $('<h3>'+overviewTitle+'</h3>').appendTo('.overViewInfo'); $('<p>'+description+'</p>').appendTo('.overViewInfo'); var sublinks = myXml.find('mainsublink').children('sublink'); $('#intro h3').append(thisTitle); $('#intro').append(thisIntro); sublinks.each(function(numsub){ var newSubLink = $(this); var sublinkPage = $(this).attr('pageto'); var linkInfo = $(this).text(); $('ul.career-link').append('<li><a href="'+sublinkPage+'">'+linkInfo+'</a></li>'); }) // alert('thisTitle : '+thisTitle+'thisIntro :'+thisIntro); $(myXml).find('listgroup').each(function(index){ var count = index; var listGroup = $(this); var listGroupTitle = $(this).attr('title'); var shortNote = $(this).attr('shortnote'); var subLink = $(this).find('sublist'); var firstList = $(this).find('list'); $('.grouplist').append('<div class="list-group"><h3>'+listGroupTitle+'</h3><ul class="level-one level' + count + '"></ul></div>'); firstList.each(function(listnum) { $(this).wrapInner('<li>') .find('sublistgroup').wrapInner('<ul>').children().unwrap() .find('sublist').wrapInner('<li>').children().unwrap(); // Append content of 'list' node $('ul.level'+count).append($(this).children()); }); }); }); })

    Read the article

  • Javascript table construction bug using JQuery in Firefox on Mac OSX

    - by Poita_
    I'm using some code to build up tables using JQuery, but in Firefox 3.5.3 on Mac OSX, the table cells all appear on separate lines by themselves, instead of in their respective rows. Chrome 5.0.342.7 beta on OSX correctly produces the table, as does Safari 4.0.5. Here is a minimal reproduction case: <html> <body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var b = $('body'); b.append("<table>"); for (var i = 0; i < 3; ++i) { b.append("<tr>"); for (var j = 0; j < 3; ++j) b.append("<td>x</td>"); b.append("</tr>"); } b.append("</table>"); }); </script> </body> </html> In Chrome and Safari, I get this correct output: x x x x x x x x x but Firefox produces: x x x x x x x x x Note that if I manually create that exact table without using Javascript (i.e. direct into the HTML) then the table appears correctly in Firefox. Also, if I change the JS to append then entire table in one call then it also works -- the only time it doesn't work is if you append it part-by-part as I have done before. My question is: is this to be expected, or should I report this as a bug to Firefox? I'm pretty sure this is a Firefox bug, but I'm a bit of a newbie to JS and web development in general, so perhaps there's something I'm missing? P.S. obviously there are easy ways to get around this -- that's not my concern. See above.

    Read the article

  • BlackBerry - Facebook extended permissions

    - by Max Gontar
    Hi! I've just found a great sample of Facebook Connect on Blackberry by Eki Y. Baskoro, The following is a short HOWTO on using Facebook Connect on Blackberry. I created a simple Facade encapsulating the Facebook REST API as well as added 'rough' MVC approach for screen navigation. I have tested on JDE 4.5 using 8320 simulator. This is still work in progress and all work is GPLed. It works great for reading stuff. NB Don't forget to get Facebook App Key and set it in TestBB class. But now I want to post something on my wall. So I've add new method to FacebookFacade class using Stream.publish API: /*** * Publishes message to the stream. * @param message - message that will appear on the facebook stream * @param targetId - The ID of the user, Page, group, or event where * you are publishing the content. */ public void streamPublish(String message, String targetId) { Hashtable arguments = new Hashtable(); arguments.put("method", "stream.publish"); arguments.put("message", message); arguments.put("target_id", targetId); try { JSONObject result = new JSONObject( int new JSONTokener(sendRequest(arguments))); int errorCode = result.getInt("error_code"); if (errorCode != 0) System.out.println("Error Code: "+errorCode); } catch (Exception e) { System.out.println(e); } } /*** * Publishes message on current user wall. * @param message - message that will appear on the facebook stream */ public void postOnTheWall(String message) { String targetId = String.valueOf(getLoggedInUserId()); streamPublish(message, targetId); } This will return Error code 200, "The user hasn't authorized the application to perform this action" First I thought it's related with Facebook - Application Settings - Additional Permissions - Publish recent activity (one line stories) to my wall but even checked, no difference... Then I've found this post explains that issue related with extended permissions. This in turn should be fixed by modifying url a little in LoginScreen class : public LoginScreen(FacebookFacade facebookFacade) { this.facebookFacade = facebookFacade; StringBuffer data = new StringBuffer(); data.append("api_key=" + facebookFacade.getApplicationKey()); data.append("&connect_display=popup"); data.append("&v=1.0"); //revomed //data.append("&next=http://www.facebook.com/connect/login_success.html"); //added data.append("&next=http://www.facebook.com/connect/prompt_permissions.php?" + "api_key="+facebookFacade.getApplicationKey()+"&display=popup&v=1.0"+ "&next=http://www.facebook.com/connect/login_success.html?"+ "xxRESULTTOKENxx&fbconnect=true" + "&ext_perm=read_stream,publish_stream,offline_access"); data.append("&cancel_url=http://www.facebook.com/connect/login_failure.html"); data.append("&fbconnect=true"); data.append("&return_session=true"); (new FetchThread("http://m.facebook.com/login.php?" + data.toString())).start(); } Unfortunately it's not working. Still Error Code 200 in return to stream.publish request... Do you have any suggestions how to resolve this? Thank you!

    Read the article

  • Autohotkey: clipboard enhancements don't work in Google Docs word processor

    - by Robert Mark Bram
    Came across this amazing AutoHotkey tip in an earlier question: Clipboard enhancements ; Append to clipboard (cut) ^+x:: clipboardBefore = %clipboard% Send ^x ClipWait, 2 clipboard = %clipboardBefore% %clipboard% return ; Append to clipboard (copy) ^+c:: clipboardBefore = %clipboard% Send ^c ClipWait, 2 clipboard = %clipboardBefore% %clipboard% return Source: most useful autohotkey scripts But the append copy and cut don't seem to work in Google Docs (word processing). Anyone know how they can be fixed? Rob :)

    Read the article

  • add the same qtreewidgetitems into the second column

    - by srinu
    hello i am using the following program to display the qtreewidget. main.cpp include include "qdomsimple.h" include include "qdomsimple.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QStringList filelist; filelist.push_back("C:\department1.xml"); filelist.push_back("C:\department2.xml"); filelist.push_back("C:\department3.xml"); QDOMSimple w(filelist); w.resize(260,200); w.show(); return a.exec(); } qdomsimple.cpp include "qdomsimple.h" include include QDOMSimple::QDOMSimple(QStringList strlst,QWidget *parent) : QWidget(parent) { k=0; // DOM document QDomDocument doc("title"); QStringList headerlabels; headerlabels.push_back("Chemistry"); headerlabels.push_back("Mechanical"); headerlabels.push_back("IT"); m_tree = new QTreeWidget( this ); m_tree->setColumnCount(3); m_tree->setHeaderLabels(headerlabels); QStringList::iterator it; for(it=strlst.begin();it<strlst.end();it++) { QFile file(*it); if ( file.open( QIODevice::ReadOnly | QIODevice::Text )) { // The tree view to be filled with xml data // (m_tree is a class member variable) // Creating the DOM tree doc.setContent( &file ); file.close(); // Root of the document QDomElement root = doc.documentElement(); // Taking the first child node of the root QDomNode child = root.firstChild(); // Setting the root as the header of the tree //QTreeWidgetItem* header = new QTreeWidgetItem; //header->setText(k,root.nodeName()); //m_tree->setHeaderItem(header); // Parse until the end of document while (!child.isNull()) { //Convert a DOM node to DOM element QDomElement element = child.toElement(); //Parse only if the node is a really an element if (!element.isNull()) { //Parse the element recursively parseElement( element,0); //Go to the next sibling child = child.nextSiblingElement(); } } //m_tree->setGeometry( QApplication::desktop()->availableGeometry() ); //setGeometry( QApplication::desktop()->availableGeometry() ); } k++; } } void QDOMSimple::parseElement( QDomElement& aElement, QTreeWidgetItem *aParentItem ) { // A map of all attributes of an element QDomNamedNodeMap attrMap = aElement.attributes(); // List all attributes QStringList attrList; for ( int i = 0; i < attrMap.count(); i++ ) { // Attribute name //QString attr = attrMap.item( i ).nodeName(); //attr.append( "-" ); /* Attribute value QString attr; attr.append( attrMap.item( i ).nodeValue() );*/ //attrList.append( attr ); attrList.append(attrMap.item( i).nodeValue()); } QTreeWidgetItem* item; // Create a new view item for elements having child nodes if (aParentItem) { item = new QTreeWidgetItem(aParentItem); } // Create a new view item for elements without child nodes else { item = new QTreeWidgetItem( m_tree ); } //Set tag name and the text QString tagNText; tagNText.append( aElement.tagName() ); //tagNText.append( "------" ); //tagNText.append( aElement.text() ); item->setText(0, tagNText ); // Append attributes to the element node of the tree for ( int i = 0; i < attrList.count(); i++ ) { QTreeWidgetItem* attrItem = new QTreeWidgetItem( item ); attrItem->setText(0, attrList[i] ); } // Repeat the process recursively for child elements QDomElement child = aElement.firstChildElement(); while (!child.isNull()) { parseElement( child, item ); child = child.nextSiblingElement(); } } QDOMSimple::~QDOMSimple() { } for this i got the qtreewidget like this +file1 +file2 +file3 but actual wanted output is +file1 +file2 +file3 i don't know how to do it.Thanks in advance

    Read the article

  • Increasing speed of python code

    - by Curious2learn
    Hi, I have some python code that has many classes. I used cProfile to find that the total time to run the program is 68 seconds. I found that the following function in a class called Buyers takes about 60 seconds of those 68 seconds. I have to run the program about 100 times, so any increase in speed will help. Can you suggest ways to increase the speed by modifying the code? If you need more information that will help, please let me know. def qtyDemanded(self, timePd, priceVector): '''Returns quantity demanded in period timePd. In addition, also updates the list of customers and non-customers. Inputs: timePd and priceVector Output: count of people for whom priceVector[-1] < utility ''' ## Initialize count of customers to zero ## Set self.customers and self.nonCustomers to empty lists price = priceVector[-1] count = 0 self.customers = [] self.nonCustomers = [] for person in self.people: if person.utility >= price: person.customer = 1 self.customers.append(person) else: person.customer = 0 self.nonCustomers.append(person) return len(self.customers) self.people is a list of person objects. Each person has customer and utility as its attributes. EDIT - responsed added ------------------------------------- Thanks so much for the suggestions. Here is the response to some questions and suggestions people have kindly made. I have not tried them all, but will try others and write back later. (1) @amber - the function is accessed 80,000 times. (2) @gnibbler and others - self.people is a list of Person objects in memory. Not connected to a database. (3) @Hugh Bothwell cumtime taken by the original function - 60.8 s (accessed 80000 times) cumtime taken by the new function with local function aliases as suggested - 56.4 s (accessed 80000 times) (4) @rotoglup and @Martin Thomas I have not tried your solutions yet. I need to check the rest of the code to see the places where I use self.customers before I can make the change of not appending the customers to self.customers list. But I will try this and write back. (5) @TryPyPy - thanks for your kind offer to check the code. Let me first read a little on the suggestions you have made to see if those will be feasible to use. EDIT 2 Some suggested that since I am flagging the customers and noncustomers in the self.people, I should try without creating separate lists of self.customers and self.noncustomers using append. Instead, I should loop over the self.people to find the number of customers. I tried the following code and timed both functions below f_w_append and f_wo_append. I did find that the latter takes less time, but it is still 96% of the time taken by the former. That is, it is a very small increase in the speed. @TryPyPy - The following piece of code is complete enough to check the bottleneck function, in case your offer is still there to check it with other compilers. Thanks again to everyone who replied. import numpy class person(object): def __init__(self, util): self.utility = util self.customer = 0 class population(object): def __init__(self, numpeople): self.people = [] self.cus = [] self.noncus = [] numpy.random.seed(1) utils = numpy.random.uniform(0, 300, numpeople) for u in utils: per = person(u) self.people.append(per) popn = population(300) def f_w_append(): '''Function with append''' P = 75 cus = [] noncus = [] for per in popn.people: if per.utility >= P: per.customer = 1 cus.append(per) else: per.customer = 0 noncus.append(per) return len(cus) def f_wo_append(): '''Function without append''' P = 75 for per in popn.people: if per.utility >= P: per.customer = 1 else: per.customer = 0 numcustomers = 0 for per in popn.people: if per.customer == 1: numcustomers += 1 return numcustomers

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >