Search Results

Search found 4882 results on 196 pages for 'odd behaviour'.

Page 12/196 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Sum of a matrix, even or odd

    - by user1790201
    This function receives a numeric matrix represented as a list of rows, where each row is in turn a list. Assume that it is a square matrix: all rows have the same length and there are as many rows as elements in each row. Also assume that the matrix is at least of dimension 2 by 2 (i.e. minimally the matrix has 2 rows with 2 elements each) The function should return a list with as many elements as number of rows. Element i in the resulting list should have the sum of the values in row i. For example, if the matrix is 1 2 3 10 20 30 100 200 300 then this function should return the list [6,60,600] That is, addValuesInAllRows( [ [1,2,3], [10,20,30], [100,200,300] ] ) should return [6,60,600] Isn't this sort of similar but how would you sum up the list individually

    Read the article

  • Strange iterator behaviour

    - by A-ha
    #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { string s = "Haven't got an idea why."; auto beg = s.begin(); auto end = s.end(); while (beg < end) { cout << *beg << '\n'; if (*beg == 'a') {//whithout if construct it works perfectly beg = s.erase(beg); } ++beg; } return 0; } Why if I erase one or more chars from this string this code breaks? I suppose it has something to do with returned iterator after erase operation being created at higher address than end iterator but I'm not sure and it surely isn't right behaviour. Or is it?

    Read the article

  • Strange Behaviour WPF TreeView ItemContainerStyle and ItemTemplate

    - by Matze
    I just noticed some strange behaviour of WPF's TreeView. I added both ItemContainerStyle to bind to "IsSelected" of my ViewModel and an ItemsTemplated for custom display of my data. But now the user cannot change the selected node anymore. For testing purposes I created a similar UI using ListView and Expander. This version works as excepted. Any tips why TreeView does fail? <TreeView ItemsSource="{Binding ElementName=frame, Path=list}"> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}" > <Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/> </Style> </TreeView.ItemContainerStyle> <TreeView.ItemTemplate> <HierarchicalDataTemplate> <TreeViewItem Header="{Binding}"> <TextBlock Text="{Binding Path= Item.SomeData}"/> </TreeViewItem> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>

    Read the article

  • WPF Richtextbox XamlWriter behaviour

    - by Krishna
    I am trying to save some c# source code into the database. Basically I have a RichTextBox that users can type their code and save that to the database. When I copy and paste from the visual studio environment, I would like to preserve the formating etc. So I have chosen to save the FlowDocuments Xaml to the database and set this back to the RichTextBox.Document. My below two function serialise and deserialise the RTB's contents. private string GetXaml(FlowDocument document) { if (document == null) return String.Empty; else{ StringBuilder sb = new StringBuilder(); XmlWriter xw = XmlWriter.Create(sb); XamlDesignerSerializationManager sm = new XamlDesignerSerializationManager(xw); sm.XamlWriterMode = XamlWriterMode.Expression; XamlWriter.Save(document, sm ); return sb.ToString(); } } private FlowDocument GetFlowDocument(string xamlText) { var flowDocument = new FlowDocument(); if (xamlText != null) flowDocument = (FlowDocument)XamlReader.Parse(xamlText); // Set return value return flowDocument; } However when I try to serialise and deserialise the following code, I am noticing this incorrect(?) behaviour using System; public class TestCSScript : MarshalByRefObject { } Serialised XAML is using System; public class TestCSScript : MarshalByRefObject {}{ } Notice the the new set of "{}" What am I doing wrong here... Thanks in advance for the help!

    Read the article

  • MVC ASP.NET, ObjectContext and Ajax. Weird Behaviour

    - by fabianadipolo
    Hi, i've been creating a web application in mvc asp.net. I have three different project/solutions. One solution contains the model in EF (DAL) and all the methods to add, update, delete and query the objects in the model, the objectcontext is managed here in a per request basis. Other solution contains a content management system in wich authorized users insert, delete, update and access objects through the DAL mentioned before. And the last solution contains the web page that is accessed by all users and where the only operations executed are selects, no update, inserts or deletes here. All the selects are executed against the DAL mentioned before (the first solution). The problem here is that i'm not sure whether an HttpContext lifespan ObjectContext is the best solution. I have a lot of ajax calls in my web app and i'm not sure if an httpcontext could interfere with the performance of the application. I've been noticed that in some cases, specially when someone is working in the content manager inserting, updating or deleting, when you try to click on any link of the user web application (the web app that is accessed by any user - the third one that i mentioned before) the web page freezes and it remains stucked transferring data. In order to stop that behaviour you have to stop and refresh or click several times on the link. Excuse me for my bad english. I hope you could understand and could help me to solve this issue. Thanx in advance.

    Read the article

  • Something preventing default (explorer-style) CListCtrl jump to line behaviour

    - by andywebsdale
    I'm maintaining an MFC/COM/ATL 45-odd project solution originally written with VS6. I'm now using VS2008. I'm looking at a list control(vanilla CListCtrl) which doesn't behave as we think it should. Normally in an MFC list control you can press a key, (Q say) & selection will jump down to the 1st line beginning with 'Q' (like windows explorer). Does anyone have an idea as to why this might not happen? The styles/Extended styles are set the same as another control in the same project, which DOES work OK. Do I have to send my own message, or is there a flag, etc. that controls that functionality or what? Normally Google would supply the answer, but I haven't been able to frame my query correctly to come up with the relevant info this time. Here's the line from the .rc file for the CListCtrl that doesn't jump to a line on keypress: CONTROL "List1",IDC_BAL_LIST,"SysListView32",LVS_REPORT | LVS_SHOWSELALWAYS | WS_BORDER | WS_TABSTOP,0,73,493,230 And here's a line from the same .rc file showing a list control that does do that: CONTROL "List1",IDC_LIST1,"SysListView32",LVS_REPORT | LVS_SHOWSELALWAYS | WS_BORDER | WS_TABSTOP,1,38,501,219 As you can see, there's no obvious difference to the properties, so what program code would affect it?

    Read the article

  • Strange Behaviour in DataGrid SilverLight 3 Control

    - by Asim Sajjad
    Here is the my Xaml Code. Here I have changed the Foreground of the cell depending on the current age of the person. <data:DataGridTemplateColumn Header="First Name" Width="150" MinWidth="150" CanUserReorder="False" SortMemberPath="FirstName"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate > <TextBlock Foreground ="{Binding Path=DateOfBirth,Mode=OneWay,Converter={StaticResource CellColor}}" Text="{Binding FirstName}" ToolTipService.ToolTip="{Binding FirstName}" FontFamily="Arial" FontSize="11" VerticalAlignment="Center" Margin="5,0,0,0" /> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> <data:DataGridTextColumn Foreground ="{Binding Path=DateOfBirth,Mode=OneWay,Converter={StaticResource CellColor}}" Header="Last Name" Width="150" MinWidth="150" Binding="{Binding LastName}" CanUserSort="True" IsReadOnly="True" CanUserReorder="False"/> When I run the above code it return following Exception AG_E_PARSER_BAD_PROPERTY_VALU My question is that when I remove the Foreground converter from the DataGridTextColumn Column it runs fine As the Foreground converter is applied in the DataGridTemplateColumn Column which will not through excepction. But when I used same Converter to the DataGridTextColumn it throw execption why, can anyone know why is th is behaviour thanks in advance.

    Read the article

  • Is private members hacking a defined behaviour ?

    - by ereOn
    Hi, Lets say I have the following class: class BritneySpears { public: int getValue() { return m_value; }; private: int m_value; }; Which is an external library (that I can't change). I obviously can't change the value of m_value, only read it. Even subclassing BritneySpears won't work. What if I define the following class: class AshtonKutcher { public: int getValue() { return m_value; }; public: int m_value; }; And then do: BritneySpears b; // Here comes the ugly hack AshtonKutcher* a = reinterpret_cast<AshtonKutcher*>(&b); a->m_value = 17; // Print out the value std::cout << b.getValue() << std::endl; I know this is a bad practice. But just for curiosity: is this guaranted to work ? Is it a defined behaviour ? Bonus question: Have you ever had to use such an ugly hack ? Thanks !

    Read the article

  • Ruby and public_method_defined? : strange behaviour

    - by aXon
    Hi there Whilst reading through the book "The well grounded Rubyist", I came across some strange behaviour. The idea behind the code is using one's own method_missing method. The only thing I am not able to grasp is, why this code gets executed, as I do not have any Person.all_with_* class methods defined, which in turn means that the self.public_method_defined?(attr) returns true (attr is friends and then hobbies). #!/usr/bin/env ruby1.9 class Person PEOPLE = [] attr_reader :name, :hobbies, :friends def initialize(mame) @name = name @hobbies = [] @friends = [] PEOPLE << self end def has_hobby(hobby) @hobbies << hobby end def has_friend(friend) @friends << friend end def self.method_missing(m,*args) method = m.to_s if method.start_with?("all_with_") attr = method[9..-1] if self.public_method_defined?(attr) PEOPLE.find_all do |person| person.send(attr).include?(args[0]) end else raise ArgumentError, "Can't find #{attr}" end else super end end end j = Person.new("John") p = Person.new("Paul") g = Person.new("George") r = Person.new("Ringo") j.has_friend(p) j.has_friend(g) g.has_friend(p) r.has_hobby("rings") Person.all_with_friends(p).each do |person| puts "#{person.name} is friends with #{p.name}" end Person.all_with_hobbies("rings").each do |person| puts "#{person.name} is into rings" end The output is is friends with is friends with is into rings which is really understandable, as there is nothing to be executed.

    Read the article

  • Override java methods without affecting parent behaviour

    - by Timmmm
    suppose I have this classes (sorry it's kind of hard to think of a simple example here; I don't want any "why would you want to do that?" answers!): class Squarer { public void setValue(int v) { mV = v; } public int getValue() { return mV; } private int mV; public void square() { setValue(getValue() * getValue()); } } class OnlyOddInputsSquarer extends Squarer { @Override public void setValue(int v) { if (v % 2 == 0) { print("Sorry, this class only lets you square odd numbers!") return; } super.setValue(v); } } auto s = new OnlyOddInputsSquarer(); s.setValue(3); s.square(); This won't work. When Squarer.square() calls setValue(), it will go to OnlyOddInputsSquarer.setValue() which will reject all its values (since all squares are even). Is there any way I can override setValue() so that all the functions in Squarer still use the method defined there? PS: Sorry, java doesn't have an auto keyword you haven't heard about! Wishful thinking on my part.

    Read the article

  • Click behaviour - Difference in IE and FF ?!

    - by OlliD
    Hey folks, i just came to the conclusion that a project i am currently working on might have a "logical" error in functionality. Currently I'am using server technology with PHP/MySQL and JQuery. Within the page there's a normal link reference with tag <a href="contentpage?page=xxx">next step</a> The pain point now seems to be the given jquery click event on the same element. The intension was to save the (current) content of the page (- form elements) via another php script using the php session command. For any reason, IE can handle the click event of Jquery right before executing the standard html command, that reloads the current page again with the new page parameter. By using FF the behaviour is different. I assume, that FF first execute the html command and afterwards execute the javascript code which handles the click event. Therefore the resultset here is wrong respectivly empty. My question now is whether you made the same experience and how you handled / wordarrounded this problem. I'd be thankful fur any of your tips or further feedback. Maybe you also have a solution on how to rethink about the current architecture. Regards, Oliver

    Read the article

  • Unexpected behaviour of Process.MainWindowHandle

    - by Ed Guiness
    I've been trying to understand Process.MainWindowHandle. According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window." (Emphasis added) But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above. To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms. Here's the interesting part of this test app... IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd != oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS. Perhaps I've misunderstood the documentation. Can anyone shed light?

    Read the article

  • (closed) nodejs responding an image (via pipe and response.end()) leads into strange behaviour

    - by johannesboyne
    What the Problem was: I had 2 different writeStreams! If WriteStram#1 is closed, the second should be closed too and then it all should be piped... BUT node is asynchronious so while one has been closed, the other one hasn't. Even the stream.end() was called... well you always should wait for the close event! thx guys for your help! I am at my wit's end. I used this code to pipe an image to my clients: req.pipe(fs.createReadStream(__dirname+'/imgen/cached_images/' + link).pipe(res)) it does work but sometimes the image is not transferred completely. But no error is thrown neither on client side (browser) nor on server side (node.js). My second try was var img = fs.readFileSync(__dirname+'/imgen/cached_images/' + link); res.writeHead(200, { 'Content-Type' : 'image/png' }); res.end(img, 'binary'); but it leads to the same strange behaviour... Does anyone got a clue for me? Regards! (abstracted code...) var http = require('http'); http.createServer(function (req, res) { Imgen.generateNew( 'virtualtwins/www_leonardocampus_de/overview/28', 'www.leonardocampus.de', 'overview', '28', null, [], [], function (link) { fs.stat(__dirname+'/imgen/cached_images/' + link, function(err, file_info) { if (err) { console.log('err', err); } console.log('file info', file_info.size); res.writeHead(200, 'image/png'); fs.createReadStream(__dirname+'/imgen/cached_images/' + link).pipe(res); }); } ); }).listen(13337, '127.0.0.1'); Imgen.generateNew just creates a new file, saves it to the disk and gives back the path (link)

    Read the article

  • Dumb IE6 resize behaviour - hope it rings some bells with someone

    - by Ollie2893
    Hi, I'm having no end of fun (sic) with jQuery.tabs. The widget is quite crafty in that it turns basic HTML like so <div> <ul> <li>Tab #1</li> ... </ul> <div for panel #1> </div> <div for panel #2> </div> ... </div> into a cute tabbed dialogue. (It does so by restyling the UL and then toggling the "display" attribute for the panel DIVs to show/not show whatever panel is selected.) Now I found that I can spare myself a lot of trouble in my JS project if I insert a scrollable IFRAME into each panel. One usability problem I'm trying to ameliorate is that when the tabbed panel becomes larger than the browser's window, then the user ends up with too many scrollbars. I am trying to avoid this situation by linking the size of the tabbed panel to that of $(window). That is, I trap and process the resize event on $(window). To make my life bearable, all components are relatively sized. This is also true, in particular, of the IFRAMEs (100% width, 100% height). The only exception are the panel DIVs, which are of fixed height (in px). And this is the only dimension css attribute that I manipulate during my resize action. All of this works a treat in FF and Chrome, but IE6 is doing something rather cute: So long as I do not affect the width of the browser window (but only change its height), only the panel DIV changes in height; the IFRAME contained will not change. As a result of this behaviour, it is not possible to shorten the tabbed panel below the height of the IFRAME. I can lengthen the DIV, yes. But the IFRAME will not fill the panel in that case. All becomes good the moment I make the slightest change to the width of the browser window. In that moment, the IFRAME expands to catch up with the extended DIV or DIV and IFRAME contract in tandem. Bizarre. I inserted useless CSS instructions like "position: relative" and "zoom: 1". Also nudged the display with "display: block". No joy so far. Any ideas? Thanks.

    Read the article

  • IsAuthenticated is false! weird behaviour + review question

    - by Naor
    This is the login function (after I validate user name and password, I load user data into "user" variable and call Login function: public static void Login(IUser user) { HttpResponse Response = HttpContext.Current.Response; HttpRequest Request = HttpContext.Current.Request; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserId.ToString(), DateTime.Now, DateTime.Now.AddHours(12), false, UserResolver.Serialize(user)); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); cookie.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(cookie); string redirectUrl = user.HomePage; Response.Redirect(redirectUrl, true); } UserResolver is the following class: public class UserResolver { public static IUser Current { get { IUser user = null; if (HttpContext.Current.User.Identity.IsAuthenticated) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; user = Desrialize(ticket.UserData); } return user; } } public static string Serialize(IUser user) { StringBuilder data = new StringBuilder(); StringWriter w = new StringWriter(data); string type = user.GetType().ToString(); //w.Write(type.Length); w.WriteLine(user.GetType().ToString()); StringBuilder userData = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(user.GetType()); serializer.Serialize(new StringWriter(userData), user); w.Write(userData.ToString()); w.Close(); return data.ToString(); } public static IUser Desrialize(string data) { StringReader r = new StringReader(data); string typeStr = r.ReadLine(); Type type=Type.GetType(typeStr); string userData = r.ReadToEnd(); XmlSerializer serializer = new XmlSerializer(type); return (IUser)serializer.Deserialize(new StringReader(userData)); } } And the global.asax implements the following: void Application_PostAuthenticateRequest(Object sender, EventArgs e) { IPrincipal p = HttpContext.Current.User; if (p.Identity.IsAuthenticated) { IUser user = UserResolver.Current; Role[] roles = user.GetUserRoles(); HttpContext.Current.User = Thread.CurrentPrincipal = new GenericPrincipal(p.Identity, Role.ToString(roles)); } } First question: Am I do it right? Second question - weird thing! The user variable I pass to Login has 4 members: UserName, Password, Name, Id. When UserResolver.Current executed, I got the user instance. I descided to change the user structure - I add an array of Warehouse object. Since that time, when UserResolver.Current executed (after Login), HttpContext.Current.User.Identity.IsAuthenticated was false and I couldn't get the user data. When I removed the Warehouse[] from user structure, it starts to be ok again and HttpContext.Current.User.Identity.IsAuthenticated become true after I Login. What is the reason to this weird behaviour?

    Read the article

  • Strange behaviour with mediaplayer and seekTo

    - by Mathias Lin
    I'm implementing a custom video player because I need custom video controls. I have an app with only one activity, which on startup shall start playing a video right away. Now, the problem I have is: I don't want the video to start from the beginning, but from a later position. Therefore I do a seekTo(16867). Since seekTo is asynchronous, I place the start call of the mediaplayer (player.start()) in the onSeekComplete of the onSeekCompleteListener. The strange behaviour I experience though is that I can see/hear the video playing from the beginning for a few millisecs before it actually plays from/jumps to the position I seeked to. But - on the other hand - the Log output I call before the player.start returns the correct position 16867, where I seeked to. Below is the relevant code section, the complete class is at http://pastebin.com/jqAAFsuX (I'm on Nexus One / 2.2 StageFright) private void playVideo(String url) { try { btnVideoPause.setEnabled(false); if (player==null) { player=new MediaPlayer(); player.setScreenOnWhilePlaying(true); } else { player.stop(); player.reset(); } url = "/sdcard/myapp/main/videos/main.mp4"; // <--- just for test purposes hardcoded here now player.setDataSource(url); player.setDisplay(holder); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setOnCompletionListener(this); player.setOnPreparedListener(this); player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { public void onSeekComplete(MediaPlayer mediaPlayer) { Log.d("APP", "current pos... "+ player.getCurrentPosition() ); player.start(); // <------------------ start video on seek completed player.setOnSeekCompleteListener(null); } }); player.prepareAsync(); } catch (Throwable t) { Log.e(TAG, "Exception in btnVideoPause prep", t); } } public void onPrepared(MediaPlayer mediaplayer) { width=player.getVideoWidth(); height=player.getVideoHeight(); if (width!=0 && height!=0) { holder.setFixedSize(width, height); progressBar.setProgress(0); progressBar.setMax(player.getDuration()); player.seekTo(16867); // <------------------ seeking to position } btnVideoPause.setEnabled(true); }

    Read the article

  • Different behaviour using unidirectional or bidirectional relation

    - by sinuhepop
    I want to persist a mail entity which has some resources (inline or attachment). First I related them as a bidirectional relation: @Entity public class Mail extends BaseEntity { @OneToMany(mappedBy = "mail", cascade = CascadeType.ALL, orphanRemoval = true) private List<MailResource> resource; private String receiver; private String subject; private String body; @Temporal(TemporalType.TIMESTAMP) private Date queued; @Temporal(TemporalType.TIMESTAMP) private Date sent; public Mail(String receiver, String subject, String body) { this.receiver = receiver; this.subject = subject; this.body = body; this.queued = new Date(); this.resource = new ArrayList<>(); } public void addResource(String name, MailResourceType type, byte[] content) { resource.add(new MailResource(this, name, type, content)); } } @Entity public class MailResource extends BaseEntity { @ManyToOne(optional = false) private Mail mail; private String name; private MailResourceType type; private byte[] content; } And when I saved them: Mail mail = new Mail("[email protected]", "Hi!", "..."); mail.addResource("image", MailResourceType.INLINE, someBytes); mail.addResource("documentation.pdf", MailResourceType.ATTACHMENT, someOtherBytes); mailRepository.save(mail); Three inserts were executed: INSERT INTO MAIL (ID, BODY, QUEUED, RECEIVER, SENT, SUBJECT) VALUES (?, ?, ?, ?, ?, ?) INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE, MAIL_ID) VALUES (?, ?, ?, ?, ?) INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE, MAIL_ID) VALUES (?, ?, ?, ?, ?) Then I thought it would be better using only a OneToMany relation. No need to save which Mail is in every MailResource: @Entity public class Mail extends BaseEntity { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "mail_id") private List<MailResource> resource; ... public void addResource(String name, MailResourceType type, byte[] content) { resource.add(new MailResource(name, type, content)); } } @Entity public class MailResource extends BaseEntity { private String name; private MailResourceType type; private byte[] content; } Generated tables are exactly the same (MailResource has a FK to Mail). The problem is the executed SQL: INSERT INTO MAIL (ID, BODY, QUEUED, RECEIVER, SENT, SUBJECT) VALUES (?, ?, ?, ?, ?, ?) INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE) VALUES (?, ?, ?, ?) INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE) VALUES (?, ?, ?, ?) UPDATE MAILRESOURCE SET mail_id = ? WHERE (ID = ?) UPDATE MAILRESOURCE SET mail_id = ? WHERE (ID = ?) Why this two updates? I'm using EclipseLink, will this behaviour be the same using another JPA provider as Hibernate? Which solution is better?

    Read the article

  • C strange array behaviour

    - by LukeN
    After learning that both strncmp is not what it seems to be and strlcpy not being available on my operating system (Linux), I figured I could try and write it myself. I found a quote from Ulrich Drepper, the libc maintainer, who posted an alternative to strlcpy using mempcpy. I don't have mempcpy either, but it's behaviour was easy to replicate. First of, this is the testcase I have #include <stdio.h> #include <string.h> #define BSIZE 10 void insp(const char* s, int n) { int i; for (i = 0; i < n; i++) printf("%c ", s[i]); printf("\n"); for (i = 0; i < n; i++) printf("%02X ", s[i]); printf("\n"); return; } int copy_string(char *dest, const char *src, int n) { int r = strlen(memcpy(dest, src, n-1)); dest[r] = 0; return r; } int main() { char b[BSIZE]; memset(b, 0, BSIZE); printf("Buffer size is %d", BSIZE); insp(b, BSIZE); printf("\nFirst copy:\n"); copy_string(b, "First", BSIZE); insp(b, BSIZE); printf("b = '%s'\n", b); printf("\nSecond copy:\n"); copy_string(b, "Second", BSIZE); insp(b, BSIZE); printf("b = '%s'\n", b); return 0; } And this is its result: Buffer size is 10 00 00 00 00 00 00 00 00 00 00 First copy: F i r s t b = 46 69 72 73 74 00 62 20 3D 00 b = 'First' Second copy: S e c o n d 53 65 63 6F 6E 64 00 00 01 00 b = 'Second' You can see in the internal representation (the lines insp() created) that there's some noise mixed in, like the printf() format string in the inspection after the first copy, and a foreign 0x01 in the second copy. The strings are copied intact and it correctly handles too long source strings (let's ignore the possible issue with passing 0 as length to copy_string for now, I'll fix that later). But why are there foreign array contents (from the format string) inside my destination? It's as if the destination was actually RESIZED to match the new length.

    Read the article

  • Strange behaviour on postback in ASP.NET

    - by C-King
    I'm working on a website with a login form. To log in, a postback is used to an OnClick handler in the codebehind. Somehow, the value returned from the Text-property of the username and password textboxes is ten times the value I entered, separated by commas. I checked my entire code for double ID's (which seems to be the most common problem causing this behaviour), but I found each ID defined only once. In the ASPX file I have this: <asp:Label ID="lblFeedback" ForeColor="Red" Font-Bold="true" runat="server" Visible="false" /><br /> <asp:Panel ID="pnlLogin" runat="server"> <table style="border-style: none;"> <tr> <td> <asp:Label ID="lblUsername" AssociatedControlID="txtUsername" runat="server" /> </td> <td> <asp:TextBox ID="txtUsername" runat="server" /><br /> </td> </tr> <tr> <td> <asp:Label ID="lblPassword" AssociatedControlID="txtPassword" runat="server" /> </td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="password" /><br /> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" /> </td> </tr> </table> </asp:Panel> The OnClick handler in the Codebehind: protected void btnLogin_Click(object sender, EventArgs e) { string username = Util.Escape(txtUsername.Text); string password = Util.Escape(txtPassword.Text); WebsiteUser user = WebsiteUser.Create(username, password); if (user != null) { //Set some session variables and redirect to user profile } else { lblFeedback.Text = Localizer.Translate("INVALID_LOGIN"); lblFeedback.ForeColor = Color.Red; lblFeedback.Visible = true; pnlLogin.Visible = true; } } The website is running on ASP.NET 2.0 on ISS 5.1 (Win XP Pro)

    Read the article

  • Warning: comparison with string literals results in unspecified behaviour

    - by nunos
    So I starting the project of writing a simplified sheel for linux in c. I am not at all proficient with c nor with Linux that's exactly the reason I decided it would be a good idea. Starting with the parser, I have already encountered some problems. The code should be straightforward that's why I didn't include any comments. I am getting a warning with gcc: "comparison with string literals results in unspecified behaviour" at the lines commented with "WARNING HERE" (see code below). I have no idea why this causes an warning, but the real problem is that even though I am comparing an "<" to an "<" is doesn't get inside the if... I am looking for an answer for the problem explained, however if there's something that you see in the code that should be improved please say so. Just take in mind I am not that proficient and that this is still a work in progress (or better yet, a work in start). Thanks in advance. #include <stdio.h> #include <unistd.h> #include <string.h> typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[100]; int i = 0; arg = strtok(cmd_line, " \n"); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " \n"); i++; } int num_elems = i; cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; int iarg = 0; for (i = 0; i < num_elems; i++) { if (args[i] == "&") //WARNING HERE return -1; else if (args[i] == "<") //WARNING HERE if (args[i+1] != NULL) cmd_info->infile = args[i+1]; else return -1; else if (args[i] == ">") //WARNING HERE if (args[i+1] != NULL) cmd_info->outfile = args[i+1]; else return -1; else cmd_info->arg[iarg++] = args[i]; } cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } int main(int argc, char* argv[]) { char cmd_line[100]; Command_Info cmd_info; printf(">>> "); fgets(cmd_line, 100, stdin); parse_cmd(cmd_line, &cmd_info); print_cmd(&cmd_info); return 0; }

    Read the article

  • QuickBox2D poly behaviour vs box or circle

    - by Ben Kanizay
    Hi I've played a little with Box2D before and have just started using QuickBox2D which makes things heaps easier. I am however getting different behaviour with a specific poly shape than I am with a box. All other properties are the same. I've included 3 simple examples and their source below. What I really want to work is Example 1 with both objects as poly. As you can see, it seems like the 'paddle' poly is the one that's failing - the 'ball' (whether it's a poly or circle) just falls straight through it instead of bouncing off as it does with a box 'paddle' object. Would appreciate some help or insight. As I can only post one line at this stage, the swf previews of the 3 examples can be seen here Example 1 source: package { import com.actionsnippet.qbox.QuickBox2D; import com.actionsnippet.qbox.QuickObject; import flash.display.MovieClip; public class Eg1 extends MovieClip { private var sim:QuickBox2D; private var paddle:QuickObject; private var ball:QuickObject; public function Eg1() { this.sim = new QuickBox2D(this); this.paddle = this.sim.addPoly({ x:13, y:19, angle:0, density:0, draggable:false, isBullet:true, verts:[[-3.84,-0.67,-2.84,-1,-2.17,-0.33,2.17,-0.33,2.84,-1,3.84,-0.67,2.84,1,-2.51,1]] }); this.ball = this.sim.addPoly({ x:13, y:1, restitution:1, friction:1, draggable:false, isBullet:true, verts:[[-0.34,-1,0.34,-1,0.67,-0.33,0.67,0.33,0.34,1,-0.34,1,-0.67,0.33,-0.67,-0.33]] }); this.sim.start(); } }} Example 2 source: package { import com.actionsnippet.qbox.QuickBox2D; import com.actionsnippet.qbox.QuickObject; import flash.display.MovieClip; public class Eg2 extends MovieClip { private var sim:QuickBox2D; private var paddle:QuickObject; private var ball:QuickObject; public function Eg2() { this.sim = new QuickBox2D(this); this.paddle = this.sim.addBox({ x:13, y:19, angle:0, density:0, draggable:false, isBullet:true, width:8 }); this.ball = this.sim.addPoly({ x:13, y:1, restitution:1, friction:1, draggable:false, isBullet:true, verts:[[-0.34,-1,0.34,-1,0.67,-0.33,0.67,0.33,0.34,1,-0.34,1,-0.67,0.33,-0.67,-0.33]] }); this.sim.start(); } }} Example 3 source: package { import com.actionsnippet.qbox.QuickBox2D; import com.actionsnippet.qbox.QuickObject; import flash.display.MovieClip; public class Eg3 extends MovieClip { private var sim:QuickBox2D; private var paddle:QuickObject; private var ball:QuickObject; public function Eg3() { this.sim = new QuickBox2D(this); this.paddle = this.sim.addPoly({ x:13, y:19, angle:0, density:0, draggable:false, isBullet:true, verts:[[-3.84,-0.67,-2.84,-1,-2.17,-0.33,2.17,-0.33,2.84,-1,3.84,-0.67,2.84,1,-2.51,1]] }); this.ball = this.sim.addCircle({ x:13, y:1, restitution:1, friction:1, draggable:false, isBullet:true, radius:1 }); this.sim.start(); } }}

    Read the article

  • JPA behaviour...

    - by Marcel
    Hi I have some trouble understanding a JPA behaviour. Mabye someone could give me a hint. Situation: Product entity: @Entity public class Product implements Serializable { ... @OneToMany(mappedBy="product", fetch=FetchType.EAGER) private List<ProductResource> productResources = new ArrayList<ProductResource>(); .... public List<ProductResource> getProductResources() { return productResources; } public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof Product)) return false; Product p = (Product) obj; return p.productId == productId; } } Resource entity: @Entity public class Resource implements Serializable { ... @OneToMany(mappedBy="resource", fetch=FetchType.EAGER) private List<ProductResource> productResources = new ArrayList<ProductResource>(); ... public void setProductResource(List<ProductResource> productResource) { this.productResources = productResource; } public List<ProductResource> getProductResources() { return productResources; } public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof Resource)) return false; Resource r = (Resource) obj; return (long)resourceId==(long)r.resourceId; } } ProductResource Entity: This is a JoinTable (association class) with additional properties (amount). It maps Product and Resources. @Entity public class ProductResource implements Serializable { ... @JoinColumn(nullable=false, updatable=false) @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST) private Product product; @JoinColumn(nullable=false, updatable=false) @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST) private Resource resource; private int amount; public void setProduct(Product product) { this.product = product; if(!product.getProductResources().contains((this))){ product.getProductResources().add(this); } } public Product getProduct() { return product; } public void setResource(Resource resource) { this.resource = resource; if(!resource.getProductResources().contains((this))){ resource.getProductResources().add(this); } } public Resource getResource() { return resource; } ... public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof ProductResource)) return false; ProductResource pr = (ProductResource) obj; return (long)pr.productResourceId == (long)productResourceId; } } This is the Session Bean (running on glassfish). @Stateless(mappedName="PersistenceManager") public class PersistenceManagerBean implements PersistenceManager { @PersistenceContext(unitName = "local_mysql") private EntityManager em; public Object create(Object entity) { em.persist(entity); return entity; } public void delete(Object entity) { em.remove(em.merge(entity)); } public Object retrieve(Class entityClass, Long id) { Object entity = em.find(entityClass, id); return entity; } public void update(Object entity) { em.merge(entity); } } I call the session Bean from a java client: public class Start { public static void main(String[] args) throws NamingException { PersistenceManager pm = (PersistenceManager) new InitialContext().lookup("java:global/BackITServer/PersistenceManagerBean"); ProductResource pr = new ProductResource(); Product p = new Product(); Resource r = new Resource(); pr.setProduct(p); pr.setResource(r); ProductResource pr_stored = (ProductResource) pm.create(pr); pm.delete(pr_stored); Product p_ret = (Product) pm.retrieve(Product.class, pr_stored.getProduct().getProductId()); // prints out true ???????????????????????????????????? System.out.println(p_ret.getProductResources().contains(pr_stored)); } } So here comes my problem. Why is the ProductResource entity still in the List productResources(see code above). The productResource tuple in the db is gone after the deletion and I do newly retrieve the Product entity. If I understood right every method call of the client happens in a new persistence context, but here i obviously get back the non-refreshed product object!? Any help is appreciated Thanks Marcel

    Read the article

  • Django stupid mark_safe?

    - by Mark
    I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' />') else: lst.extend(['>', content, '</', tag, '>']) else: lst.append('>') return mark_safe(''.join(lst)) Which worked great, but then I read this article on efficient string concatenation (I know it doesn't really matter for this, but I wanted consistency) and decided to update my script: def html_tag(tag, body=None, close=True, attrs={}): s = StringIO() s.write('<%s'%tag) for key, val in attrs.iteritems(): s.write(' %s="%s"' % (key, escape_html(val))) if close: if body is None: s.write(' />') else: s.write('>%s</%s>' % (body, tag)) else: s.write('>') return mark_safe(s.getvalue()) But now my HTML get escaped when I try to render it from my template. Everything else is exactly the same. It works properly if I replace the last line with return mark_safe(unicode(s.getvalue())). I checked the return type of s.getvalue(). It should be a str, just like the first function, so why is this failing?? Also fails with SafeString(s.getvalue()) but succeeds with SafeUnicode(s.getvalue()). I'd also like to point out that I used return mark_safe(s.getvalue()) in a different function with no odd behavior.

    Read the article

  • Java OutOfMemoryError message changes when trying to create Arrays of different sizes

    - by Gordon
    In the question by DKSRathore How to simulate the Out Of memory : Requested array size exceeds VM limit some odd behavior was noted when creating an arrays. When creating an array of size Integer.MAX_VALUE an exception with the error java.lang.OutOfMemoryError Requested array size exceeds VM limit was thrown. However when an array was created with a size less than the max but still above the virtual machine memory limit the error message read java.lang.OutOfMemoryError: Java heap space. Testing further I managed to narrow down where the error messages changes. long[] l = new long[2147483645]; exceptions message reads - Requested array size exceeds VM limit long[] l = new long[2147483644]; exceptions message reads - Java heap space errors I increased my virtual machine memory and still produced the same result. Has anyone any idea why this happens? Some extra info: Integer.MAX_VALUE = 2147483647. Edit: Here's the code I used to find the value, might be helpful. int max = Integer.MAX_VALUE; boolean done = false; while (!done) { try { max--; // Throws an error long[] l = new long[max]; // Exit if an error is no longer thrown done = true; } catch (OutOfMemoryError e) { if (!e.getMessage().contains("Requested array size exceeds VM limit")) { System.out.println("Message changes at " + max); done = true; } } }

    Read the article

  • Why is my HDD not showing up?

    - by Mike
    I'm on Windows 7, got a new 2 TiB NON-external hard disk. When I plug it in it doesn't show up on the Disk Management list in the Computer Management window (that you get by right-clicking My Computer and selecting "Manage"). At first I thought it was broken, but I could see it using a friend's computer. I've run a full disk scan using the official tool from Western Digital, no problems. I've formatted it and partitioned it at another friends place, I've even encrypted the disk fully without any problems, then mounted it and placed a text file on it with the word "hello" inside and saved the file. When I boot my own computer the disk shows up in BIOS. So the disk is not broken. I've tried changing what SATA slot on the motherboard I stick it in. Makes no difference. After all this: Why won't my Windows 7 discover the disk???

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >