Search Results

Search found 2136 results on 86 pages for 'dominik str'.

Page 5/86 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Can this code be further optimized??

    - by kaki
    i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code. But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries`

    Read the article

  • Compression Program in C

    - by Delandilon
    I want to compress a series of characters. For example if i type Input : FFFFFBBBBBBBCCBBBAABBGGGGGSSS (27 x 8 bits = 216 bits) Output: F5B7C2B3A2B2G5S3 (14 x 8 bits = 112bits) So far this is what i have, i can count the number of Characters in the Array. But the most important task is to count them in the same sequence. I can't seem to figure that out :( Ive stared doing C just a few weeks back, i have knowledge on Array, pointers, ASCII value but in any case can't seem to count these characters in a sequence. Ive try a bit of everything. This approach is no good but it the closest i came to it. #include <stdio.h> #include <conio.h> int main() { int charcnt=0,dotcnt=0,commacnt=0,blankcnt=0,i, countA, countB; char str[125]; printf("*****String Manipulations*****\n\n"); printf("Enter a string\n\n"); scanf("%[^'\n']s",str); printf("\n\nEntered String is \" %s \" \n",str); for(i=0;str[i]!='\0';i++) { // COUNTING EXCEPTION CHARS if(str[i]==' ') blankcnt++; if(str[i]=='.') dotcnt++; if(str[i]==',') commacnt++; if (str[i]=='A' || str[i]=='a') countA++; if (str[i]=='B' || str[i]=='b') countA++; } //PRINT RESULT OF COUNT charcnt=i; printf("\n\nTotal Characters : %d",charcnt); printf("\nTotal Blanks : %d",blankcnt); printf("\nTotal Full stops : %d",dotcnt); printf("\nTotal Commas : %d\n\n",commacnt); printf("A%d\n", countA); }

    Read the article

  • Ajax, Callback, postback and Sys.WebForms.PageRequestManager.getInstance().add_beginRequest

    - by user338262
    Hi, I have a user control which encapsulates a NumericUpDownExtender. This UserControl implements the interface ICallbackEventHandler, because I want that when a user changes the value of the textbox associated a custom event to be raised in the server. By the other hand each time an async postback is done I shoe a message of loading and disable the whole screen. This works perfect when something is changed in for example an UpdatePanel through this lines of code: Sys.WebForms.PageRequestManager.getInstance().add_beginRequest( function (sender, args) { var modalPopupBehavior = $find('programmaticSavingLoadingModalPopupBehavior'); modalPopupBehavior.show(); } ); The UserControl is placed inside a detailsview which is inside an UpdatePanel in an aspx. When the custom event is raised I want another textbox in the aspx to change its value. So far, When I click on the UpDownExtender, it goes correctly to the server and raises the custom event, and the new value of the textbox is assigned in the server. but it is not changed in the browser. I suspect that the problem is the callback, since I have the same architecture for a UserControl with an AutoCompleteExtender which implement IPostbackEventHandler and it works. Any clues how can I solve this here to make the UpDownNumericExtender user control to work like the AutComplete one? This is the code of the user control and the parent: using System; using System.Web.UI; using System.ComponentModel; using System.Text; namespace Corp.UserControls { [Themeable(true)] public partial class CustomNumericUpDown : CorpNumericUpDown, ICallbackEventHandler { protected void Page_PreRender(object sender, EventArgs e) { if (!Page.IsPostBack) { currentInstanceNumber = CorpAjaxControlToolkitUserControl.getNextInstanceNumber(); } registerControl(this.HFNumericUpDown.ClientID, currentInstanceNumber); string strCallServer = "NumericUpDownCallServer" + currentInstanceNumber.ToString(); // If this function is not written the callback to get the disponibilidadCliente doesn't work if (!Page.ClientScript.IsClientScriptBlockRegistered("ReceiveServerDataNumericUpDown")) { StringBuilder str = new StringBuilder(); str.Append("function ReceiveServerDataNumericUpDown(arg, context) {}").AppendLine(); Page.ClientScript.RegisterClientScriptBlock(typeof(CorpNumericUpDown), "ReceiveServerDataNumericUpDown", str.ToString(), true); } nudeNumericUpDownExtender.BehaviorID = "NumericUpDownEx" + currentInstanceNumber.ToString(); ClientScriptManager cm = Page.ClientScript; String cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerDataNumericUpDown", ""); String callbackScript = "function " + strCallServer + "(arg, context)" + Environment.NewLine + "{" + Environment.NewLine + cbReference + ";" + Environment.NewLine + "}" + Environment.NewLine; cm.RegisterClientScriptBlock(typeof(CustomNumericUpDown), strCallServer, callbackScript, true); base.Page_PreRender(sender,e); } [System.ComponentModel.Browsable(true)] [System.ComponentModel.Bindable(true)] public Int64 Value { get { return (string.IsNullOrEmpty(HFNumericUpDown.Value) ? Int64.Parse("1") : Int64.Parse(HFNumericUpDown.Value)); } set { HFNumericUpDown.Value = value.ToString(); //txtAutoCompleteCliente_AutoCompleteExtender.ContextKey = value.ToString(); // TODO: Change the text of the textbox } } [System.ComponentModel.Browsable(true)] [System.ComponentModel.Bindable(true)] [Description("The text of the numeric up down")] public string Text { get { return txtNumericUpDown.Text; } set { txtNumericUpDown.Text = value; } } public delegate void NumericUpDownChangedHandler(object sender, NumericUpDownChangedArgs e); public event NumericUpDownChangedHandler numericUpDownEvent; [System.ComponentModel.Browsable(true)] [System.ComponentModel.Bindable(true)] [System.ComponentModel.Description("Raised after the number has been increased or decreased")] protected virtual void OnNumericUpDownEvent(object sender, NumericUpDownChangedArgs e) { if (numericUpDownEvent != null) //check to see if anyone has attached to the event numericUpDownEvent(this, e); } #region ICallbackEventHandler Members public string GetCallbackResult() { return "";//throw new NotImplementedException(); } public void RaiseCallbackEvent(string eventArgument) { NumericUpDownChangedArgs nudca = new NumericUpDownChangedArgs(long.Parse(eventArgument)); OnNumericUpDownEvent(this, nudca); } #endregion } /// <summary> /// Class that adds the prestamoList to the event /// </summary> public class NumericUpDownChangedArgs : System.EventArgs { /// <summary> /// The current selected value. /// </summary> public long Value { get; private set; } public NumericUpDownChangedArgs(long value) { Value = value; } } } using System; using System.Collections.Generic; using System.Text; namespace Corp { /// <summary> /// Summary description for CorpAjaxControlToolkitUserControl /// </summary> public class CorpNumericUpDown : CorpAjaxControlToolkitUserControl { private Int16 _currentInstanceNumber; // This variable hold the instanceNumber assignated at first place. public short currentInstanceNumber { get { return _currentInstanceNumber; } set { _currentInstanceNumber = value; } } protected void Page_PreRender(object sender, EventArgs e) { const string strOnChange = "OnChange"; const string strCallServer = "NumericUpDownCallServer"; StringBuilder str = new StringBuilder(); foreach (KeyValuePair<String, Int16> control in controlsToRegister) { str.Append("function ").Append(strOnChange + control.Value).Append("(sender, eventArgs) ").AppendLine(); str.Append("{").AppendLine(); str.Append(" if (sender) {").AppendLine(); str.Append(" var hfield = document.getElementById('").Append(control.Key).Append("');").AppendLine(); str.Append(" if (hfield.value != eventArgs) {").AppendLine(); str.Append(" hfield.value = eventArgs;").AppendLine(); str.Append(" ").Append(strCallServer + control.Value).Append("(eventArgs, eventArgs);").AppendLine(); str.Append(" }").AppendLine(); str.Append(" }").AppendLine(); str.Append("}").AppendLine(); Page.ClientScript.RegisterClientScriptBlock(typeof(CorpNumericUpDown), Guid.NewGuid().ToString(), str.ToString(), true); } str = new StringBuilder(); foreach (KeyValuePair<String, Int16> control in controlsToRegister) { str.Append(" funcsPageLoad[funcsPageLoad.length] = function() { $find('NumericUpDownEx" + control.Value + "').add_currentChanged(").Append(strOnChange + control.Value).Append(");};").AppendLine(); str.Append(" funcsPageUnLoad[funcsPageUnLoad.length] = function() { $find('NumericUpDownEx" + control.Value + "').remove_currentChanged(").Append(strOnChange + control.Value).Append(");};").AppendLine(); } Page.ClientScript.RegisterClientScriptBlock(typeof(CorpNumericUpDown), Guid.NewGuid().ToString(), str.ToString(), true); } } } and to create the loading view I use this: //The beginRequest event is raised before the processing of an asynchronous postback starts and the postback is sent to the server. You can use this event to call custom script to set a request header or to start an animation that notifies the user that the postback is being processed. Sys.WebForms.PageRequestManager.getInstance().add_beginRequest( function (sender, args) { var modalPopupBehavior = $find('programmaticSavingLoadingModalPopupBehavior'); modalPopupBehavior.show(); } ); //The endRequest event is raised after an asynchronous postback is finished and control has been returned to the browser. You can use this event to provide a notification to users or to log errors. Sys.WebForms.PageRequestManager.getInstance().add_endRequest( function (sender, arg) { var modalPopupBehavior = $find('programmaticSavingLoadingModalPopupBehavior'); modalPopupBehavior.hide(); } ); Thanks in advance! Daniel.

    Read the article

  • ahow can I resolve Django Error: str' object has no attribute 'autoescape'?

    - by Angelbit
    Hi have tried to create a inclusion tag on Django but don't work and return str' object has no attribute 'autoescape' this is the code of custom tag: from django import template from quotes.models import Quotes register = template.Library() def show_quote(): quote = Quotes.objects.values('quote', 'author').get(id=0) return {'quote': quote['quote']} register.inclusion_tag('quotes.html')(show_quote) EDIT: Quote class from django.db import models class Quotes(models.Model): quote = models.CharField(max_length=255) author = models.CharField(max_length=100) class Meta: db_table = 'quotes' quotes.html <blockquote id="quotes">{{ quote }}</blockquote>

    Read the article

  • Dual Monitor (Monitor and TV)

    - by umpirsky
    I connected TV to my computer, and trying to set dual display. Whatever resolution I choose for my second display (TV) I get message like this: The selected configuration for displays could not be applied required virtual size does not fit available size: requested=(2704, 1050), minimum=(320, 200), maximum=(1680, 1680) How can I fix this? Also, while I was experimenting system went to deadlock, I restarted and after boot monitor just turns off once system is up. I boot in recovery mode and after several retries fixed it somehow, I don't know how, probably by changing display config from display manager. now I found xorg.conf.new file in my home dir: Section "ServerLayout" Identifier "X.org Configured" Screen 0 "Screen0" 0 0 Screen 1 "Screen1" RightOf "Screen0" Screen 2 "Screen2" RightOf "Screen1" InputDevice "Mouse0" "CorePointer" InputDevice "Keyboard0" "CoreKeyboard" EndSection Section "Files" ModulePath "/usr/lib/xorg/modules" FontPath "/usr/share/fonts/X11/misc" FontPath "/usr/share/fonts/X11/cyrillic" FontPath "/usr/share/fonts/X11/100dpi/:unscaled" FontPath "/usr/share/fonts/X11/75dpi/:unscaled" FontPath "/usr/share/fonts/X11/Type1" FontPath "/usr/share/fonts/X11/100dpi" FontPath "/usr/share/fonts/X11/75dpi" FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType" FontPath "built-ins" EndSection Section "Module" Load "extmod" Load "dbe" Load "glx" Load "dri" Load "dri2" Load "record" EndSection Section "InputDevice" Identifier "Keyboard0" Driver "kbd" EndSection Section "InputDevice" Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/input/mice" Option "ZAxisMapping" "4 5 6 7" EndSection Section "Monitor" Identifier "Monitor0" VendorName "Monitor Vendor" ModelName "Monitor Model" EndSection Section "Monitor" Identifier "Monitor1" VendorName "Monitor Vendor" ModelName "Monitor Model" EndSection Section "Monitor" Identifier "Monitor2" VendorName "Monitor Vendor" ModelName "Monitor Model" EndSection Section "Device" ### Available Driver options are:- ### Values: <i>: integer, <f>: float, <bool>: "True"/"False", ### <string>: "String", <freq>: "<f> Hz/kHz/MHz", ### <percent>: "<f>%" ### [arg]: arg optional #Option "NoAccel" # [<bool>] #Option "SWcursor" # [<bool>] #Option "Dac6Bit" # [<bool>] #Option "Dac8Bit" # [<bool>] #Option "BusType" # [<str>] #Option "CPPIOMode" # [<bool>] #Option "CPusecTimeout" # <i> #Option "AGPMode" # <i> #Option "AGPFastWrite" # [<bool>] #Option "AGPSize" # <i> #Option "GARTSize" # <i> #Option "RingSize" # <i> #Option "BufferSize" # <i> #Option "EnableDepthMoves" # [<bool>] #Option "EnablePageFlip" # [<bool>] #Option "NoBackBuffer" # [<bool>] #Option "DMAForXv" # [<bool>] #Option "FBTexPercent" # <i> #Option "DepthBits" # <i> #Option "PCIAPERSize" # <i> #Option "AccelDFS" # [<bool>] #Option "IgnoreEDID" # [<bool>] #Option "CustomEDID" # [<str>] #Option "DisplayPriority" # [<str>] #Option "PanelSize" # [<str>] #Option "ForceMinDotClock" # <freq> #Option "ColorTiling" # [<bool>] #Option "VideoKey" # <i> #Option "RageTheatreCrystal" # <i> #Option "RageTheatreTunerPort" # <i> #Option "RageTheatreCompositePort" # <i> #Option "RageTheatreSVideoPort" # <i> #Option "TunerType" # <i> #Option "RageTheatreMicrocPath" # <str> #Option "RageTheatreMicrocType" # <str> #Option "ScalerWidth" # <i> #Option "RenderAccel" # [<bool>] #Option "SubPixelOrder" # [<str>] #Option "ClockGating" # [<bool>] #Option "VGAAccess" # [<bool>] #Option "ReverseDDC" # [<bool>] #Option "LVDSProbePLL" # [<bool>] #Option "AccelMethod" # <str> #Option "DRI" # [<bool>] #Option "ConnectorTable" # <str> #Option "DefaultConnectorTable" # [<bool>] #Option "DefaultTMDSPLL" # [<bool>] #Option "TVDACLoadDetect" # [<bool>] #Option "ForceTVOut" # [<bool>] #Option "TVStandard" # <str> #Option "IgnoreLidStatus" # [<bool>] #Option "DefaultTVDACAdj" # [<bool>] #Option "Int10" # [<bool>] #Option "EXAVSync" # [<bool>] #Option "ATOMTVOut" # [<bool>] #Option "R4xxATOM" # [<bool>] #Option "ForceLowPowerMode" # [<bool>] #Option "DynamicPM" # [<bool>] #Option "NewPLL" # [<bool>] #Option "ZaphodHeads" # <str> Identifier "Card0" Driver "radeon" BusID "PCI:2:0:0" EndSection Section "Device" ### Available Driver options are:- ### Values: <i>: integer, <f>: float, <bool>: "True"/"False", ### <string>: "String", <freq>: "<f> Hz/kHz/MHz", ### <percent>: "<f>%" ### [arg]: arg optional #Option "ShadowFB" # [<bool>] #Option "Rotate" # <str> #Option "fbdev" # <str> #Option "debug" # [<bool>] Identifier "Card1" Driver "fbdev" BusID "PCI:2:0:0" EndSection Section "Device" ### Available Driver options are:- ### Values: <i>: integer, <f>: float, <bool>: "True"/"False", ### <string>: "String", <freq>: "<f> Hz/kHz/MHz", ### <percent>: "<f>%" ### [arg]: arg optional #Option "ShadowFB" # [<bool>] #Option "DefaultRefresh" # [<bool>] #Option "ModeSetClearScreen" # [<bool>] Identifier "Card2" Driver "vesa" BusID "PCI:2:0:0" EndSection Section "Screen" Identifier "Screen0" Device "Card0" Monitor "Monitor0" SubSection "Display" Viewport 0 0 Depth 1 EndSubSection SubSection "Display" Viewport 0 0 Depth 4 EndSubSection SubSection "Display" Viewport 0 0 Depth 8 EndSubSection SubSection "Display" Viewport 0 0 Depth 15 EndSubSection SubSection "Display" Viewport 0 0 Depth 16 EndSubSection SubSection "Display" Viewport 0 0 Depth 24 EndSubSection EndSection Section "Screen" Identifier "Screen1" Device "Card1" Monitor "Monitor1" SubSection "Display" Viewport 0 0 Depth 1 EndSubSection SubSection "Display" Viewport 0 0 Depth 4 EndSubSection SubSection "Display" Viewport 0 0 Depth 8 EndSubSection SubSection "Display" Viewport 0 0 Depth 15 EndSubSection SubSection "Display" Viewport 0 0 Depth 16 EndSubSection SubSection "Display" Viewport 0 0 Depth 24 EndSubSection EndSection Section "Screen" Identifier "Screen2" Device "Card2" Monitor "Monitor2" SubSection "Display" Viewport 0 0 Depth 1 EndSubSection SubSection "Display" Viewport 0 0 Depth 4 EndSubSection SubSection "Display" Viewport 0 0 Depth 8 EndSubSection SubSection "Display" Viewport 0 0 Depth 15 EndSubSection SubSection "Display" Viewport 0 0 Depth 16 EndSubSection SubSection "Display" Viewport 0 0 Depth 24 EndSubSection EndSection Can I delete it? Second display (TV) only works when I check Mirror displays option.

    Read the article

  • Displaylink USB show "Logo / Loading" on monitor

    - by Ken Le
    I tried with this problem for 2 years already. LOL, today, I install Ubuntu for I have to resolve it or I will back to stupid Windows 7. First, I have 3 monitors. My graphic card is support dual ( ATI Radeon ), so I have no problem on extend those multi monitor on VGA and DVI. The 3rd monitor is Displaylink USB. After installed everything required, when I reboot, the displaylink monitor show "Ubuntu ...." like logo / loading screen. I go to System Display , Detect monitor, it only show my 1st and 2nd, NO 3RD Displaylink. I can move my mouse between those 1st & 2nd, but the 3rd is only show the Ubuntu Screen. I press Ctrl+Alt+1, then screen switch to Displaylink USB 3RD monitor, but its "Terminal" not a desktop. Then I press Ctrl+Alt+7 , the screen switch back to my 1st, 2nd, and the displaylink 3rd is witch back to Logo / Ubuntu again. This is my /etc/X11/xorg.conf : Section "ServerLayout" Identifier "X.org Configured" Screen 0 "aticonfig-Screen[0]-0" 0 0 Screen 1 "DisplayLinkScreen" Leftof "aticonfig-Screen[0]-0" InputDevice "Mouse0" "CorePointer" InputDevice "Keyboard0" "CoreKeyboard" EndSection Section "Files" ModulePath "/usr/lib/xorg/modules" FontPath "/usr/share/fonts/X11/misc" FontPath "/usr/share/fonts/X11/cyrillic" FontPath "/usr/share/fonts/X11/100dpi/:unscaled" FontPath "/usr/share/fonts/X11/75dpi/:unscaled" FontPath "/usr/share/fonts/X11/Type1" FontPath "/usr/share/fonts/X11/100dpi" FontPath "/usr/share/fonts/X11/75dpi" FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType" FontPath "built-ins" EndSection Section "Module" Load "glx" Load "dri2" Load "dbe" Load "dri" Load "record" Load "extmod" EndSection Section "InputDevice" Identifier "Keyboard0" Driver "kbd" EndSection Section "InputDevice" Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/input/mice" Option "ZAxisMapping" "4 5 6 7" EndSection Section "Monitor" Identifier "aticonfig-Monitor[0]-0" Option "VendorName" "ATI Proprietary Driver" Option "ModelName" "Generic Autodetecting Monitor" Option "DPMS" "true" EndSection Section "Monitor" Identifier "DisplayLinkMonitor" EndSection Section "Monitor" Identifier "0-DFP1" Option "VendorName" "ATI Proprietary Driver" Option "ModelName" "Generic Autodetecting Monitor" Option "DPMS" "true" Option "PreferredMode" "1680x1050" Option "TargetRefresh" "60" Option "Position" "0 0" Option "Rotate" "normal" Option "Disable" "false" EndSection Section "Monitor" Identifier "0-CRT2" Option "VendorName" "ATI Proprietary Driver" Option "ModelName" "Generic Autodetecting Monitor" Option "DPMS" "true" Option "PreferredMode" "1920x1080" Option "TargetRefresh" "60" Option "Position" "1680 0" Option "Rotate" "normal" Option "Disable" "false" EndSection Section "Device" ### Available Driver options are:- ### Values: <i>: integer, <f>: float, <bool>: "True"/"False", ### <string>: "String", <freq>: "<f> Hz/kHz/MHz", ### <percent>: "<f>%" ### [arg]: arg optional #Option "NoAccel" # [<bool>] #Option "SWcursor" # [<bool>] #Option "Dac6Bit" # [<bool>] #Option "Dac8Bit" # [<bool>] #Option "BusType" # [<str>] #Option "CPPIOMode" # [<bool>] #Option "CPusecTimeout" # <i> #Option "AGPMode" # <i> #Option "AGPFastWrite" # [<bool>] #Option "AGPSize" # <i> #Option "GARTSize" # <i> #Option "RingSize" # <i> #Option "BufferSize" # <i> #Option "EnableDepthMoves" # [<bool>] #Option "EnablePageFlip" # [<bool>] #Option "NoBackBuffer" # [<bool>] #Option "DMAForXv" # [<bool>] #Option "FBTexPercent" # <i> #Option "DepthBits" # <i> #Option "PCIAPERSize" # <i> #Option "AccelDFS" # [<bool>] #Option "IgnoreEDID" # [<bool>] #Option "CustomEDID" # [<str>] #Option "DisplayPriority" # [<str>] #Option "PanelSize" # [<str>] #Option "ForceMinDotClock" # <freq> #Option "ColorTiling" # [<bool>] #Option "VideoKey" # <i> #Option "RageTheatreCrystal" # <i> #Option "RageTheatreTunerPort" # <i> #Option "RageTheatreCompositePort" # <i> #Option "RageTheatreSVideoPort" # <i> #Option "TunerType" # <i> #Option "RageTheatreMicrocPath" # <str> #Option "RageTheatreMicrocType" # <str> #Option "ScalerWidth" # <i> #Option "RenderAccel" # [<bool>] #Option "SubPixelOrder" # [<str>] #Option "ClockGating" # [<bool>] #Option "VGAAccess" # [<bool>] #Option "ReverseDDC" # [<bool>] #Option "LVDSProbePLL" # [<bool>] #Option "AccelMethod" # <str> #Option "DRI" # [<bool>] #Option "ConnectorTable" # <str> #Option "DefaultConnectorTable" # [<bool>] #Option "DefaultTMDSPLL" # [<bool>] #Option "TVDACLoadDetect" # [<bool>] #Option "ForceTVOut" # [<bool>] #Option "TVStandard" # <str> #Option "IgnoreLidStatus" # [<bool>] #Option "DefaultTVDACAdj" # [<bool>] #Option "Int10" # [<bool>] #Option "EXAVSync" # [<bool>] #Option "ATOMTVOut" # [<bool>] #Option "R4xxATOM" # [<bool>] #Option "ForceLowPowerMode" # [<bool>] #Option "DynamicPM" # [<bool>] #Option "NewPLL" # [<bool>] #Option "ZaphodHeads" # <str> Identifier "Card0" Driver "radeon" BusID "PCI:5:0:0" EndSection Section "Device" ### Available Driver options are:- ### Values: <i>: integer, <f>: float, <bool>: "True"/"False", ### <string>: "String", <freq>: "<f> Hz/kHz/MHz", ### <percent>: "<f>%" ### [arg]: arg optional #Option "ShadowFB" # [<bool>] #Option "Rotate" # <str> #Option "fbdev" # <str> #Option "debug" # [<bool>] Identifier "Card1" Driver "fbdev" BusID "PCI:5:0:0" EndSection Section "Device" ### Available Driver options are:- ### Values: <i>: integer, <f>: float, <bool>: "True"/"False", ### <string>: "String", <freq>: "<f> Hz/kHz/MHz", ### <percent>: "<f>%" ### [arg]: arg optional #Option "ShadowFB" # [<bool>] #Option "DefaultRefresh" # [<bool>] #Option "ModeSetClearScreen" # [<bool>] Identifier "Card2" Driver "vesa" BusID "PCI:5:0:0" EndSection Section "Device" Identifier "aticonfig-Device[0]-0" Driver "fglrx" Option "Monitor-DFP1" "0-DFP1" Option "Monitor-CRT2" "0-CRT2" BusID "PCI:5:0:0" EndSection Section "Device" Identifier "DisplayLinkDevice" Driver "displaylink" Option "fbdev" "/dev/fb1" Option "ShadowFB" "off" EndSection Section "Screen" Identifier "aticonfig-Screen[0]-0" Device "aticonfig-Device[0]-0" DefaultDepth 24 SubSection "Display" Viewport 0 0 Virtual 3600 1920 Depth 24 EndSubSection EndSection Section "Screen" Identifier "DisplayLinkScreen" Device "DisplayLinkDevice" Monitor "DisplayLinkMonitor" DefaultDepth 24 SubSection "Display" Depth 24 Modes "1920x1080" EndSubSection EndSection

    Read the article

  • calculater by using reverse polish notation and using a stack

    - by programmer
    hello everyone I have a segmentation fault ,can you help please? if i have this operater "3 5 +" that mean 3+5 and like "9 8 * 5 + 4 + sin", "sin(((9*8)+5)+4)" so my idea is check if the first and second are numbers and push theem in the stack then when i have operator i pop the numbers and make the calculation then push the answer again. ` typedef struct st_node { float val; struct st_node *next; } t_node; typedef t_node t_stack; // a function to allocate memory for a stack and returns the stack t_stack* fnewCell() { t_stack* ret; ret = (t_stack*) malloc(sizeof(t_stack)); return ret; } // a function to allocate memory for a stack, fills it with value v and pointer n , and returns the stack t_stack* fnewCellFilled(float v, t_stack* n) { t_stack* ret; ret = fnewCell(); ret->val = v; ret->next =n; return ret; } //function to initialize stack void initstack(t_stack** stack) { fnewCellFilled(0,NULL); } // add new cell void insrtHead(t_stack** head,float val) { *head = fnewCellFilled(val,*head); } //function to push the value v into the stack s void push(t_stack **s, float val) { insrtHead(s,val); } //function to pop a value from the stack and returns it int pop(t_stack **s) { t_stack* tmp; int ret; tmp = (*s)->next; ret = (*s)->val; free(*s); (*s) = tmp; return ret; } int isempty (t_stack *t) { return t == NULL; } //function to transfer a string(str) to int (value) //returns -1 when success , i otherwise int str2int(char *str,int *value) { int i; *value = 0; int sign=(str[0]=='-' ? -1 : 1); for(i=(str[0]=='-' ? 1 : 0);str[i]!=0;i++) { if(!(str[i]>=48 && str[i]<=57)) // Ascii char 0 to 9 return i; *value= *value*10+(str[i]-48); } *value = *value * sign; return -1; } //a function that takes a string, transfer it into integer and make operation using a stack void function(t_stack *stack, char *str) { char x[10]=" "; int y,j,i=0,z; printf("++\n"); if(str[i] != '\0') { strcpy(x, strtok(str, " ")); z= str2int(x, &y); if(z == -1) { push(&stack,y); i=i+2; } } while(str[i] != '\0') { strcpy(x, strtok(NULL, " ")); z= str2int(x, &y); if(z == -1) { printf("yes %d",y); push(&stack,y); i=i+2; } else { y=pop(&stack); j=pop(&stack); if(x[0] == '+' ) push(&stack,y+j); else if (x[0] == '-' ) push(&stack,j-y); else if(x[0] == '*' ) push(&stack,j*y); else if(x[0] == '/') push (&stack ,j/y); } } } int main() { t_stack *s; initstack(&s); char *str="3 5 +"; function(s,str); return 0; } `

    Read the article

  • Accessing elements of List<List<string>>

    - by shiv09
    Hello Friends........... Can anyone let me know how can access an element of a list that has been added to a list of list............. I'll mention the code............ List str = new List(); List stud = new List(); A method has been defined that inserts data into str and after the method gets over......... stud.Add(str); The method and stud.Add(str) is on a button click...... so, each time str contains different data....... the problem is I want to search in whole of stud i.e. all the str created, whether str[0]==textBox3.Text; I'm confused in the For loops...how to reach to all the str[0] in stud to verify the condition...................

    Read the article

  • Parsing and getting specific values from CSV string

    - by Amit Ranjan
    I am having a string in CSV format. Please see my earlier question http://stackoverflow.com/questions/2865861/parsing-csv-string-and-binding-it-to-listbox I can add new values to it by some mechanism. Everything will be same except the new values will have numeric part = 0. Take example I have this exsiting CSV string 1 , abc.txt , 2 , def.doc , 3 , flyaway.txt Now by some mechanism i added two more files Superman.txt and Spiderman.txt to the existing string. Now it became 1 , abc.txt , 2 , def.doc , 3 , flyaway.txt, 0, Superman.txt, 0 , Spiderman.txt What i am doing here is that this csv string is paased into SP where its splitted and inserted to db. So for inserting I have to take the files with numeric part 0 only rest will be omiited .Which will be further then converted into CSV string Array will look like this str[0]="1" str[1]="abc.txt" str[2]="2" str[3]="def.doc " str[4]="3" str[5]="flyaway.txt" str[6]="0" str[7]="Superman.txt" str[8]="0" str[9]="Spiderman.txt" So at last i want to say my input will be 1 , abc.txt , 2 , def.doc , 3 , flyaway.txt, 0, Superman.txt, 0 , Spiderman.txt Desired Output: 0, Superman.txt, 0 , Spiderman.txt

    Read the article

  • Explanation of this SQL sanitization code

    - by Derek
    I got this from for a login form tutorial: function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } Could some one explain exactly what this does? I know that the 'clean' var is called up afterwards to sanitize the fields; I.e. $email = clean($_POST['email']);

    Read the article

  • cant get regex to work as i want

    - by Jorm
    With this function: function bbcode_parse($str) { $str = htmlentities($str); $find = array( '/\\*\*(.[^*]*)\*\*/is', ); $replace = array( '<b>' ); $str = preg_replace($find, $replace, $str); return $str; } And with text "My name is **bob**" I get in source code Hi my name is <b> Been trying to get this to work for a while now. Would appricate some expert help :)

    Read the article

  • Python overriding class (not instance) special methods

    - by André
    How do I override a class special method? I want to be able to call the __str__() method of the class without creating an instance. Example: class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' class ClassFoo: @classmethod def __str__(cls): return 'ClassBar' if __name__ == '__main__': print(Foo) print(Foo()) print(StaticFoo) print(StaticFoo()) print(ClassFoo) print(ClassFoo()) produces: <class '__main__.Foo'> Bar <class '__main__.StaticFoo'> StaticBar <class '__main__.ClassFoo'> ClassBar should be: Bar Bar StaticBar StaticBar ClassBar ClassBar Even if I use the @staticmethod or @classmethod the __str__ is still using the built in python definition for __str__. It's only working when it's Foo().__str__() instead of Foo.__str__().

    Read the article

  • SOLR date faceting and BC / BCE dates / negative date ranges

    - by Nigel_V_Thomas
    Date ranges including BC dates is this possible? I would like to return facets for all years between 11000 BCE (BC) and 9000 BCE (BC) using SOLR. A sample query might be with date ranges converted to ISO 8601: q=*:*&facet.date=myfield_earliestDate&facet.date.end=-92009-01-01T00:00:00&facet.date.gap=%2B1000YEAR&facet.date.other=all&facet=on&f.myfield_earliestDate.facet.date.start=-112009-01-01T00:00:00 However the returned results seem to be suggest that dates are in positive range, ie CE, not BCE... see sample returned results <response> <lst name="responseHeader"> <int name="status">0</int> <int name="QTime">6</int> <lst name="params"> <str name="f.vra.work.creation.earliestDate.facet.date.start">-112009-01-01T00:00:00Z</str> <str name="facet">on</str> <str name="q">*:*</str> <str name="facet.date">vra.work.creation.earliestDate</str> <str name="facet.date.gap">+1000YEAR</str> <str name="facet.date.other">all</str> <str name="facet.date.end">-92009-01-01T00:00:00Z</str> </lst> </lst> <result name="response" numFound="9556" start="0">ommitted</result> <lst name="facet_counts"> <lst name="facet_queries"/> <lst name="facet_fields"/> <lst name="facet_dates"> <lst name="vra.work.creation.earliestDate"> <int name="112010-01-01T00:00:00Z">0</int> <int name="111010-01-01T00:00:00Z">0</int> <int name="110010-01-01T00:00:00Z">0</int> <int name="109010-01-01T00:00:00Z">0</int> <int name="108010-01-01T00:00:00Z">0</int> <int name="107010-01-01T00:00:00Z">0</int> <int name="106010-01-01T00:00:00Z">0</int> <int name="105010-01-01T00:00:00Z">0</int> <int name="104010-01-01T00:00:00Z">0</int> <int name="103010-01-01T00:00:00Z">0</int> <int name="102010-01-01T00:00:00Z">0</int> <int name="101010-01-01T00:00:00Z">0</int> <int name="100010-01-01T00:00:00Z">5781</int> <int name="99010-01-01T00:00:00Z">0</int> <int name="98010-01-01T00:00:00Z">0</int> <int name="97010-01-01T00:00:00Z">0</int> <int name="96010-01-01T00:00:00Z">0</int> <int name="95010-01-01T00:00:00Z">0</int> <int name="94010-01-01T00:00:00Z">0</int> <int name="93010-01-01T00:00:00Z">0</int> <str name="gap">+1000YEAR</str> <date name="end">92010-01-01T00:00:00Z</date> <int name="before">224</int> <int name="after">0</int> <int name="between">5690</int> </lst> </lst> </lst> </response> Any ideas why this is the case, can solr handle negative dates such as -112009-01-01T00:00:00Z?

    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

  • Very different I/O performance in C++ on Windows

    - by Mr.Gate
    Hi all, I'm a new user and my english is not so good so I hope to be clear. We're facing a performance problem using large files (1GB or more) expecially (as it seems) when you try to grow them in size. Anyway... to verify our sensations we tryed the following (on Win 7 64Bit, 4core, 8GB Ram, 32 bit code compiled with VC2008) a) Open an unexisting file. Write it from the beginning up to 1Gb in 1Mb slots. Now you have a 1Gb file. Now randomize 10000 positions within that file, seek to that position and write 50 bytes in each position, no matter what you write. Close the file and look at the results. Time to create the file is quite fast (about 0.3"), time to write 10000 times is fast all the same (about 0.03"). Very good, this is the beginnig. Now try something else... b) Open an unexisting file, seek to 1Gb-1byte and write just 1 byte. Now you have another 1Gb file. Follow the next steps exactly same way of case 'a', close the file and look at the results. Time to create the file is the faster you can imagine (about 0.00009") but write time is something you can't believe.... about 90"!!!!! b.1) Open an unexisting file, don't write any byte. Act as before, ramdomizing, seeking and writing, close the file and look at the result. Time to write is long all the same: about 90"!!!!! Ok... this is quite amazing. But there's more! c) Open again the file you crated in case 'a', don't truncate it... randomize again 10000 positions and act as before. You're fast as before, about 0,03" to write 10000 times. This sounds Ok... try another step. d) Now open the file you created in case 'b', don't truncate it... randomize again 10000 positions and act as before. You're slow again and again, but the time is reduced to... 45"!! Maybe, trying again, the time will reduce. I actually wonder why... Any Idea? The following is part of the code I used to test what I told in previuos cases (you'll have to change someting in order to have a clean compilation, I just cut & paste from some source code, sorry). The sample can read and write, in random, ordered or reverse ordered mode, but write only in random order is the clearest test. We tryed using std::fstream but also using directly CreateFile(), WriteFile() and so on the results are the same (even if std::fstream is actually a little slower). Parameters for case 'a' = -f_tempdir_\casea.dat -n10000 -t -p -w Parameters for case 'b' = -f_tempdir_\caseb.dat -n10000 -t -v -w Parameters for case 'b.1' = -f_tempdir_\caseb.dat -n10000 -t -w Parameters for case 'c' = -f_tempdir_\casea.dat -n10000 -w Parameters for case 'd' = -f_tempdir_\caseb.dat -n10000 -w Run the test (and even others) and see... // iotest.cpp : Defines the entry point for the console application. // #include <windows.h> #include <iostream> #include <set> #include <vector> #include "stdafx.h" double RealTime_Microsecs() { LARGE_INTEGER fr = {0, 0}; LARGE_INTEGER ti = {0, 0}; double time = 0.0; QueryPerformanceCounter(&ti); QueryPerformanceFrequency(&fr); time = (double) ti.QuadPart / (double) fr.QuadPart; return time; } int main(int argc, char* argv[]) { std::string sFileName ; size_t stSize, stTimes, stBytes ; int retval = 0 ; char *p = NULL ; char *pPattern = NULL ; char *pReadBuf = NULL ; try { // Default stSize = 1<<30 ; // 1Gb stTimes = 1000 ; stBytes = 50 ; bool bTruncate = false ; bool bPre = false ; bool bPreFast = false ; bool bOrdered = false ; bool bReverse = false ; bool bWriteOnly = false ; // Comsumo i parametri for(int index=1; index < argc; ++index) { if ( '-' != argv[index][0] ) throw ; switch(argv[index][1]) { case 'f': sFileName = argv[index]+2 ; break ; case 's': stSize = xw::str::strtol(argv[index]+2) ; break ; case 'n': stTimes = xw::str::strtol(argv[index]+2) ; break ; case 'b':stBytes = xw::str::strtol(argv[index]+2) ; break ; case 't': bTruncate = true ; break ; case 'p' : bPre = true, bPreFast = false ; break ; case 'v' : bPreFast = true, bPre = false ; break ; case 'o' : bOrdered = true, bReverse = false ; break ; case 'r' : bReverse = true, bOrdered = false ; break ; case 'w' : bWriteOnly = true ; break ; default: throw ; break ; } } if ( sFileName.empty() ) { std::cout << "Usage: -f<File Name> -s<File Size> -n<Number of Reads and Writes> -b<Bytes per Read and Write> -t -p -v -o -r -w" << std::endl ; std::cout << "-t truncates the file, -p pre load the file, -v pre load 'veloce', -o writes in order mode, -r write in reverse order mode, -w Write Only" << std::endl ; std::cout << "Default: 1Gb, 1000 times, 50 bytes" << std::endl ; throw ; } if ( !stSize || !stTimes || !stBytes ) { std::cout << "Invalid Parameters" << std::endl ; return -1 ; } size_t stBestSize = 0x00100000 ; std::fstream fFile ; fFile.open(sFileName.c_str(), std::ios_base::binary|std::ios_base::out|std::ios_base::in|(bTruncate?std::ios_base::trunc:0)) ; p = new char[stBestSize] ; pPattern = new char[stBytes] ; pReadBuf = new char[stBytes] ; memset(p, 0, stBestSize) ; memset(pPattern, (int)(stBytes&0x000000ff), stBytes) ; double dTime = RealTime_Microsecs() ; size_t stCopySize, stSizeToCopy = stSize ; if ( bPre ) { do { stCopySize = std::min(stSizeToCopy, stBestSize) ; fFile.write(p, stCopySize) ; stSizeToCopy -= stCopySize ; } while (stSizeToCopy) ; std::cout << "Creating time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } else if ( bPreFast ) { fFile.seekp(stSize-1) ; fFile.write(p, 1) ; std::cout << "Creating Fast time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } size_t stPos ; ::srand((unsigned int)dTime) ; double dReadTime, dWriteTime ; stCopySize = stTimes ; std::vector<size_t> inVect ; std::vector<size_t> outVect ; std::set<size_t> outSet ; std::set<size_t> inSet ; // Prepare vector and set do { stPos = (size_t)(::rand()<<16) % stSize ; outVect.push_back(stPos) ; outSet.insert(stPos) ; stPos = (size_t)(::rand()<<16) % stSize ; inVect.push_back(stPos) ; inSet.insert(stPos) ; } while (--stCopySize) ; // Write & read using vectors if ( !bReverse && !bOrdered ) { std::vector<size_t>::iterator outI, inI ; outI = outVect.begin() ; inI = inVect.begin() ; stCopySize = stTimes ; dReadTime = 0.0 ; dWriteTime = 0.0 ; do { dTime = RealTime_Microsecs() ; fFile.seekp(*outI) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++outI ; if ( !bWriteOnly ) { dTime = RealTime_Microsecs() ; fFile.seekg(*inI) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++inI ; } } while (--stCopySize) ; std::cout << "Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " (Ave: " << xw::str::itoa(dWriteTime/stTimes, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { std::cout << "Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " (Ave: " << xw::str::itoa(dReadTime/stTimes, 10, 'f') << ")" << std::endl ; } } // End // Write in order if ( bOrdered ) { std::set<size_t>::iterator i = outSet.begin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.begin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End // Write in reverse order if ( bReverse ) { std::set<size_t>::reverse_iterator i = outSet.rbegin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.rbegin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End dTime = RealTime_Microsecs() ; fFile.close() ; std::cout << "Flush/Close Time is " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; std::cout << "Program Terminated" << std::endl ; } catch(...) { std::cout << "Something wrong or wrong parameters" << std::endl ; retval = -1 ; } if ( p ) delete []p ; if ( pPattern ) delete []pPattern ; if ( pReadBuf ) delete []pReadBuf ; return retval ; }

    Read the article

  • ArgumentException or ArgumentNullException for string parameters?

    - by Anna Lear
    Far as best practices are concerned, which is better: public void SomeMethod(string str) { if(string.IsNullOrEmpty(str)) { throw new ArgumentException("str cannot be null or empty."); } // do other stuff } or public void SomeMethod(string str) { if(str == null) { throw new ArgumentNullException("str"); } if(str == string.Empty) { throw new ArgumentException("str cannot be empty."); } // do other stuff } The second version seems more precise, but also more cumbersome than the first. I usually go with #1, but figured I'd check if there's an argument to be made for #2.

    Read the article

  • Problem using delete[] (Heap corruption) when implementing operator+= (C++)

    - by Darel
    I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong. I have written a simple class to emulate basic functionality of strings. The class's members include a character pointer data (which points to a dynamically created char array) and an integer strSize (which holds the length of the string, sans terminator.) Since I'm using new and delete, I've implemented the copy constructor and destructor. My problem occurs when I try to implement the operator+=. The LHS object builds the new string correctly - I can even print it using cout - but the problem comes when I try to deallocate the data pointer in the destructor: I get a "Heap Corruption Detected after normal block" at the memory address pointed to by the data array the destructor is trying to deallocate. Here's my complete class and test program: #include <iostream> using namespace std; // Class to emulate string class Str { public: // Default constructor Str(): data(0), strSize(0) { } // Constructor from string literal Str(const char* cp) { data = new char[strlen(cp) + 1]; char *p = data; const char* q = cp; while (*q) *p++ = *q++; *p = '\0'; strSize = strlen(cp); } Str& operator+=(const Str& rhs) { // create new dynamic memory to hold concatenated string char* str = new char[strSize + rhs.strSize + 1]; char* p = str; // new data char* i = data; // old data const char* q = rhs.data; // data to append // append old string to new string in new dynamic memory while (*p++ = *i++) ; p--; while (*p++ = *q++) ; *p = '\0'; // assign new values to data and strSize delete[] data; data = str; strSize += rhs.strSize; return *this; } // Copy constructor Str(const Str& s) { data = new char[s.strSize + 1]; char *p = data; char *q = s.data; while (*q) *p++ = *q++; *p = '\0'; strSize = s.strSize; } // destructor ~Str() { delete[] data; } const char& operator[](int i) const { return data[i]; } int size() const { return strSize; } private: char *data; int strSize; }; ostream& operator<<(ostream& os, const Str& s) { for (int i = 0; i != s.size(); ++i) os << s[i]; return os; } // Test constructor, copy constructor, and += operator int main() { Str s = "hello"; // destructor for s works ok Str x = s; // destructor for x works ok s += "world!"; // destructor for s gives error cout << s << endl; cout << x << endl; return 0; }

    Read the article

  • Why is my implementation of strcmp not returning the proper value?

    - by Avanish Giri
    Why is this printing out 0 back in main but 6 when it is inside of the strcmp function? 7 int main() 8 { 9 char* str = "test string"; 10 char* str2 = "test strong"; 11 //printf("string length = %d\n",strlen(str)); 12 13 int num = strcmp(str,str2); 14 15 printf("num = %d\n",num); 16 } 29 int strcmp(char* str, char* str2) 30 { 31 if(*str == '\0' && *str2 == '\0') 32 return 0; 33 if(*str2 - *str == 0) 34 { 35 strcmp(str+1,str2+1); 36 } 37 else 38 { 39 int num = *str2 - *str; 40 cout << "num = " <<num<<endl; 41 return num; 42 } 43 } The output is: num = 6 num = 0 Why is it printing 0 when obviously the value that it should be returning is 6?

    Read the article

  • Why Solr admin query page interprets UTF-8 as ISO-8859-1

    - by Scott Chu
    I deploy a war to my Tomcat 6.0.35 on Win7 64bit and when I use full-interface query page (I mean form.jsp) in Solr Admin to query 2 Chinese character (say it's C1C2) , the debug info shows: <lst name="debug"> <str name="rawquerystring">æ°è</str> <str name="querystring">æ°è</str> <str name="parsedquery">NEWSID:æ°è</str> <str name="parsedquery_toString">NEWSID:æ°è</str> ... You can see C1C2 becomes æ°è. I deploy same war file to Tomcat on Linux or on another Win7 64bit of my colleagues' computer, the encoding acts well. Does anyone know why and how can I avoid this problem? Thanks in advance!

    Read the article

  • C++, is it possible to call a constructor directly, without new?

    - by osgx
    Hello Can I call constructor explicitly, without using new, if I already have a memory for object? // class Object1{char *str;public:Object1(char*str):str(str){puts("ctor");puts(str);};~Object1(){puts("dtor");puts(str);}}; Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")}; do_smth_useful(ooo); ooo[0].~Object1(); // call destructor ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory

    Read the article

  • Very different IO performance in C/C++

    - by Roberto Tirabassi
    Hi all, I'm a new user and my english is not so good so I hope to be clear. We're facing a performance problem using large files (1GB or more) expecially (as it seems) when you try to grow them in size. Anyway... to verify our sensations we tryed the following (on Win 7 64Bit, 4core, 8GB Ram, 32 bit code compiled with VC2008) a) Open an unexisting file. Write it from the beginning up to 1Gb in 1Mb slots. Now you have a 1Gb file. Now randomize 10000 positions within that file, seek to that position and write 50 bytes in each position, no matter what you write. Close the file and look at the results. Time to create the file is quite fast (about 0.3"), time to write 10000 times is fast all the same (about 0.03"). Very good, this is the beginnig. Now try something else... b) Open an unexisting file, seek to 1Gb-1byte and write just 1 byte. Now you have another 1Gb file. Follow the next steps exactly same way of case 'a', close the file and look at the results. Time to create the file is the faster you can imagine (about 0.00009") but write time is something you can't believe.... about 90"!!!!! b.1) Open an unexisting file, don't write any byte. Act as before, ramdomizing, seeking and writing, close the file and look at the result. Time to write is long all the same: about 90"!!!!! Ok... this is quite amazing. But there's more! c) Open again the file you crated in case 'a', don't truncate it... randomize again 10000 positions and act as before. You're fast as before, about 0,03" to write 10000 times. This sounds Ok... try another step. d) Now open the file you created in case 'b', don't truncate it... randomize again 10000 positions and act as before. You're slow again and again, but the time is reduced to... 45"!! Maybe, trying again, the time will reduce. I actually wonder why... Any Idea? The following is part of the code I used to test what I told in previuos cases (you'll have to change someting in order to have a clean compilation, I just cut & paste from some source code, sorry). The sample can read and write, in random, ordered or reverse ordered mode, but write only in random order is the clearest test. We tryed using std::fstream but also using directly CreateFile(), WriteFile() and so on the results are the same (even if std::fstream is actually a little slower). Parameters for case 'a' = -f_tempdir_\casea.dat -n10000 -t -p -w Parameters for case 'b' = -f_tempdir_\caseb.dat -n10000 -t -v -w Parameters for case 'b.1' = -f_tempdir_\caseb.dat -n10000 -t -w Parameters for case 'c' = -f_tempdir_\casea.dat -n10000 -w Parameters for case 'd' = -f_tempdir_\caseb.dat -n10000 -w Run the test (and even others) and see... // iotest.cpp : Defines the entry point for the console application. // #include <windows.h> #include <iostream> #include <set> #include <vector> #include "stdafx.h" double RealTime_Microsecs() { LARGE_INTEGER fr = {0, 0}; LARGE_INTEGER ti = {0, 0}; double time = 0.0; QueryPerformanceCounter(&ti); QueryPerformanceFrequency(&fr); time = (double) ti.QuadPart / (double) fr.QuadPart; return time; } int main(int argc, char* argv[]) { std::string sFileName ; size_t stSize, stTimes, stBytes ; int retval = 0 ; char *p = NULL ; char *pPattern = NULL ; char *pReadBuf = NULL ; try { // Default stSize = 1<<30 ; // 1Gb stTimes = 1000 ; stBytes = 50 ; bool bTruncate = false ; bool bPre = false ; bool bPreFast = false ; bool bOrdered = false ; bool bReverse = false ; bool bWriteOnly = false ; // Comsumo i parametri for(int index=1; index < argc; ++index) { if ( '-' != argv[index][0] ) throw ; switch(argv[index][1]) { case 'f': sFileName = argv[index]+2 ; break ; case 's': stSize = xw::str::strtol(argv[index]+2) ; break ; case 'n': stTimes = xw::str::strtol(argv[index]+2) ; break ; case 'b':stBytes = xw::str::strtol(argv[index]+2) ; break ; case 't': bTruncate = true ; break ; case 'p' : bPre = true, bPreFast = false ; break ; case 'v' : bPreFast = true, bPre = false ; break ; case 'o' : bOrdered = true, bReverse = false ; break ; case 'r' : bReverse = true, bOrdered = false ; break ; case 'w' : bWriteOnly = true ; break ; default: throw ; break ; } } if ( sFileName.empty() ) { std::cout << "Usage: -f<File Name> -s<File Size> -n<Number of Reads and Writes> -b<Bytes per Read and Write> -t -p -v -o -r -w" << std::endl ; std::cout << "-t truncates the file, -p pre load the file, -v pre load 'veloce', -o writes in order mode, -r write in reverse order mode, -w Write Only" << std::endl ; std::cout << "Default: 1Gb, 1000 times, 50 bytes" << std::endl ; throw ; } if ( !stSize || !stTimes || !stBytes ) { std::cout << "Invalid Parameters" << std::endl ; return -1 ; } size_t stBestSize = 0x00100000 ; std::fstream fFile ; fFile.open(sFileName.c_str(), std::ios_base::binary|std::ios_base::out|std::ios_base::in|(bTruncate?std::ios_base::trunc:0)) ; p = new char[stBestSize] ; pPattern = new char[stBytes] ; pReadBuf = new char[stBytes] ; memset(p, 0, stBestSize) ; memset(pPattern, (int)(stBytes&0x000000ff), stBytes) ; double dTime = RealTime_Microsecs() ; size_t stCopySize, stSizeToCopy = stSize ; if ( bPre ) { do { stCopySize = std::min(stSizeToCopy, stBestSize) ; fFile.write(p, stCopySize) ; stSizeToCopy -= stCopySize ; } while (stSizeToCopy) ; std::cout << "Creating time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } else if ( bPreFast ) { fFile.seekp(stSize-1) ; fFile.write(p, 1) ; std::cout << "Creating Fast time is: " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; } size_t stPos ; ::srand((unsigned int)dTime) ; double dReadTime, dWriteTime ; stCopySize = stTimes ; std::vector<size_t> inVect ; std::vector<size_t> outVect ; std::set<size_t> outSet ; std::set<size_t> inSet ; // Prepare vector and set do { stPos = (size_t)(::rand()<<16) % stSize ; outVect.push_back(stPos) ; outSet.insert(stPos) ; stPos = (size_t)(::rand()<<16) % stSize ; inVect.push_back(stPos) ; inSet.insert(stPos) ; } while (--stCopySize) ; // Write & read using vectors if ( !bReverse && !bOrdered ) { std::vector<size_t>::iterator outI, inI ; outI = outVect.begin() ; inI = inVect.begin() ; stCopySize = stTimes ; dReadTime = 0.0 ; dWriteTime = 0.0 ; do { dTime = RealTime_Microsecs() ; fFile.seekp(*outI) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++outI ; if ( !bWriteOnly ) { dTime = RealTime_Microsecs() ; fFile.seekg(*inI) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++inI ; } } while (--stCopySize) ; std::cout << "Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " (Ave: " << xw::str::itoa(dWriteTime/stTimes, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { std::cout << "Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " (Ave: " << xw::str::itoa(dReadTime/stTimes, 10, 'f') << ")" << std::endl ; } } // End // Write in order if ( bOrdered ) { std::set<size_t>::iterator i = outSet.begin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.begin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.end(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End // Write in reverse order if ( bReverse ) { std::set<size_t>::reverse_iterator i = outSet.rbegin() ; dWriteTime = 0.0 ; stCopySize = 0 ; for(; i != outSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekp(stPos) ; fFile.write(pPattern, stBytes) ; dWriteTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Write time is " << xw::str::itoa(dWriteTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dWriteTime/stCopySize, 10, 'f') << ")" << std::endl ; if ( !bWriteOnly ) { i = inSet.rbegin() ; dReadTime = 0.0 ; stCopySize = 0 ; for(; i != inSet.rend(); ++i) { stPos = *i ; dTime = RealTime_Microsecs() ; fFile.seekg(stPos) ; fFile.read(pReadBuf, stBytes) ; dReadTime += RealTime_Microsecs() - dTime ; ++stCopySize ; } std::cout << "Reverse ordered Read time is " << xw::str::itoa(dReadTime, 5, 'f') << " in " << xw::str::itoa(stCopySize) << " (Ave: " << xw::str::itoa(dReadTime/stCopySize, 10, 'f') << ")" << std::endl ; } }// End dTime = RealTime_Microsecs() ; fFile.close() ; std::cout << "Flush/Close Time is " << xw::str::itoa(RealTime_Microsecs()-dTime, 5, 'f') << std::endl ; std::cout << "Program Terminated" << std::endl ; } catch(...) { std::cout << "Something wrong or wrong parameters" << std::endl ; retval = -1 ; } if ( p ) delete []p ; if ( pPattern ) delete []pPattern ; if ( pReadBuf ) delete []pReadBuf ; return retval ; }

    Read the article

  • function to remove duplicate characters in a string

    - by Codenotguru
    The following code is trying to remove any duplicate characters in a string.Iam not sure if the code is right??Can anybody help me with the working of the code i.e whats actually happening when there is a match in characters? public static void removeDuplicates(char[] str) { if (str == null) return; int len = str.length; if (len < 2) return; int tail = 1; for (int i = 1; i < len; ++i) { int j; for (j = 0; j < tail; ++j) { if (str[i] == str[j]) break; } if (j == tail) { str[tail] = str[i]; ++tail; } } str[tail] = 0; }

    Read the article

  • jQuery: Quick question. How to select string variable?

    - by user317563
    Hello world, EDIT: I would like to avoid doing something like this: var str = 'Hello'; if ( str == 'Hello') { alert(str); } I would rather do: var str = 'Hello'; $(str).filter(':contains("Hello")').each(function(){ alert(this) }); I've tried a lot of things: $(str).text().method1().method2().method3(); $(str).val().method1().method2().method3(); $(str).contents().method1().method2().method3(); Nothing worked. Is it possible to do this? Thank you for your time. Kind regards, Marius

    Read the article

  • IOS 7 Table cell not show

    - by user2855572
    I am getting very strange problem in my app. I am creating table view cell dynamically.My problem is that textlable is not showing. Code was working on ios 5 and ios 6 but not working on ios 7 it is giving problem.Anybody help me NSString *Str=[NSString stringWithFormat:@"%@",[dateCalcuArray objectAtIndex:indexPath.row]]; Str=[Str stringByReplacingOccurrencesOfString:@"(" withString:@""]; Str=[Str stringByReplacingOccurrencesOfString:@")" withString:@""]; Str=[Str stringByReplacingOccurrencesOfString:@"\"" withString:@""]; ipad_Cell.datelbl.text=Str; ipad_Cell.datelbl.textColor=[UIColor whiteColor];

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >