text
stringlengths
8
267k
meta
dict
Q: Connecting to .NET COM app from .NET COM client I'm having trouble with something that should be brain-dead simple. I am writing a COM client in .NET that will eventually talk to an old-style C++ COM interface when the server code is written. In the meantime, I've written an unsigned WPF .NET application and implemented the same interface - same IID, different ProgID and CLSID - so I'll have a harness I can test with. In theory, all I will need to do is switch my reference from one namespace to another and change the concrete class on the new statement and everything else will remain the same. I'm envisioning that when I CoCreate the CLSID, it will bring up the application with its GUI and my client can do its calls OLE Automation-style from there and see the effects on the screen. Only that's not what's happening. In Add References for my client application, I see the typelib for my test harness in the COM list, but it refuses to let me add the reference because it detects that it is a .NET type library and expects a .NET reference. If I reference it as a project or browse to it as an EXE, it apparently loads the EXE in-process as if it were a DLL and uses the COM classes without actually activating it out of process. I figured anything I did with a .NET COM application would work similarly to a C++ COM application. I'm not sure what my options are at this point. Am I facing a hard limitation or are there [attributes] that affect this behavior? (It has admittedly been a couple of years since I did really seriously detailed COM interop and I have an uneasy feeling that this is something really simple that I've since forgotten.) Lupestro A: Sounds like what you need is out-of-proc COM object. You can create COM+ objects inplemented in .Net and then instantiate them out-of-proc. This article explains how to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: another css 100% height question Sorry but I can't get this to work. Should be a quick answer. My html is laid out like so: <html> <header> ... </header> <body> <div class = "background"></div> <div class = "content"> ... </div> <body> </html> The I want the background div to simply place a 1000px background colour down the entire length of the page. The content is then padded 40px on each side, inside this background colour. The css is like so: body { width:1000px; margin-left:auto; margin-right:auto; } .background { position:absolute; top:0px; width:1000px; height:100%; } .content { min-height:100%; padding-left:40px; padding-right:40px; } I thought it worked like so... The body div would expand to hold the min-height of the .content div. This means that 100% height of the .background div would fill the entire body and so the length of the page. However it does not. It only fills the window height. Where am I going wrong? Thanks A: As topek guessed, this will do it: html, body{ height:100% } The reason this works is because percentage CSS heights only work if the parent element has a height defined on it. By adding the above, you're giving .background's parents a height. Update: based on OP's comment, here's how you would get the .background div to always appear to fill the viewport: html, body { height: 100%; padding: 0; margin: 0; } /* Fixed element that takes up entire viewport */ .background { position: fixed; z-index: 1; top: 0; left: 0; width: 100%; height: 100%; } /* Content that stacks above .background */ .content { position: relative; z-index: 2; } As .content grows larger than the viewport and the user scrolls, the fixed position of .background will keep it always in view. And of course, a handy example. A: All you need is: body, html { height:100% } Then specify height:100%; any DIV you want to have full height. BTW - 1000px wide is a bad unit to use. People with 1024 wide screens will get horizontal scrollbars. Better to stick to 980 or less. 960 is good because it can be divided by many factors. A: You should put bg into html or body elements as the first choices. html { background: url("bg.jpg") no-repeat top center; } or body { background: url("bg.jpg") no-repeat top center; } Fixed: background: url("bg.jpg") no-repeat top center fixed; /* And bg will stay in fixed position */ A: I think this is what you're looking for. http://jsfiddle.net/sg3s/GxRcp/ The key in this little example is the position: fixed; for .background so that it is kept in the screen while scrolling. If you don't really want to do this and want the background to expand ARROUND the content just make it a normal / relatively positioned element, and wrap it arround .content... If you give a more acurate description of the layout you're trying to create (and maybe why in such a way) we may be able to help you better. Btw, in your example html there is an error, header should be head.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django -- Can't get static CSS files to load I'm running Django's development server (runserver) on my local machine (Mac OS X) and cannot get the CSS files to load. Here are the relevant entries in settings.py: STATIC_ROOT = '/Users/username/Projects/mysite/static/' STATIC_URL = '/static/' STATICFILES_DIRS = ( '/Users/thaymore/Projects/mysite/cal/static', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #'django.contrib.staticfiles.finders.DefaultStorageFinder', ) INSTALLED_APPS = ( # other apps ... 'django.contrib.staticfiles', ) In my views.py I'm requesting the context: return render_to_response("cal/main.html",dict(entries=entries),context_instance=RequestContext(request)) And in my template the {{ STATIC_URL }} renders correctly: <link type="text/css" href="{{ STATIC_URL }}css/main.css" /> Turns into: <link type="text/css" href="/static/css/main.css"/> Which is where the file is actually located. I also ran collectstatic to make sure all the files were collected. I also have the following lines in my urls.py: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() I'm new to Django so am probably missing something simple -- would appreciate any help. A: Read this carefully: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/ Is django.contrib.staticfiles in your INSTALLED_APPS in settings.py? Is DEBUG=False? If so, you need to call runserver with the --insecure parameter: python manage.py runserver --insecure collectstatic has no bearing on serving files via the development server. It is for collecting the static files in one location STATIC_ROOT for your web server to find them. In fact, running collectstatic with your STATIC_ROOT set to a path in STATICFILES_DIRS is a bad idea. You should double-check to make sure your CSS files even exist now. A: Another simple thing to try is to stop, and then restart the server e.g. $ python manage.py runserver I looked into the other answers, but restarting the server worked for me. A: For recent releases of Django, You have to configure static files in settings.py as, STATIC_URL = '/static/' # the path in url STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] and use it with static template tag, {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> A: Are these missing from your settings.py? I am pasting one of my project's settings: TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages") Also, this is what I have in my urls.py: urlpatterns += patterns('', ( r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static'} )) A: added PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "static"), ) and removed STATIC_ROOT from settings.py, It worked for me A: Add the following code to your settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] After that, create the static folder at the root directory of your project. To load the static files on templates use: {% load static %} <img src="{% static "images/index.jpeg" %}" alt="My image"/> A: DEBUG = True in my local settings did it for me. A: These steps work for me, just see Load Static Files (CSS, JS, & Images) in Django I use Django 1.10. * *create a folder static on the same level of settings.py, my settings.py's path is ~/djcode/mysite/mysite/settings.py, so this dir is ~/djcode/mysite/mysite/static/; *create two folders static_dirs and static_root in static, that's ~/djcode/mysite/mysite/static/static_dirs/ and ~/djcode/mysite/mysite/static/static_root/; *write settings.py like this: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static', 'static_root') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'mysite', 'static', 'static_dirs'), ) *do this command $ python manage.py collectstatic in shell; *create a folder css in static_dirs and put into your own .css file, your css file' path is ~/djcode/mysite/mysite/static/static_dirs/css/my_style.css; *change <link> tag in .html file: <link rel="stylesheet" type="text/css" href="{% static 'css/my_style.css' %}">, Finally this link's path is http://192.168.1.100:8023/static/css/my_style.css Bingo! A: You had same path in STATICFILES_DIRS AND STATIC_ROOT, I ran into the same issue and below was the exception - ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting For local you don't need STATICFILES_DIRS, as anyway you don't need to run collectstatic. Once you comment it, it should work fine. A: Have you added into your templates: {% load staticfiles %} This loads what's needed, but for some reason I have experienced that sometimes work without this... ??? A: I tried this model and it worked. Changes in settings as per the django project created with shell "django-admin.py startproject xxx"# here xxx is my app name modify the folder as below structure loading our static files to run on server Structure of xxx is: > . > |-- manage.py > |-- templates > | `-- home.html > `-- test_project > |-- __init__.py > |-- settings.py > |-- static > | |-- images > | | `-- 01.jpg > | |-- style.css > |-- urls.py > `-- wsgi.py - modifications in Settings.py import os INSTALLED_APPS = ( 'xxx',# my app is to be load into it) STATIC_ROOT = '' STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(__file__) TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, '../templates'),)#include this - modifications in urls.py from django.conf.urls import patterns, include, url from django.views.generic import TemplateView class DirectTemplateView(TemplateView): extra_context = None def get_context_data(self, **kwargs): context = super(self.__class__, self).get_context_data(**kwargs) if self.extra_context is not None: for key, value in self.extra_context.items(): if callable(value): context[key] = value() else: context[key] = value return context urlpatterns = patterns('', url(r'^$', DirectTemplateView.as_view(template_name="home.html")), ) - home.html <html> <head> <link href="{{STATIC_URL}}style.css" rel="stylesheet" type="text/css"> </head> <body> <h1>This is home for some_app</h1> <img src="{{STATIC_URL}}/images/01.jpg" width=150px;height=150px; alt="Smiley "> </body> </html> A: I had to use STATICFILES_DIRS = ( '/home/USERNAME/webapps/django/PROJECT/static/', ) That helped me. A: See if your main application (where the static directory is located) is included in your INSTALLED_APPS. Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting. A: Add this "django.core.context_processors.static", context processor in your settings.py TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.static", ) A: You can just set STATIC_ROOT depending on whether you are running on your localhost or on your server. To identify that, refer to this post. And you can rewrite you STATIC_ROOT configuration as: import sys if 'runserver' in sys.argv: STATIC_ROOT = '' else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' A: If you set DEBUG=FALSE you need to do follow steps In your urls.py file: add this line from django.views.static import serve url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), A: I have the same issue (ununtu 16.04 server). This helped me python manage.py collectstatic --noinput A: add following in settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') A: Two most Basis points to be noted for running Static files in Django Application are - Declare static file path in your settings.py file STATIC_URL = '/static/' Another important parameter is the web page in which you are using static keyword, you need to load the static files. {% load static %} A: Go to your HTML page load static by {% load static %} Now only mistake I've made was this My code: <img src="**{% static** "images/index.jpeg" %}" alt="My image"> Updated: <img src=**"{% static 'images/index.jpeg' %}' alt="My image"**> You get it right A: I had same issue check your settings.py and make sure STATIC_URL = '/static/' in my case first / at the beginning was missing and that was causing all static files not to work
{ "language": "en", "url": "https://stackoverflow.com/questions/7574759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: MySQL ENUM column won't match quoted values after import to new machine Recently I've imported a new database to develop on my local machine, however it doesn't work: the ENUM column only works when the variable is sent without quotation marks. Here's an example: mysql.local>select count(*) from psh_products where active = 1; +----------+ | count(*) | +----------+ | 72782 | +----------+ 1 row in set (0.04 sec) mysql.local>select count(*) from psh_products where active = '1'; +----------+ | count(*) | +----------+ | 0 | +----------+ 1 row in set (0.00 sec) In case you're wondering about the table structure: CREATE TABLE `psh_products` ( `productID` int(12) unsigned NOT NULL AUTO_INCREMENT, `catID` int(2) unsigned NOT NULL, `main_sku` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `sku` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `shortsku` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `upc` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` text COLLATE utf8_unicode_ci NOT NULL, `quantity` int(2) unsigned NOT NULL, `buy_now` decimal(11,2) NOT NULL, `seller_cost` decimal(11,2) NOT NULL, `cdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `codedir` varchar(2) COLLATE utf8_unicode_ci NOT NULL, `code` varchar(32) COLLATE utf8_unicode_ci NOT NULL, `basic_colorID` int(2) unsigned NOT NULL, `manu_colorID` int(2) unsigned NOT NULL, `brandID` int(2) unsigned NOT NULL, `matID` int(2) unsigned NOT NULL, `sizeID` int(2) unsigned NOT NULL, `size_sID` int(2) unsigned NOT NULL, `styleID` int(2) unsigned NOT NULL, `featID` int(2) unsigned NOT NULL, `occID` int(2) unsigned NOT NULL, `widthID` int(2) unsigned NOT NULL, `width_sID` int(2) unsigned NOT NULL, `genderID` int(2) unsigned NOT NULL, `gender_sID` int(2) unsigned NOT NULL, `hits` int(2) unsigned NOT NULL, `active` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', `tags` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `tmp_img` varchar(250) COLLATE utf8_unicode_ci NOT NULL, `imgact` enum('again','flip','resize','moderated','badimg','badimgm','badimga') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'moderated', `status` enum('new','moderated') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'moderated', `quanflag` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', `deleted` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', PRIMARY KEY (`productID`), KEY `idx_cid` (`catID`), KEY `idx_bid` (`brandID`), KEY `idx_act` (`active`), KEY `idx_act_hits` (`active`,`hits`), KEY `idx_wid` (`widthID`), KEY `idx_sid` (`sizeID`), KEY `idx_styleid` (`styleID`), KEY `idx_sku` (`sku`), KEY `idx_msku` (`main_sku`), KEY `idx_matid` (`matID`), KEY `idx_cid_mstyleid` (`catID`,`featID`), KEY `idx_shortsku` (`shortsku`), KEY `idx_quant` (`quantity`), KEY `idx_quanflag` (`quanflag`), KEY `idx_hits` (`hits`), KEY `idx_act_qua_cat` (`active`,`quantity`,`catID`), KEY `idx_act_qua_cat_sho` (`active`,`quantity`,`catID`,`shortsku`), KEY `idx_bcolor_id` (`basic_colorID`), KEY `idx_mcolor_id` (`manu_colorID`), KEY `idx_cdate` (`cdate`), KEY `idx_deleted` (`deleted`), KEY `occID` (`occID`), KEY `idx_fid` (`featID`), KEY `width_sID` (`width_sID`,`genderID`,`gender_sID`) ) ENGINE=InnoDB AUTO_INCREMENT=72790 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci Any ideas are welcome! A: Note that when you use a numerical value in a query against an enum data type as in your first query, the numerical value is treated as an index, not as one of the enumerated values. So, querying select count(*) from psh_products where active = 1; is really equivalent to select count(*) from psh_products where active = '0'; since '0' is the first item (index 1) in the enumeration. Because of this confusion, the documentation explicilty states "we strongly recommend that you do not use numbers as enumeration values." A: That was my mistake, I did UPDATE psh_products SET ACTIVE = 1 WHERE ...... So the update overwrote the '1''s that were there with 1's.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Get the name of an executable from another project in the solution? I am trying to call one executable from another. Each executable is compiled by its own project and both projects are in the same solution. I found this question, but that only refers to the path of the executable. I'm looking for a way to programmatically retrieve the name of the executable. I have already included 'Project 2' in 'Project 1' so I know that when I run 'Project 1' that the executable from 'Project 2' will be there, so the location isn't an issue; only the name of the executable is. Does anyone know if/how this can be done? Thanks. A: At runtime there is no longer any notion of solutions and projects and Visual Studio and stuff. At runtime you have a file system, files, inside folders, executables. So for example if you have an executable located in c:\foo\bin\Debug\foo.exe trying to read a file in c:\bar\bin\Debug\bar.txt you have to specify the absolute path to this file. Don't think in terms of Visual Studio projects. Think in terms of how your executables will be organized once you ship them to the target computer. You basically have 2 possibilities: * *Use an absolute path to refer to a file (c:\bar\bin\Debug\bar.txt) *Use a relative path (in relation to the current path of the executable) to refer to a file (..\..\..\bar\bin\Debug\bar.txt) A: For a bit of extra reference, a project will usually yield an executable (.exe) or assembly (*.dll) which is usually found in the bin\Debug folder for that project. The name comes from the Assembly name found under the Application tab in the project's properties (in VS2010 at least). Projects that can't be directly started will yield a *.dll file, console or winforms application should yield and *.exe. As for programmatically finding the assembly name, this may be helpful: System.Reflection.AssemblyName.Name property This may also be helpful: How to get the assembly (System.Reflection.Assembly) for a given type in .Net
{ "language": "en", "url": "https://stackoverflow.com/questions/7574761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Expression Engine Channels, Categories and Entries - All with differeny custom fields I have a site with these sections in the top nav: * *About Us *News *Staff *Become a Member Within each top nav item, is X amount of sub sections. eg: About Us * *Who We Are *Industry Stats *Annual Report Then, within each one of those has X amount of sub pages: About Us * *Who We Are * * *Overview * * *Our History * * *Our Objectives The root level top nav items (About Us) will always require the same custom fields. The middle and bottom level pages will generally have the same content, and but will be much different to that of the root level, and so requires a different set of custom fields. I have set the structure up so that the root items are the channels, the middle are categories, and the lower levels are just 'entries'. My problem now, is that using a 'channel field group' on the root channel obviously filters through all categories and entries associated. So when I go to edit or publish a category landing or entry page - i am stuck by being shown the custom field group for the root landing page. I would like it so that the end user (my client) doesnt have to see a lot of custom fields when they edit or publish a page that isnt at root channel level. How to I set this site up, so that I can pick and choose different field groups on different pages that are within the same channel? A: While you can use custom Publish Page Layouts per channel and per member group, as far I'm aware you can't present 'pages' or entries with varying Publish Layouts. If you're using different templates for levels in your navigation, Blueprints, may be what you're looking for. Blueprints lets you take control of your Publish Layouts [...] It is designed let you create Publish Layouts based on templates. The taxonomy in how way you've architected your navigation and 'pages' is interesting, but not one as a client I would like to maintain or understand. For example, something as simple adding a new top-level section or page of the site should be easy, but with your methodology would require setting up an entirely new channel! Some ExpressionEngine add-ons that may be better suited for your site and still allow you to achieve the customization you desire would be Structure, NavEE or Taxonomy — of course theres always the the native Pages Module as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there an online tool to test all HTTP methods against some public server? Is there an online tool that can help constructing proper HTTP request to to test all HTTP/WEBDAV methods against some public server? By all methods I mean at least the following: * *GET *PUT *DELETE *MERGE *OPTIONS *PROPFIND *MKACTIVITY A: I haven't found any online tool, but WFetch seems to be a good alternative for Windows to construct any kind of custom HTTP request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Faster way to fill a 160x43 byte array from colors of Bitmap class What's the faster way to effectively fill an array of bytes where each byte represents a pixel (black or white: < 125 = black, > 125 = white) from a Bitmap class? I used this for colored images: Better/faster way to fill a big array in C# However now I'm looking for something different (I can even use a single color like Red to fill this, it doesn't matter is just something I should choose), because the array format changed. Any suggestion? Actually I'm using this code, which is obviusly not the best idea for (int x = 0; x < LgLcd.NativeConstants.LGLCD_BMP_WIDTH; ++x) { for (int y = 0; y < LgLcd.NativeConstants.LGLCD_BMP_HEIGHT; ++y) { tmp = bmp.GetPixel(x, y); array[y * LgLcd.NativeConstants.LGLCD_BMP_WIDTH + x] = (byte)((tmp.R == 255 && tmp.G == 255 && tmp.B == 255) ? 0 : 255); //array[y * x] = (byte)0; } } My idea was parallelizing everything (yea, 1 thread per line maybe? (or per column)), it should help I think. EDIT: Ok, first, I need a way to have the possibility to access different bytes of the image at the same time, Brandon Moretz is suggesting maybe the correct way to access bytes with lockbits. I would like to avoid, however, unsafe code. Does Lockbits involves necessarily unsafe code? Second, my idea of parallelization was to use Parallel.For. This method should use the ThreadPool class, which will use an amount of threads not greater than cores of your cpu, and they are pre-allocated. This method will be called a lot of times, so I think it's not a big trouble, because the threadpool will be used a lot after first call. Is what I'm saying correct? A: Is using "unsafe" code blocks an option? You can use LockBits on a Bitmap to get it's BitmapData, then use Scan0 & Stride properties to iterate over it. If it's 255 colors I'm assuming a byte per pixel, so so something like: *( ( ( byte* )bmpData.Scan0 ) + ( y * bmpData.Stride ) + x ) = (byte)((tmp.R == 255 && tmp.G == 255 && tmp.B == 255) ? 0 : 255); A: General approach is to divide the image into regions then process. i.e. you can use: Thread 1) for (int x = 0; x < LGLCD_BMP_WIDTH /2; ++x) { ... } Thread 2) for (int x = LGLCD_BMP_WIDTH / 2; x < LGLCD_BMP_WIDTH; ++x) { ... } where you would have two halves of the image be processed by different threads. You can divide further into 4, 8, etc. pieces as you wish. A thread per line would be excess, as thread creation overhead would overwhelm the benefits by a large margin. A: I found the answer by myself, working with lockbits and Marshal.ReadByte with a really nice and fast result: public void SetPixels(Bitmap image) { byte[] array = Pixels; var data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Parallel.For(0, data.Height, new Action<int>(i => { byte tmp; int pixel4bpp, pixelPerbpp; pixelPerbpp = data.Stride / data.Width; for (pixel4bpp = 0; pixel4bpp < data.Stride; pixel4bpp += pixelPerbpp) { tmp = (byte)(( Marshal.ReadByte(data.Scan0, 0 + (data.Stride * i) + pixel4bpp) + Marshal.ReadByte(data.Scan0, 1 + (data.Stride * i) + pixel4bpp) + Marshal.ReadByte(data.Scan0, 2 + (data.Stride * i) + pixel4bpp) + Marshal.ReadByte(data.Scan0, 3 + (data.Stride * i) + pixel4bpp) ) / pixelPerbpp); array[i * data.Width + (pixel4bpp / pixelPerbpp)] = tmp; } })); image.UnlockBits(data); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TinyMce is not working in Chrome I have TinyMce to compose emails in my asp.net page, it is working fine but in Google Chrome no tools (font size, font name, text color etc for example) are working. They work fine in all other broswers. Kindly guide and help me. Thanks A: Here is a link to a HOWTO. It describes well how the tinymce spellchecker plugin can be configured to use a variety of spellcheckers (located on a server) and what needs to be done to make it work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: E-mail sent with commons-mail is *sometimes* not received. How can I troubleshoot? When I send out an e-mail and it isn't received, how can I figure out what the cause of the problem is? My app sends e-mails through SMTP using the Apache commons-mail library. For testing purposes, I am using the gmail SMTP server. (Our production app uses an internal server on our network). In one case on the test server, I have a batch job that generates 5 e-mails with attachments. Some e-mails are received and others are marked as sent, but never appear in my inbox. There doesn't seem to be a pattern to which e-mails are received and which ones silently vanish. The code that sends and checks for errors looks like this: final Mail mail = ...; //The Mail class is our app's mail object, which provides data used to generate the MIME e-mail and record the results. final MultiPartEmail email = ...; try { email.setSentDate(mail.getDateSent()); email.send(); } catch (EmailException ee) { success = false; mail.setDateSent(null); getLog().error("Mail not sent: ", ee); if (ee.getMessage().indexOf("receiver address required") != -1) { mail.setErrorMessage(ee.getMessage()); getLog().error(mail.toString()); } } In the debugger, I determine that no exception is thrown. My first guess was that the attachment size is too large; but, gmail supposedly supports 25MB attachments, and my largest attachment is 14.3 MB. In some cases when I run the entire batch of 5 e-mails, the e-mail with the largest attachment gets through, and the smaller ones disappear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically Left Justify a number in an Excel document How do I left justify my columns in Excel programmatically in VB? I have a VB program that is writing an excel file based off of certain information. I have tried using: oSheet.Columns.HorizontalAlignment.Left() This works against columns with text. I have multiple columns that are strictly numbers. This function will not work against columns with Numeric Cells. Below is the MissingMemberException I keep getting: Public member 'Left' on type 'Integer' not found. A: Range.HorizontalAlignment is a property that requires an integer constant. Left is xlLeft. xlLeft evaluates to -4131. xlDistributed is -4117, xlRight is -4152, xlCenter is -4108, and xlJustify is -4130. A: HorizontalAlignment should work for both text and numbers. You should specify the value for the alignment though since it is a property. A: Although the @Banjoe answer will work, the documentation specifies the following valid constants for HorizontalAlignment property: xlHAlignCenter xlHAlignCenterAcrossSelection xlHAlignDistributed xlHAlignFill xlHAlignGeneral xlHAlignJustify xlHAlignLeft xlHAlignRight A: I used the following, and it worked great for me: Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Add() objExcel.Cells(1, 1).Value = "Some data" objExcel.Cells(1, 2).Value = "More data" Set objWorksheet = objWorkbook.Worksheets(1) objExcel.Columns(2).Select objExcel.Selection.EntireColumn.HorizontalAlignment = 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7574781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java TCP socket message breaks i have a java client-server app in java, both using the same connection class that contains both send/receive messages. for some reason, some of the messages i send are received in a malformed order: here's the code //set up _in = new BufferedReader(new InputStreamReader(this._socket.getInputStream())); _out = new BufferedWriter(new OutputStreamWriter(this._socket.getOutputStream())); this._socket.setSoTimeout(S_TIMEOUT); public synchronized boolean send(String message){ try { _out.write(message); _out.write(Connection.DELIMITER); _out.flush(); return true; } catch (IOException e) { } return false; } public String receive(){ int c; try { String message = ""; System.out.println("Getting message:"); c = _in.read(); while(c != -1 && c != Connection.DELIMITER) { message += (char) c; c = _in.read(); } if (c == -1) { return null; } return message; } catch (IOException e) { } return null; } some messages, for example "new_order" will might return with "ew_ord". some characters are lost, others are sent separately. this seems odd as its TCP could this be an encoding related issue? Delimiter is (char) 0 socket timeout is 20000 (ie 20 senconds). every 10 seconds i send an empty message to make sure socket does not close EDIT: although it was solved using the Scanner, i must say that the original code worked fine for many messages/various machines for a very long time (a few weeks), and then suddenly failed to work with one specific message on one specific machine (other messages went through just fine). i've done socket data transfer in java MANY times and i've written many read/write methods to handle the sockets. it's the first time i ran into this. although in the original code i set the encoding (in the posted code i didn't), i believe that the problem was encoding related. at one point, the message that was received had every second character missing. afterwards i changed it a bit, and the first/second character of the message were received in a separate message. from my understanding, it's either an encoding issue or some firewall/other security program that was running on the message sender machine, that decided to filter outgoing packets. A: Try replacing your receive with a Scanner and let it do the work for you. // in your setup Scanner sc = new Scanner(_in).useDelimiter(Connection.DELIMETER); public String receive() { try { return sc.next(); } catch(IOException e) { return ""; } } A: For starters, I would make sure you're printing exceptions in those catch blocks. Then, you're using the platform default encoding for converting characters to bytes. If these two processes are running on different machines, it's possible they're using different encodings. I would make sure you're specifying an encoding when you set up the Reader and Writer. A: You can use UTF encoding for getting Full String of Message. U can try this code and I am Sure About this code because i used it in My Chat Application. String data=" "; socket = new Socket("localhost",999); while(true) { dos = new DataOutputStream(socket.getOutputStream()); dis = new DataInputStream(socket.getInputStream()); data = dis.readUTF(); jta.append(data +"\n"); } Where jta is JTextArea. It's for Client Side Now For Server Side: try { server = new ServerSocket(999); Socket soc = server.accept(); while(true) { String data=""; try { dis = new DataInputStream(soc.getInputStream()); dos = new DataOutputStream(soc.getOutputStream()); data = dis.readUTF(); } catch(Exception e) { } jta.append(data + "\n"); } } catch (IOException e) { JOptionPane.showMessageDialog(this, e); System.exit(-1); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Design alternatives to thread implementation of coroutines for converting a push method into a pull method I have a collection class that holds lots of different types of data in a compressed format. In order to enumerate over all of the values in the collection is has an Execute(Query, IDataWriter) method. You pass it a query that defines what data you want, and then for each piece of matching data it calls a method on the IDataWriter object you pass in. The IDataWriter interface has 15 different methods, one for each different data type in the collection. Now I need to commit this data to the database and I want to be able to implement IEnumerator<SqlDataRecord> to commit stuff to the database. The problem comes in how to convert calling Execute which dumps a ton of data into the IDataWriter object(push), to a pull method so that the IEnumerator's MoveNext and Current can be used. I have looked at Coroutines and fibers, but none of the examples I have found seem like they would work for an existing method (Execute in my case) that internally knows nothing of the corountine. So my plan in pseudocode is to do the following using Threads and manual synchronization. The Execute method would be running in a seperate Thread and I would manually wait and signal it inside each IDataWriter method class EnumeratorAdapterObject : IEnumerator<SqlDataRecord>, IDataWriter { public EnumeratorAdapterObject(Store storeObject) { workerThread = new Thread(storeObject.Execute(query, this)); } public bool MoveNext() { if (firstTimeCalled) { start worker thread } else { signal resume } block for either a call into an Add method or the Execute thread finishes if (not anything buffered) return false else return true } // 14 other methods like this implemented in IDataWriter, each with different types public void Add_Decimal(IntvlDataHeader header, decimal data) { buffer field of current SqlDataRecord = generate record; signal main thread wait for resume signal } public SqlDataRecord Current { get { return buffer field of current SqlDataRecord; } } } Does this look like a good approach? Does anyone know of any examples or questions that already implement this? Or would there be a way to take advantage of any of the new 4.0 features? I thought about using a blocking concurrent collection with a limit of 1 thing in it, but then how would the consumer(the IEnumerator's MoveNext) know when the other thread is finished adding stuff? A: Rather than doing manual Thread creation and synchronization with Signal/Wait I figured out that I can use Blocking collection with a call to CompleteAdding() when done. The following is a quick example, for my problem above I will wrap this in an object that implements IEnumerator<SqlDataRecord> and IDataWriter, so instead of the GenerateStuff call I will be calling Execute and the Add_* methods will be the ones calling col.Add(new SqlDataRecord(....)) static void Main(string[] args) { var col = new BlockingCollection<int>(1); Task.Factory.StartNew( () => { GenerateStuff(col); col.CompleteAdding(); }); while (!col.IsCompleted) { Thread.Sleep(100); int result; if (!col.TryTake(out result, -1)) { break; } Console.WriteLine("Got {0}", result); } Console.WriteLine("Done Adding!"); } static void GenerateStuff(BlockingCollection<int> col) { for (int i = 0; i < 10; i++) { Thread.Sleep(10); Console.WriteLine("Adding {0}", i); col.Add(i); Console.WriteLine("Added {0}", i); } } This also has the advantage that the worker thread that is running the Execute will be generating the next result concurrently with the IEnumerator returning Current and the sql code doing whatever it does to commit the data. With the manual thread signalling only one thread would ever run at a time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tweetstream not connecting? I'm using a recent version of Tweetstream and can't seem to connect to the twitter streaming API. I'm authenticating through oAuth like so: require "rubygems" require "tweetstream" def index TweetStream.configure do |config| config.consumer_key = 'aaa' config.consumer_secret = 'aaa' config.oauth_token = '11329872-aaa' config.oauth_token_secret = 'aaa' config.auth_method = :oauth config.parser = :yajl end TweetStream::Client.new.track('words') do |status| puts "streaming" puts "#{status.text}" end end It eventually times out though with the following: TweetStream::ReconnectError (Failed to reconnect after 7 tries.) Any idea what's wrong? A: Found the solution to this one was a missing required gem. All I needed to add was: require 'yajl' I also noticed that this is only required if you're using oAuth to authenticate with twitter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling an action in certain time in android I want to call specific action at certain time. I don't want the delay method. let's say for example the phone will change ringer mode at 10:30 pm. Thanks in advance and sorry for my English :) A: You'll have to use AlarmManager Service to do this, and a BroadcastReceiver to manage result. AlarmManager mgr=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE); Intent i=new Intent(this, AlarmReceiver.class); PendingIntent pi=PendingIntent.getBroadcast(this, 1, i, PendingIntent.FLAG_UPDATE_CURRENT); mgr.cancel(pi); long MINUTE=AlarmManager.INTERVAL_HOUR/60; long TIMER=MINUTE*minutes; mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), TIMER , pi); AND also public class AlarmReceiver extends BroadcastReceiver{... Try search for BroadCastReceiver tutorials
{ "language": "en", "url": "https://stackoverflow.com/questions/7574806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use logging inside Gevent? I have a code like: log = logging.getLogger(__file__) def func(): print "1" log.debug("Printed") g = gevent.spawn(func) g.join() but when I ran it my log doesn't show in shell. Any ideas? Is there a better way to do logging inside gevent based coroutines? A: It is unrelated to gevent. You should configure logging e.g., logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(msg)s")
{ "language": "en", "url": "https://stackoverflow.com/questions/7574813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to obtain a lock in two places but release on one place? i'm newbie in c#. I need to obtain lock in 2 methods, but release in one method. Will that work? public void obtainLock() { Monitor.Enter(lockObj); } public void obtainReleaseLock() { lock (lockObj) { doStuff } } Especially can I call obtainLock and then obtainReleaseLock? Is "doubleLock" allowed in C#? These two methods are always called from the same thread, however lockObj is used in another thread for synchronization. upd: after all comments what do you think about such code? is it ideal? public void obtainLock() { if (needCallMonitorExit == false) { Monitor.Enter(lockObj); needCallMonitorExit = true; } // doStuff } public void obtainReleaseLock() { try { lock (lockObj) { // doAnotherStuff } } finally { if (needCallMonitorExit == true) { needCallMonitorExit = false; Monitor.Exit(lockObj); } } } A: Yes, locks are "re-entrant", so a call can "double-lock" (your phrase) the lockObj. however note that it needs to be released exactly as many times as it is taken; you will need to ensure that there is a corresponding "ReleaseLock" to match "ObtainLock". I do, however, suggest it is easier to let the caller lock(...) on some property you expose, though: public object SyncLock { get { return lockObj; } } now the caller can (instead of obtainLock()): lock(something.SyncLock) { //... } much easier to get right. Because this is the same underlying lockObj that is used internally, this synchronizes against either usage, even if obtainReleaseLock (etc) is used inside code that locked against SyncLock. With the context clearer (comments), it seems that maybe Wait and Pulse are the way to do this: void SomeMethodThatMightNeedToWait() { lock(lockObj) { if(needSomethingSpecialToHappen) { Monitor.Wait(lockObj); // ^^^ this ***releases*** the lock (however many times needed), and // enters the pending-queue; when *another* thread "pulses", it // enters the ready-queue; when the lock is *available*, it // reacquires the lock (back to as many times as it held it // previously) and resumes work } // do some work, happy that something special happened, and // we have the lock } } void SomeMethodThatMightSignalSomethingSpecial() { lock(lockObj) { // do stuff Monitor.PulseAll(lockObj); // ^^^ this moves **all** items from the pending-queue to the ready-queue // note there is also Pulse(...) which moves a *single* item } } Note that when using Wait you might want to use the overload that accepts a timeout, to avoid waiting forever; note also it is quite common to have to loop and re-validate, for example: lock(lockObj) { while(needSomethingSpecialToHappen) { Monitor.Wait(lockObj); // at this point, we know we were pulsed, but maybe another waiting // thread beat us to it! re-check the condition, and continue; this might // also be a good place to check for some "abort" condition (and // remember to do a PulseAll() when aborting) } // do some work, happy that something special happened, and we have the lock } A: Only one owner can hold the lock at a given time; it is exclusive. While the locking can be chained the more important component is making sure you obtain and release the proper number of times, avoiding difficult to diagnose threading issues. When you wrap your code via lock { ... }, you are essentially calling Monitor.Enter and Monitor.Exit as scope is entered and departed. When you explicitly call Monitor.Enter you are obtaining the lock and at that point you would need to call Monitor.Exit to release the lock. A: You would have to use the Monitor for this functionality. Note that you open yourself up to deadlocks and race conditions if you aren't careful with your locks and having them taken and released in seperate areas of code can be risky Monitor.Exit(lockObj); A: This doesn't work. The code lock(lockObj) { // do stuff } is translated to something like Monitor.Enter(lockObj) try { // do stuff } finally { Monitor.Exit(lockObj) } That means that your code enters the lock twice but releases it only once. According to the documentation, the lock is only really released by the thread if Exit was called as often as Enter which is not the case in your code. Summary: Your code will not deadlock on the call to obtainReleaseLock, but the lock on lockObj will never be released by the thread. You would need to have an explicit call to Monitor.Exit(lockObj), so the calls to Monitor.Enter matches the number of calls to Monitor.Exit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reference for MongoDB runCommand with optional parameters I need to know where I can find the reference resource for MongoDB runCommand. i.e. what kind of commands are available and what kind of optional parameters each command can use. For example, db.runCommand({addshard: "10.0.4.85:27020", allowLocal : 1, maxSize:2, minKey: 1, maxKey:10}); Thank you // Update // maxSize is documented here maxSize A: Check out the MongoDB Command Reference (PDF) for a list of the most frequently used. Also, to get a full list, the card also provides this tip: To get a list of all commands available on your version of the server, run mongod --rest and then visit http://localhost:28017/_commands in your web browser
{ "language": "en", "url": "https://stackoverflow.com/questions/7574816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery Validate treats errors as separate instances instead of combining them I am able to relocate my jquery validate errors to specific container set above my form but the elements show up as separate errors (multiple). Ideally, I want to have one large error box (which on my other pages I already call with class 'error') and state something a long the lines of "Please fix the following errors:..." with the results being an unordered list. My jquery is as follows: <script type="text/javascript"> $(function() { $("#login_form").validate({ errorLabelContainer: "#containererreurtotal", wrapper: "li", errorClass: "error", rules: { AGTNO: 'required', AGTPW: 'required' }, messages: { AGTNO: 'Your Number or Email Address is required.', AGTPW: 'Your Password is required.' }, submitHandler: function(form) { $('body').append('<div id="overlay"></div>'); $('#overlay').show(); form.submit(); } }); }); </script> Above my form, I have the following: <ul id="containererreurtotal"></ul> any ideas where I am going wrong? A: http://jsfiddle.net/HK4TP/1/ Hide your error container and give it the appropriate styling, the rest will be handled by the plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3 create default nested objects I have a form where the user signs up and creates an Account, an User and a Website. def new @account = Account.new @account.users.build @account.websites.build ... end def create @account = Account.new(params[:account]) ... Everything works fine. Now, I want to create a default Page with Page.title = "homepage" and Page.body = "". How can I do that? I tried different options and it doesn't work. For example, I do this @account.websites.pages.build and I get this undefined method pages for []:ActiveRecord::Relation. A: The collection returned by @account.websites is an array, rails can't intuit which member of the collection you're trying to create an associated object on... You need to specify which website you want to build a page for, ie @account.websites.first.pages.build
{ "language": "en", "url": "https://stackoverflow.com/questions/7574823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing compiler's warning from a method call, advise needed As part of my Utils class, i have both public static boolean isStringEmptyOrNull(String... s) { When testing for a null condition assertTrue(Utils.isStringEmptyOrNull(null)); I get "The argument of type null should explicitly be cast to String[] for the invocation of the varargs method isStringEmptyOrNull(String...) from type Utils. It could alternatively be cast to String for a varargs invocation" warning. I'd rather not case anything though. This test is designed to simulate a condition where argument passed to the method is a null. Is there a way to remove this warning without changing the signature of the method? A: You should probably test both of these cases: assertTrue(Utils.isStringEmptyOrNull(new String[] { null })); assertTrue(Utils.isStringEmptyOrNull((String[]) null)); ... although it's not clear to me why a method which sounds like it should only take a single string is taking an array of strings in the first place, to be honest. (Is it obvious to you which of those invocations you meant without the cast? It isn't obvious to me... I'd have to look it up to check.) A: If you are trying to mimic the way a client of your library function would call your code, you should take advantage of the fact that they will not call this particular method with the literal "null" (what would be the point?) Instead, they would pass in some variable or expression. Since that's the case, you can do something like this and avoid casting: String nullString = null; assertTrue(Utils.isStringEmptyOrNull(nullString)); A: You could specifically tell the compiler to ignore the warning using @SuppressWarnings("all"). A: Well that warning's there for a reason: when you call your method with null argument, since null is all and any type in Java (including Array), the compiler effectively will not know if you're calling the var-args method with an array or a non-array object (each of which is treated differentlly when var-args arguments are used). What you can do is annotate the method with SuppressWarnings("All") and then test for null before doing anything with the argument(s) A: Change your test like so: String nullString = null; assertTrue(Utils.isStringEmptyOrNull(nullString)); Rather curious why you use a vararg method for this in the first place though...
{ "language": "en", "url": "https://stackoverflow.com/questions/7574827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to sort values with XSLT? I have an XML similar to this: <Test> <grapes> <a>TypeA</a> <b>value1</b> </grapes> <oranges> <a>TypeB</a> <b>value2</b> </oranges> <apples> <a>TypeA</a> <b>value3</b> </apples> </Test> where the values are unique but the Type, might be the same. I am trying to sort it so that the output is similar to this: <group type="TypeA"> <value v="value1" /> <value v="value3" /> </group> <group type="TypeB"> <value v="value2" /> </group> I am having a hard time making sure the groups are unique in the output and the values are in the right group. How should my XSL be structured? A: Here is a much simpler solution (completely "push style", no <xsl:for-each>, no nesting, no <xsl:variable>, no current(), , no //, no axes): <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:key name="kGoodsByType" match="/*/*" use="a"/> <xsl:template match= "/*/*[generate-id() = generate-id(key('kGoodsByType', a)[1]) ] "> <group type="{a}"> <xsl:apply-templates select="key('kGoodsByType', a)/b"/> </group> </xsl:template> <xsl:template match="b"> <value v="{.}"/> </xsl:template> <xsl:template match="*/* | text()" priority="-1"/> </xsl:stylesheet> when this transformation is applied on the provided XML document: <Test> <grapes> <a>TypeA</a> <b>value1</b> </grapes> <oranges> <a>TypeB</a> <b>value2</b> </oranges> <apples> <a>TypeA</a> <b>value3</b> </apples> </Test> the wanted, correct result is produced: <group type="TypeA"> <value v="value1"/> <value v="value3"/> </group> <group type="TypeB"> <value v="value2"/> </group> Explanation: Muenchian grouping of /*/* using as key the string values of their a children. II. XSLT 2.0 solution: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <xsl:for-each-group select="*/a" group-by="."> <group type="{current-grouping-key()}"> <xsl:sequence select="current-group()/../b"/> </group> </xsl:for-each-group> </xsl:template> </xsl:stylesheet> When this transformation is performed on the same XML document (above), the same correct result is produced: <group type="TypeA"> <b>value1</b> <b>value3</b> </group> <group type="TypeB"> <b>value2</b> </group> Explanation: * *<xsl:for-each-group> *current-group() *current-grouping-key() A: XSLT 1.0 : You start by creating unique groups for your types using the muenchian method. Google it to find out what it is. Then it's just a matter of iterating through them and printint out what you want, how you want it : <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:key name="types" match="a" use="text()"/> <xsl:template match="/"> <result> <xsl:for-each select="//a[generate-id(.) = generate-id(key('types', text())[1])]"> <group type="{current()/text()}"> <xsl:for-each select="//a[text() = current()/text()]"> <xsl:variable name="values" select="following-sibling::b | preceding-sibling::b"/> <xsl:for-each select="$values"> <value v="{current()}"/> </xsl:for-each> </xsl:for-each> </group> </xsl:for-each> </result> </xsl:template> </xsl:stylesheet> You will find that the output is identical to what you expect. A: My proposal is slightly different from FailedDev's: <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" /> <xsl:template match="/Test"> <root> <xsl:for-each select="*[a != following::a]"> <xsl:sort select="a" data-type="text" /> <group type="{a}"> <xsl:for-each select="/Test/*[a = current()/a]"> <xsl:sort select="b" data-type="text" /> <value v="{b}" /> </xsl:for-each> </group> </xsl:for-each> </root> </xsl:template> </xsl:stylesheet> The outer <xsl:for-each select="*[a != following::a]" /> select all unique types, ie. TypeA and TypeB. The <xsl:sort select="a" data-type="text" /> sorts these according to name, making sure TypeA will appear above TypeB. The inner <xsl:for-each select="/Test/*[a = current()/a]" /> selects a list of unique values for each type, ie. for TypeA the values value1 and value3 are extracted. Again, the resulting list is sorted to list value1 before value3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Query : problem in where section I need to write a query like this : SELECT S , D1 , D2 , (D1+D2) as D_Sum , ( (D1+D2) / (X-( SELECT SUM(T1+T2) FROM TBL1 WHERE FCode=81 AND DCode=1 AND S<S )) AS SSS FROM TBL1 WHERE Salon=1 AND FCode=81 AND DCode=1 I have problem with S<S in where section in sub query . S<S likes FALSE and doesn't works . First S are all of s in all of records in the table and second S is stored in each record . S<S : I need select all records that their s is smaller than the s is stored in the record that now processed . A: Give a name to the tables: SELECT S , D1 , D1 , (D1+D2) as D_Sum , ( (D1+D2) / (X-( SELECT SUM(innerTBL.T1+innerTBL.T2) FROM TBL1 innerTBL WHERE innerTBL.FCode=81 AND innerTBL.DCode=1 AND outerTBL.S<innerTBL.S )) AS SSS FROM TBL1 outerTBL WHERE Salon=1 AND FCode=81 AND DCode=1 Note: I should use the work "alias" instead of "name".
{ "language": "en", "url": "https://stackoverflow.com/questions/7574830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Best way to trigger OnClientCommand from server-side? I've worked myself into a bit of a problem -- I'm not sure there's a graceful way out without restructuring my code. I have a server-side timer which is running and it needs to simulate clicking a tab of a RadTabStrip. Client-Side I have the following method: function OnClientTabSelected(sender, eventArgs) { FixSplitter($find(rightPaneID)); } FixSplitter is dependent on an additional control, though: function FixSplitter(sender, eventArgs) { var multiPage = $find(multiPageID); ... } now, server-side, I have the following: public void DoTimerCycleTick(object sender, TimerEventArgs eventArgs) { GlobalSettings globalSettings = StateManager.GetStates<GlobalSettings>(); if( globalSettings.CycleEnabled ) { if (!Equals(DateTime.Now.CompareTo(globalSettings.TimeLastCycled.AddMinutes(globalSettings.CycleInterval)), -1)) //CompareTo returns -1 when time is earlier than. { int nextIndex = SelectedIndex + 1; if( nextIndex == Tabs.Count) { nextIndex = 0; } SelectedIndex = nextIndex; LayoutManager.Instance.MultiPage.SelectedIndex = nextIndex; LayoutManager.Instance.MultiPageUpdatePanel.Update(); //ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "KEY", "OnClientTabSelected();", true); globalSettings.TimeLastCycled = DateTime.Now; } } StateManager.SaveGlobalSettings(globalSettings); } The relevant bit of this code is where I'm setting indices. Clearly, this does not trigger the OnClientTabSelected method. Yet, I need to run the FixSplitter method. So, I thought a quick fix for this surprise would be to register a client script. Indeed, this would probably be sufficient if not for the dependence on the multiPage. Because my MultiPage is wrapped in an UpdatePanel which is currently updating -- it cannot be found using $find(multiPageID). $find(multiPageID) returns null where as $find(rightPaneID) returns the expected object -- both declarations are identical and the code works smoothly in all other scenarios. I am confident in saying that the culprit is the UpdatePanel. Do I have options other than creating a new method which does the same things as OnClientTabSelected except forces the MultiPageUpdatePanel to postback after executing -- instead of calling Update on the UpdatePanel server-side? I recognize that there are deeper issues with this, but it's unfinished code that can't be broken apart for a few more weeks. EDIT: After some work, here's my proposed solution. Open to critique, I'm no expert in this. :) /// <summary> /// Performs one tick of a timer on the chart. /// Ticks based on time for testability and to prevent /// weird cases when skipping the clock time forward. /// </summary> public void DoTimerCycleTick(object sender, TimerEventArgs eventArgs) { GlobalSettings globalSettings = StateManager.GetStates<GlobalSettings>(); if( globalSettings.CycleEnabled ) { if (!Equals(DateTime.Now.CompareTo(globalSettings.TimeLastCycled.AddMinutes(globalSettings.CycleInterval)), -1)) //CompareTo returns -1 when time is earlier than. { int oldIndex = SelectedIndex; int newIndex = (oldIndex + 1) != Tabs.Count ? (oldIndex + 1) : 0; SelectedIndex = newIndex; LayoutManager.Instance.MultiPage.SelectedIndex = newIndex; //LayoutManager.Instance.MultiPageUpdatePanel.Update(); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "KEY", string.Format("OnServerTabSelected({0});", newIndex), true); globalSettings.TimeLastCycled = DateTime.Now; } } StateManager.SaveGlobalSettings(globalSettings); } var showLoadingPanel = true; function OnServerTabSelected(newIndex) { var oldID = $find(multiPageID).get_selectedPageView().get_id(); var newID = $find(multiPageID).get_pageViews().getPageView(newIndex).get_id(); if ($telerik.$("#" + oldID).is(":visible")) { $telerik.$("#" + oldID).fadeOut(1000, function () { $telerik.$("#" + newID).fadeIn(1000, function () { showLoadingPanel = true; $find(multiPageID).set_selectedIndex(newIndex); }); }); showLoadingPanel = false; FixSplitter($find(rightPaneID)); return; } } A: Can't you just overload the FixSplitter method, one that takes those two paramters, does the find and then calls the other method with all 3 parameters? That way you can always override the multiPage value when you might need it; function FixSplitter(sender, eventArgs) { var multiPage = $find(multiPageID); FixSplitter(sender, multiPage, eventArgs); } function FixSplitter(sender, multiPage, eventArgs) { ... } If you can't overload for some reason you could use an alternative notation like DoFixSplitter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: open a terminal from python I'm developing a program that has a button. When pressed, I want to open a terminal that runs: sudo apt-get update I'm using: os.system("gnome-terminal -e 'sudo apt-get update'") This works fine. The only problem is that when the update is finished, the terminal closes. What can I do to leave the terminal open? A: There are a few choices: * *add ; read -p "Hit ENTER to exit" to the end of the command line. *add ; sleep 10 to the end of the command line to wait a bit, then exit. *Configure gnome terminal: Go to the "Edit" menu and click "Current Profile". Click on the "Title and Command" tab. In there, there is a setting called "When command exits". Change it to "hold the terminal open". You could also create a new profile. A: You could do this: os.system("gnome-terminal -e 'bash -c \"sudo apt-get update; exec bash\"'") A: You can remove the -e: os.system("gnome-terminal 'sudo apt-get update'") A: import os os.system("Your command") You can also pass custom command as custom variable For example: cmd_to_run = "ls -lat" os.system(cmd_to_run)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Why doesn't this JQuery stylesheet switcher store a cookie? I have a downloaded stylesheet switcher that doesn't seem to work properly. The switcher works in as much as the new stylesheet is loaded, however the cookie that it is meant to store and read never actually occurs (I assume as much, as when I refresh the page it reverts back to the default stylesheet). The console in chrome returns the following error: Uncaught ReferenceError: readCookie is not defined Now my theory was that the readCookie variable wasnt defined and i should move it to the top, but that just rendered the script completely inactive. I'm not a complete newbie when it comes to jQuery, however this is a downloaded script and I've had no experience with javascript cookies before. Any help would be HUGELY appreciated. (function($) { $(document).ready(function() { $('.styleswitch').click(function() { switchStylestyle(this.getAttribute("rel")); return false; }); var c = readCookie('style'); if (c) switchStylestyle(c); }); function switchStylestyle(styleName) { $('link[@rel*=style][title]').each(function(i) { this.disabled = true; if (this.getAttribute('title') == styleName) this.disabled = false; }); createCookie('style', styleName, 365); } })(jQuery); // cookie functions http://www.quirksmode.org/js/cookies.html function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: facebook, google, twitter, linked in login buttons I'm trying to setup single sign on (SSO) logins for each of these services. I have already setup facebook with a simple piece of code they provide like so: <fb:login-button>Facebook</fb:login-button> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js"></script> <script> FB.init({appId: '<?php echo $facebook_app_id; ?>', status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.login', function(response) { window.location.reload(); }); </script> This creates a button for you and when you click on it opens up pop up window where you can login and allow the app website access to your facebook account. Is there anything simple like this for google, twitter and linkedin? A: For LinkedIn: https://developer.linkedin.com/documents/sign-linkedin
{ "language": "en", "url": "https://stackoverflow.com/questions/7574847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ActiveRecord::Migration - Referencing a table in another schema I'm using Ruby and PostgreSQL and have created 3 distinct DB schemas: billing (for billing related data), customer (for customer related data) and edocs (for electronic documents related data). I'm not using Rails so I have a stand-alone migration code like this: #migrate.rb if ARGV[0] =~ /VERSION=\d+/ version = ARGV[0].split('=')[1].to_i else version = nil end ActiveRecord::Base.default_timezone = :utc @logger = Logger.new $stderr ActiveRecord::Base.logger = @logger ActiveSupport::LogSubscriber.colorize_logging = false @config = YAML.load_file(File.join(File.dirname(__FILE__), 'database.yml')) ActiveRecord::Base.establish_connection(@config["edocs"]) ActiveRecord::Migrator.migrate(".", version) I have already realized that I probably have to create a different directories to contain the migration for the different schemas, and changing connection info for each migrate.rb. But I'm not sure how I'm going to make a table reference another table that is in another schema. For example: class CreateBillingEventsTable < ActiveRecord::Migration def self.up create_table :billing_events do |t| t.references :customer, :null => false t.references :service_type, :null => false t.timestamps end change_table :billing_events do |t| t.index [:customer_id, :created_at] end end def self.down remove_index :billing_events, :column => [:customer_id, :created_at] drop_table :billing_events end end In the above example, "customer" and "billing_events" are in different schemas. How can I code that? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Recursively load all children/parent records in hierarchy -- Rails: 2.3.8, Ruby: 1.9.2v180, MySQL: 5.1.56 -- I have a recursive model called ExternalCategory which belongs_to :parent, :class_name => "ExternalCategory", :foreign_key => "parent_id" and has_many :children, :class_name => "ExternalCategory", :foreign_key => "parent_id" I display this hierarchy in a paginated view where only some number of top-level categories are initially visible. All ancestors of these top-level categories get loaded to the page but are only displayed via js. An ExternalCategory may have over 1000 ancestors, so without eager loading these pages can take a huge amount of time to load. That being said, I've been working on adding eager loading in an appropriate fashion but I'm not quite sure what that would be. Perhaps you can help. At the moment, I have a scope for the top_level_categories inside of ExternalCategory: named_scope :top_level_categories, :conditions => "parent_id is null" and then tacked on to the end of the has_many :children ... line up above I've added this caveat: , :include => :children So now whenever I load the children of any ExternalCategory, the children of those children get loaded, along with the children of all those children, and so on. Ideally I wouldn't be doing this in the model itself but rather in the scope, but right now I'm okay with that bit of crappiness. The main problem with all this is that I'm building up row ids in my table which reference the current element's id as well as all of it's ancestors' ids. This id gets used by the js when expanding/collapsing any category's children view. In order to create these ids, I access the current category's ancestors with recursive calls to #parent. What I end up with in my log is a ton of identical lines that look like this: CACHE (0.0ms) SELECT * FROM external_categories WHERE (external_categories.id = 216) If I avoid giving the rows all unique ids, it completely breaks the page (obviously), but things start loading lickity split. Any advice, alternate perspectives or what have you would be immensely appreciated at this point. Thanks in advance! A: The built in acts_as_tree plugin is not very good at this, but there are alternatives like ancestry which support root_id to address this specific problem. The approach that doesn't require changing anything involves fetching one "level" of depth after the next until you run out of results, trimming your retrieval time dramatically. The better approach is to add a root_id column that will make fetching all of the records in a particular branch very fast. You will have to compute this value in your migration, though, to apply it correctly. That can be a slow operation if it is only done once, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unusual result when merging two transparent images in php Im wondering if I'm doing something wrong, or if this is as good a result as im going to get. Both PNGs on the left are 95x111. The image of the robot has a 5px or so padding of transparent pixels around it, but it seems to be causing problems when they merge? $avatar = imagecreatefrompng("../guy.png"); $borderImg = imagecreatefrompng("../frame.png"); imagealphablending( $borderImg, false ); imagesavealpha( $borderImg, true ); imagecopyresampled($avatar,$borderImg, 0, 0, 0, 0, 95, 111,95, 111); imagepng($avatar, $newfilenameBig); Ive tried every combo of imagealphablending and imagesavealpha I can think of. When I set $avatar to imagesavealpa= true, then it doesnt even show the image as all, just the frame. Doesn't that seem strange? Is this as far as i'm gonna get using PHP GD? UPDATE: The desired result can be achieved when both images are created manually in PS using 24 bit mode. Is there a way to do this using imagecopy or similar? A: Try the following code its working fine. $width = 95; $height = 111; $base_image = imagecreatefrompng("../guy.png"); $top_image = imagecreatefrompng("../frame.png"); imagesavealpha($top_image, false); imagealphablending($top_image, false); imagecopy($base_image, $top_image, 0, 0, 0, 0, $width, $height); imagepng($base_image, "merged.png");
{ "language": "en", "url": "https://stackoverflow.com/questions/7574856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Group rows in an associative array of associative arrays by column value and preserve the original first level keys I have an array of subarrays in the following format: [ 'a' => ['id' => 20, 'name' => 'chimpanzee'], 'b' => ['id' => 40, 'name' => 'meeting'], 'c' => ['id' => 20, 'name' => 'dynasty'], 'd' => ['id' => 50, 'name' => 'chocolate'], 'e' => ['id' => 10, 'name' => 'bananas'], 'f' => ['id' => 50, 'name' => 'fantasy'], 'g' => ['id' => 50, 'name' => 'football'] ] And I would like to group it into a new array based on the id field in each subarray. array ( 10 => array ( e => array ( id = 10, name = bananas ) ) 20 => array ( a => array ( id = 20, name = chimpanzee ) c => array ( id = 20, name = dynasty ) ) 40 => array ( b => array ( id = 40, name = meeting ) ) 50 => array ( d => array ( id = 50, name = chocolate ) f => array ( id = 50, name = fantasy ) g => array ( id = 50, name = football ) ) ) A: The following code adapts @Tim Cooper’s code to mitigate Undefined index: id errors in the event that one of the inner arrays doesn’t contain an id: $arr = array(); foreach($old_arr as $key => $item) { if(array_key_exists('id', $item)) $arr[$item['id']][$key] = $item; } ksort($arr, SORT_NUMERIC); However, it will drop inner arrays without an id. E.g. $old_arr = array( 'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ), 'b' => array ( 'id' => 40, 'name' => 'meeting' ), 'c' => array ( 'id' => 20, 'name' => 'dynasty' ), 'd' => array ( 'id' => 50, 'name' => 'chocolate' ), 'e' => array ( 'id' => 10, 'name' => 'bananas' ), 'f' => array ( 'id' => 50, 'name' => 'fantasy' ), 'g' => array ( 'id' => 50, 'name' => 'football' ), 'h' => array ( 'name' => 'bob' ) ); will drop the 'h' array completely. A: You can also use Arrays::groupBy() from ouzo-goodies: $groupBy = Arrays::groupBy($array, Functions::extract()->id); print_r($groupBy); And result: Array ( [20] => Array ( [0] => Array ( [id] => 20 [name] => chimpanzee ) [1] => Array ( [id] => 20 [name] => dynasty ) ) [40] => Array ( [0] => Array ( [id] => 40 [name] => meeting ) ) [50] => Array ( [0] => Array ( [id] => 50 [name] => chocolate ) [1] => Array ( [id] => 50 [name] => fantasy ) [2] => Array ( [id] => 50 [name] => football ) ) [10] => Array ( [0] => Array ( [id] => 10 [name] => bananas ) ) ) And here are the docs for Arrays and Functions. A: Here is a function that will take an array as the first argument and a criteria (a string or callback function) as the second argument. The function returns a new array that groups the array as asked for. /** * Group items from an array together by some criteria or value. * * @param $arr array The array to group items from * @param $criteria string|callable The key to group by or a function the returns a key to group by. * @return array * */ function groupBy($arr, $criteria): array { return array_reduce($arr, function($accumulator, $item) use ($criteria) { $key = (is_callable($criteria)) ? $criteria($item) : $item[$criteria]; if (!array_key_exists($key, $accumulator)) { $accumulator[$key] = []; } array_push($accumulator[$key], $item); return $accumulator; }, []); } Here is the given array: $arr = array( 'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ), 'b' => array ( 'id' => 40, 'name' => 'meeting' ), 'c' => array ( 'id' => 20, 'name' => 'dynasty' ), 'd' => array ( 'id' => 50, 'name' => 'chocolate' ), 'e' => array ( 'id' => 10, 'name' => 'bananas' ), 'f' => array ( 'id' => 50, 'name' => 'fantasy' ), 'g' => array ( 'id' => 50, 'name' => 'football' ) ); And examples using the function with a string and a callback function: $q = groupBy($arr, 'id'); print_r($q); $r = groupBy($arr, function($item) { return $item['id']; }); print_r($r); The results are the same in both examples: Array ( [20] => Array ( [0] => Array ( [id] => 20 [name] => chimpanzee ) [1] => Array ( [id] => 20 [name] => dynasty ) ) [40] => Array ( [0] => Array ( [id] => 40 [name] => meeting ) ) [50] => Array ( [0] => Array ( [id] => 50 [name] => chocolate ) [1] => Array ( [id] => 50 [name] => fantasy ) [2] => Array ( [id] => 50 [name] => football ) ) [10] => Array ( [0] => Array ( [id] => 10 [name] => bananas ) ) ) Passing the callback is overkill in the example above, but using the callback finds its use when you pass in an array of objects, a multidimensional array, or have some arbitrary thing you want to group by. A: foreach($array as $key => $value){ $newarray[$value['id']][$key] = $value; } var_dump($newarray); piece of cake ;) A: $arr = array(); foreach ($old_arr as $key => $item) { $arr[$item['id']][$key] = $item; } ksort($arr, SORT_NUMERIC); A: Maybe it's worth to mention that you can also use php array_reduce function $items = [ ['id' => 20, 'name' => 'chimpanzee'], ['id' => 40, 'name' => 'meeting'], ['id' => 20, 'name' => 'dynasty'], ['id' => 50, 'name' => 'chocolate'], ['id' => 10, 'name' => 'bananas'], ['id' => 50, 'name' => 'fantasy'], ['id' => 50, 'name' => 'football'], ]; // Grouping $groupedItems = array_reduce($items, function ($carry, $item) { $carry[$item['id']][] = $item; return $carry; }, []); // Sorting ksort($groupedItems, SORT_NUMERIC); print_r($groupedItems); https://www.php.net/manual/en/function.array-reduce.php A: Because of how PHP's sorting algorithm treats multidimensional arrays -- it sorts by size, then compares elements one at a time, you can actually use a key-preserving sort on the input BEFORE restructuring. In functional style programming, this means that you don't need to declare the result array as a variable. Code: (Demo) asort($array); var_export( array_reduce( array_keys($array), function($result, $k) use ($array) { $result[$array[$k]['id']][$k] = $array[$k]; return $result; } ) ); I must say that functional programming is not very attractive for this task because the first level keys must be preserved. Although array_walk() is more succinct, it still requires the result array to be passed into the closure as a reference variable. (Demo) asort($array); $result = []; array_walk( $array, function($row, $k) use (&$result) { $result[$row['id']][$k] = $row; } ); var_export($result); I'd probably recommend a classic loop for this task. The only thing the loop needs to do is rearrange the first and second level keys. (Demo) asort($array); $result = []; foreach ($array as $k => $row) { $result[$row['id']][$k] = $row; } var_export($result); To be completely honest, I expect that ksort() will be more efficient than pre-loop sorting, but I wanted to a viable alternative.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "68" }
Q: how to change the text color using using jquery function DoInsert(ind) { var sourceIndex = $("#lstAvailableCode").val(); var targetIndex = $("#lstCodelist").val(); var success = 0; var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex; var functionName = "/Ajax/SaveCodeforInsert"; if (ind == "plan") { functionName = "/Ajax/SaveCodeforInsertForPlan"; } $.ajax({ type: "POST", traditional: true, url: functionName, async: false, data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>", dataType: "json", error: function (data) { alert("Error Adding Code"); FinishAjaxLoading(); }, success: function (data) { if (data == 0) { success = 1; } else { success = data; } FinishAjaxLoading(); var x = $("#lstAvailableCode").val(); $("#lstCodelist").val(x); $("#lstCodelist").val(x).css("background-color", "#ffffff"); } }); Here I am trying to adding one item from lstAvailableCode list box to lstCodelist box. after adding into lstCodelist box I am trying to change the textcolor to yellow or some other color. on my success message i wrote something like this. But I am not able to change the color of the text even I am not able to change the backgroud color of that list box. is that something I am doing wrong here? here is my lstCodelist box code. <select id="lstCodelist" size="17" name="lstCodelist" style="width:100%;height:280px;background-color:#EFEFFB;"></select> $.fn.fillSelectDD = function (data) { return this.clearSelectDD().each(function () { if (this.tagName == 'SELECT') { var dropdownList = this; $.each(data, function (index, optionData) { var option = new Option(optionData.Text, optionData.Value); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } }); } }); } A: $("#lstCodelist").val(x).css("background-color", "#ffffff"); should be $("#lstCodelist").css("background-color", "#ffffff"); .val() returns a value, not the original jQuery object. To change the font color, you wold use: $("#lstCodelist").css("color", "#00ffff"); A: $("#lstCodelist").val(x).css("background-color", "#ffffff"); should be $("#lstCodelist").css("background-color", "#ffffff"); Otherwise you're trying to set a css property on whatever string/number the .val() call returns, and NOT on the actual page element that the value's coming from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala XML, Get nodes where parent has attribute value match Any way to simplify the following? or reduce the boilerplate code with another function? scala> val ns = <foo><bar id="1"><tag>one</tag><tag>uno</tag></bar><bar id="2"><tag>two</tag><tag>dos</tag></bar></foo> ns: scala.xml.Elem = <foo><bar id="1"><tag>one</tag><tag>uno</tag></bar><bar id="2"><tag>two</tag><tag>dos</tag></bar></foo> scala> (ns \\ "bar" filterNot{_ \\ "@id" find { _.text == "1" } isEmpty}) \\ "tag" res0: scala.xml.NodeSeq = NodeSeq(<tag>one</tag>, <tag>uno</tag>) A: I could only find a minor improvement, the find/isEmpty test can be replaced with exists: (ns \\ "bar" filter { _ \\ "@id" exists (_.text == "1") }) \\ "tag" Edit after clarifying comment: That's a really nice idea! Try this for size: import xml._ implicit def richNodeSeq(ns: NodeSeq) = new { def \@(attribMatch: (String, String => Boolean)): NodeSeq = ns filter { _ \\ ("@" + attribMatch._1) exists (s => attribMatch._2(s.text)) } } ns \\ "bar" \@ ("id", _ == "1") \\ "tag" I used a predicate instead of hard-coding the attribute value comparison. A: The best way is to define implicit class: object XmlE { implicit class XmlE(val xml: NodeSeq) extends AnyVal { def \@(attr: (String, String => Boolean)): NodeSeq = { xml filter { _ \ ("@" + attr._1) exists (s => attr._2(s.text)) } } } } Then use it from another class : import XmlE._ .....
{ "language": "en", "url": "https://stackoverflow.com/questions/7574862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: what criteria should I use to evaluate an ORM? There are plenty of questions on here that ask 'what ORM should I use with x and y' but I didn't see any that specifically asked how to pick one. Related: Why should you use an ORM?, What ORM should I use for a ASP.Net MVC project?, Are there good reasons not to use an ORM? and more. There are a lot of ORMs out there in the world. I'd like to get an idea of how to compare them. I've heard about things like active record model and domain model among others and I'm not sure what those mean. So what are a good set of criteria I can use to compare one ORM to another? Our environment, in case you're wondering, is C#, MVC, SQL Server. A: (I tried to answer in a non-.NET specific way when possible.) The most important criteria for choosing an ORM are your business requirements. I would say another important criteria is your belief in the future sustainability of the ORM. Microsoft has a tendency to change their data access technology every two years or so, so I would say Entity Framework's future is unclear. NHibernate may follow the same path as NUnit - when Microsoft released MSTest, NUnit languished for a while, but now NUnit has momentum again since Microsoft is mostly neglecting MSTest. You have to reach your own conclusion here, right now Microsoft appears to be giving Entity Framework some love, yet as far as I know it still doesn't handle enums very well and I haven't heard when that may change. Another criteria is whether you have a preference between open source technologies or technologies from Microsoft or commercial third party technologies. At some point, the features of the ORM will matter. You may need to prototype your scenario with multiple ORMs to determine if the features (and/or performance) of the ORM match your requirements. NHibernate is the most feature rich ORM in the .NET space. Do you need to support a certain database vendor? Pick an ORM that supports the one you care about. SQL Server is the most widely supported database vendor in the .NET world. Do you have a preference between code first or database first design? Pick an ORM that supports the one you care about. Do you have a preference between active record vs. repository vs. something else? Pick an ORM that supports the one you care about. I answered the question linked below about choosing a .NET ORM partially by providing links to all the times people asked which .NET ORM they should use on StackOverflow. There is a lot of value that can be gained from reading those other answers. NHibernate, Entity Framework, active records or linq2sql There is no one right answer nor one correct set of criteria for choosing. Your business requirements are the most important ingredient to consider.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I access private class members of container class within the anonymouse inner class? How can I access all the member field of the class which contains the function initTimer() from within the AbstractActionClass? Thanks private void initTimer() { Action updateClockAction = new AbstractAction() { public void actionPerformed(ActionEvent e){ JLabel secLabel = m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds(); secLabel.setFont(new java.awt.Font("Lucida Handwriting", 1, 36)); secLabel.setForeground(Color.red); secLabel.setText(Integer.toString(m_TimerSeconds)); if(m_TimerSeconds >0) { m_TimerSeconds--; } else if (m_TimerSeconds == 0) { m_Timer.stop(); m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds().setText("0"); m_GameApplet.GetJpanelStartNetGame().GetJbuttonFinish().setVisible(false); //Checking whether time ended for both players and no solution was recieved if(!m_WasGameDecisived) { System.out.println("Tie - No one had a solution in the given time"); //askUserForAnotherRoundLeaveTableOrExitProgram();//////////////////////////////////////////////To implement } } } }; m_Timer = new Timer(1000, updateClockAction); } A: Try, ClassName.this.foo where foo is a class member. For more information, see JLS §15.8.4 Qualified this. A: Assuming your outer class is called OuterClass, then OuterClass.this.whatever
{ "language": "en", "url": "https://stackoverflow.com/questions/7574865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to set jQuery.data() using object I'm currently trying to use the .data() method to store data using a variable. However, for some reason it isn't working. Here is my proof of concept code: var option = 'x'; $(this).data({ 'x' : 0 }); alert($(this).data(option)); $(this).data({ option : 20 }); alert($(this).data(option)); Surprisingly both of the alerts return 0 as opposed to 0 and then 20. Any help is really appreciated! Thanks! A: This is because in the second version, you are referencing the key "option" instead of the variable option (key "x"). var option = 'x'; $(this).data({ 'x' : 7 }); console.log($(this).data(option)); $(this).data({ option : 20 }); console.log($(this).data('option')); A simpler version of this: option = 'x'; console.log({option: 20}); Outputs: Object { option=20 } You can however use the key value syntax with a variable. $(this).data(option, 20 ); A: You want to access the property... like this.. $(this).data({ option : 20 }); alert($(this).data('option')); A: The problem is that your option keyword in your object literal is being interpreted as a literal string for the key, rather than x (this is just how object literals work). If you want to be able to use a variable key, you'll need to use a temporary object. E.g., var option = 'x'; $(this).data({ 'x' : 0 }); alert($(this).data(option)); // create a data object so you can use a variable for the key var obj = {}; obj[option] = 20; $(this).data(obj); alert($(this).data(option)); A: The reason is that your second one $(this).data({ option : 20 }); sets 20 to the option property, when you are actually meaning to set it to the x property. I think this is what you are wanting to do instead: var option = 'x'; $(this).data({ x : 0 }); alert($(this).data(option)); $(this).data({ x : 20 }); alert($(this).data(option)); Alternatively, you can instead use the key value syntax like this: var option = 'x'; $(this).data(option, 0); alert($(this).data(option)); $(this).data(option, 20); alert($(this).data(option)); A: The key to the data object cannot be a variable. What you can do is: var option = 'x'; var data = {}; data['x'] = '0'; $(this).data(data); alert($(this).data(option));
{ "language": "en", "url": "https://stackoverflow.com/questions/7574870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE 7/8 absolute positioned elements cant go down past a certain point JS/Jquery The script is pretty simple var myMenu = null; var myItems = null; var myTopBar = null; var lastPos = 0; function menuFloat() { var scrollTop = $(window).scrollTop(); if (lastPos != scrollTop) { alert(scrollTop); myMenu.animate({top: scrollTop}, "slow"); } lastPos = scrollTop; setTimeout(menuFloat, 150); }; The problem is, I deal with long pages. Once the scrollTop hits about 1,300,000px my menu stops scrolling with the page. It is as if it has hit a maximum position value and it sticks. This is Using IE8 (and 7) in Quirks and compatibility mode (has to be this way, standards mode renders too slowly for large pages like this). Any tips for keeping my menu scrolling? (does not occur in sane browsers). A: Use the registry entry: HKEY_CURRENT_USER/SOFTWARE/Microsoft/Internet Explorer/Main/FeatureControl/FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION Add the following key: iexplore.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/7574877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error pushing to proper Heroku Web App Somewhere along the way here I copied a node app and it's still associated with an old git repository/heroku app. When I try to create a new heroku app and push to heroku i get the following error: ! No such app as young-journey-xxxx fatal: The remote end hung up unexpectedly However I don't want to push to young-journey-xxxx. I want to push to 'SOMENAME' which i just created using: heroku create --stack cedar how do i tell node/git to use SOMENAME on Heroku now? Thanks much. A: You can try to add your heroku app as a remote. http://devcenter.heroku.com/articles/git#git_remotes_and_heroku
{ "language": "en", "url": "https://stackoverflow.com/questions/7574882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rotate Image from Code I want to rotate Image Control using LayoutTransform but the problem i am facing is that i can do this in XMAL but not code behind. i am new to WPF here is XMAL ` <Image Grid.Column="1" Grid.Row="4" Height="155" HorizontalAlignment="Left" Margin="103,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="139" Source="/7SegmentLed;component/Images/Caster1.png" Grid.RowSpan="2" > <Image.LayoutTransform> <RotateTransform Angle="{Binding AngleSlider}" /> </Image.LayoutTransform> </Image> and CODE double AngleSlider = 90.0; image1.DataContext = AngleSlider; i want to update it dynamically from the values i compute at back but the fact is that i donot want to change the image it is fixed and will not change it would be great if anyone let me know what i am doing wrong A: Your binding is a bit off; while you can set the DataContext to a double, your binding is going to attempt to find a property called AngleSlider on your double, which is obviously not there. So instead, create a class with a property of type Double called AngleSlider like so: public class MySliderDataContext : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public double AngleSlider { get { return _angle; } set { _angle = value; if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("AngleSlider")); } } } Create an instance of this class, and save it in a field on your Window, and then assign that instance to the DataContext: private MySliderDataContext _sliderAngle; image1.DataContext = _sliderAngle; Now, when necessary you can do: _sliderAngle.SliderAngle = 90; And your image should rotate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE9 iframe scrolling I have an interesting "issue" that only happens in IE9. There are some forms on our web site that use iframes (the forms live on other sites we have no control over - and example would be Salesforce.com). The scrolling attribute is set to "no". This shuts off the scrollbars and prevents scrolling in all browsers except IE9. In IE9, the user can still scroll in the iframe by clicking and dragging or using the arrow keys when the iframe has focus. My question is: does anyone know of a way to prevent this? I assume if I had access to the source I could create a div and set the div to be narrower than the iframe so the content wouldn't overflow, but I don't have access to the iframe source code, so that's not an option. Any suggestions on this one? It's been driving me nuts and I'm close to saying it's not possible. Thanks! A: Setting scrolling attribute of iframe to "no" will just hide the scrolls from being appearing in IE for that iframe even if they are needed. To avoid this you must arrange the contents of iframe such that no scrolls are needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How is google dart related to google closure? I have just started using Google Closure and I have also heard about Google Dart which seems very similar. How are the two related? A: Google closure, is a set of javascript libraries and a javascript parser for compiling and compacting your javascript. There are google closure tools that can be built into your build / deploy cycle. Google Dart appears (from the current scant information) to be a language replacement for javascript, with the option for compiling to javascript. This is similar to what google GWT does now with java (ie, you write java and it compiles to javascript. I believe that this compilation process also uses the closure compiler). This would be why the GWT + Closure teams have been moved onto the Dart project - it's vital for the takeup of Dart that developers can deploy client side dart applications to browsers that don't directly support dart (ie, non chrome). Cross compilation of dart to javascript (in the same way that GWT does java to javascript) is Googles method of solving this. A: The Dart keynote speech should be happening soon (tomorrow?), but I thought I'd also add this excerpt from the Dash email. What about the existing code bases for large Google Apps? Won’t they have to rebuild everything to take advantage of Dash? The Dash Cross Compiler should be capable of taking typed Closure code (with some restrictions) and converting to Dash. Although the migration process won’t be fully automatic, it should make moving over to a Dash codebase somewhat easier. A: At the moment, DartC uses the closure compiler for optimized builds (--optimize). For a normal edit/refresh cycle, it generates javascript directly to gain some speed for the developer. The optimize (and closure phase) is more of a packaging and deployment step. A: I believe Dart was designed with Google Closure Compiler in mind from the very first start. The core principle underlying Dart's optional typing system is that: "Striping type annotation should not effect the program behavior in production mode" which match very well with Google Closure's comment-based type annotation system. http://www.dartlang.org/articles/optional-types/ bar(int n) { return n *2;} ... bar(3.2); // returns 6.4 in production, but fails in checked mode
{ "language": "en", "url": "https://stackoverflow.com/questions/7574900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: The current request for action 'Index' on controller type 'DinnersController' is ambiguous between the following action methods I am getting this error after trying to implement paging support. I am on this step of the html tutorial: http://nerddinnerbook.s3.amazonaws.com/Part8.htm A: The error you are getting tells that ASP.NET MVC has found two actions with the same name and can't chose which to use. If you have two Index-actions in your DinnersController.cs: public ActionResult Index() { and: public ActionResult Index(int? page) { Then you should remove the first Action. since the second is the 'updated' version of the first. The second Action accepts requests to: /Dinners /Dinners?page=2 /Dinners/Index /Dinners/Index?page=2 And with the change in RegisterRoutes it also accepts requests to: /Dinners/Page/2 You can have two Actions with the same name, providing one is for saving (postbacks), where you decorate the saving action with [AcceptVerbs(HttpVerbs.Post)] or just [HttpPost] A: MVC does not support overloading of action methods in your controller. It is not possible to have two Index() actions with different method signatures on the same controller. In order to make the example you are testing work, you must remove the Index() action which does not accept any parameters, and replace it with the action that takes a nullable int as a parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Prevent UIScrollView from cancelling touchesMoved: of subview? I have a UIScrollView. On top of it I allow the user to add a DraggableView (a subclass of UIImageView) by applying a long press gesture to the UIScrollView. The DraggableView overrides touchesMoved: and allows the user to drag the view around. This works until either one of two cases happens: * *The UIScrollView detects another long press while the user moves (after all his finger has been on the screen for a while) *The UIScrollView starts to scroll. What is the best way to prevent the long press detection and the scrolling of the scroll view while the user is dragging my view around? Is there a built in mechanism or do I have to keep track of a status somewhere and react accordingly? Replies in ObjC and Monotouch are both welcome. A: Figured it out meanwhile. UIScrollView has a property do enable or disable scrolling. I just set that and enable scrolling again once my long press has been handled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Showing copied data in Infragistics wingrid I'm using Infragistics wingrid in my C# winforms app. I need to be able to copy column values from an excel sheet and paste it in this datagrid.The grid should show these new values in the cells.How do I achieve this?What code changes would be required? I tried it and only one cell value gets updated. Thanks. A: In InitializeLayout do: e.Layout.Override.AllowMultiCellOperations = AllowMultiCellOperation.All;
{ "language": "en", "url": "https://stackoverflow.com/questions/7574915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adding html5 attribute to my website As some of you may have seen arcade fire released a special music video along with google that showcased the power of HTML5, if not its here: http://thewildernessdowntown.com/ My question is I'm redesigning my home page and would really like to add those birds but when i went through the websites source code i couldnt find the script anywhere and when i just took the entire html source file, saved it locally and opened it, the page opened perfectly, but no birds. Can anyone show or help me pinpoint the birds on the website so i can use them. THANKS A: Viewing the source, I came across this linked javascript file - http://www.thewildernessdowntown.com/js/main-compressed.js There is A LOT of stuff going on in there, but I found a function that might be somewhat helpful (though it seems a bit obfuscated.) addBirds1: function() { for (var e = 0; e < 100; e++) { var c = -1 - Math.random() * 0.5; var h = 1 - Math.random() * 2; var b = 1 + Math.random() * 0.5; var f = 1 - Math.random() * 2 - Math.random() * 0.5; var k = 1.5 * (0.025 + Math.random() * 0.05); var m = (b - c) / k; var l = (f - h) / k; var g = Math.atan2(l, m); this.birds_array.push({ start: { x: c, y: h }, end: { x: b, y: f }, d: { x: m, y: l }, a: g, t: k, o: Math.random(), scale: 0.4 + 0.4 * Math.random() }) } }, There are 3 versions of that function... so I'd imagine they are just ways to simulate random flying activity. It seems that what you're looking for is javascript, and not HTML5 A: The birds feature is not HTML5. It's javascript. Turn off your javascript and check it out. http://cdn.thewildernessdowntown.com/js/main-compressed.js A: HTML5 doesn't do that, sorry. It's still a markup language. You'll still have to use good ol' Javascript for that. You can see that on the website if you turn Javascript off.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to complete login with phonegap and devise (Rails) I have a rails app that has devise gem installed (with auth_token setup). I'm not sure how to make my jquery mobile app ask for the token and store it (in a secure way). Thanks! A: i have a similar set up - rails 3 backend with devise as the authentication. i'm using standard jquery, though, on a full browser instead of a mobile, and i have my users log in through normal html forms. in order to keep my users authenticated and be able to make backbone / jquery ajax calls back to my server, i had to add this to my rails.js file: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); } }); once i put that in place, i didn't have to worry about authentication anymore. hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7574920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Selectbox with Timezones in Rails 3.1 I want to make selectbox like this with simple_form (but it doesn't matter I think). I found that in Rails 2.1 was object TimeZone.us_zones but now it doesn't work neither Time.zone.all or smth. The line example for simple_form: = f.time_zone :time_zone, TimeZone.us_zones And I should have a time_zone field string format in db sqlite? A: Maybe this can be helpful as well <li> <%= f.label :time_zone %><%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, :class => :timezone %> </li> A: Works without any collection = f.time_zone_select :time_zone
{ "language": "en", "url": "https://stackoverflow.com/questions/7574922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Access IFrame's parent URL Possible Duplicate: access parent url from iframe I've been looking around but can't find a set answer or solution for this. I have 2 websites, www2.domain.net and www3.domain.net both these websites have an iFrame on them that links to www.domain.co.uk/iframe.html What I want to do is check the parent URL, i.e - is the user accessing www2.domain.net or www3.domain.net so I can show specific information to just people accessing www3.domain.net. Is this possible? Thanks, Andrew A: It's possible, but not very straightforward and requires that you have control over all three pages involved. If you do control all three sites there's cross window messaging, courtesy of window.postMessage(). However, it's a (relatively) new addition to the DOM and unsupported in older browsers like IE 7, IE 6, Safari 4, Firefox 2 and Opera 9. // Parent: iframeWin.postMessage("Hello, from "+window.location.host); // Iframe: window.onmessage = function (evt) { alert(evt.origin); } Another option is to pass the domain via the URL and then parse this at the other end: <iframe src="www.domain.co.uk/iframe.html?www2.domain.net" /> and the required JavaScript (called from the page inside the iframe): alert(window.location.search); //-> "?www2.domain.net" A: It is not. iframes are considered frames and so the cross domain policy applies to them. Since the iframe domain (www.domain.co.uk/iframe.html) is different than the parent domain (www3.domain.net) it cannot access the parent domain. I believe, however, that you can still access the iframe from the parent domain either through the DOM or via window.frames (an array of all frames including iframes). A: It is not possible in this case (as posted) due to Same Origin Policy. However, it seems that you control all these domains. If so, you could pass the parent domain in the iFrame tag's src attribute using query string and access it in the iFrame page. See @Andy's answer for implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Notepad++, removing any text not matching a certain string on each line? I have something like: oiuerer jeff oteaweawe gnwaeeeee jeff nbbaweee bbbadx jeff nvxxawee I would like to remove the text which is both before and after the word "jeff" so that each line is only "jeff". How can I do this with regex? Thanks A: Replace .*jeff.* with jeff? A: Press Ctrl+h to open this dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Direction Cosine Matrix implementation I'm trying to implement the Direction Cosine Matrix on Android. I've read some theory about DCM and I finally coded a draft public void imuUpdate(float dT, float gyro[], float accel[]) { int i; Tuple3d Kacc = new Tuple3d(); // Acc can estimate global K vector(zenith) measured in body's // coordinate systems (the reverse of gravitation vector) Kacc.x = -accel[0]; Kacc.y = -accel[1]; Kacc.z = -accel[2]; // vector3d_normalize(Kacc); Kacc.normalize(); // calculate correction vector to bring dcmGyro's K vector closer to Acc // vector (K vector according to accelerometer) Tuple3d wA = new Tuple3d(); Tuple3d dcmGyroX = new Tuple3d(); dcmGyroX.x = dcm_matrix.get(0, 2); dcmGyroX.y = dcm_matrix.get(1, 2); dcmGyroX.z = dcm_matrix.get(2, 2); wA.cross(dcmGyroX, Kacc); // calculate correction vector to bring dcmGyro's I vector closer to Mag // vector (I vector according to magnetometer) Tuple3d Imag = new Tuple3d(); Tuple3d wM = new Tuple3d(); // in the absense of magnetometer let's assume North vector (I) is // always in XZ plane of the device (y coordinate is 0) Imag.x = Math.sqrt(1 - Math.pow(dcm_matrix.get(0, 2), 2)); Imag.y = 0; Imag.z = dcm_matrix.get(0, 2); dcmGyroX.x = dcm_matrix.get(0, 0); dcmGyroX.y = dcm_matrix.get(1, 0); dcmGyroX.z = dcm_matrix.get(2, 0); wM.cross(dcmGyroX, Imag); // --------------- // dcmGyro // --------------- Tuple3d w = new Tuple3d(); // Acc can estimate global K vector(zenith) measured in body's // coordinate systems (the reverse of gravitation vector) w.x = -gyro[0]; w.y = -gyro[1]; w.z = -gyro[2]; float wA2[] = new float[3]; wA2[0] = (float) wA.x; wA2[1] = (float) wA.y; wA2[2] = (float) wA.z; w.x *= dT; w.x = (w.x + ACC_WEIGHT * wA.x + MAG_WEIGHT * wM.x) / (1.0 + ACC_WEIGHT + MAG_WEIGHT); w.y *= dT; w.y = (w.y + ACC_WEIGHT * wA.y + MAG_WEIGHT * wM.y) / (1.0 + ACC_WEIGHT + MAG_WEIGHT); w.z *= dT; w.z = (w.z + ACC_WEIGHT * wA.z + MAG_WEIGHT * wM.z) / (1.0 + ACC_WEIGHT + MAG_WEIGHT); dcm_rotate(w); } // rotate DCM matrix by a small rotation given by angular rotation vector w // see public void dcm_rotate(Tuple3d w) { // float W[3][3]; // creates equivalent skew symetric matrix plus identity matrix // vector3d_skew_plus_identity((float*)w,(float*)W); // float dcmTmp[3][3]; // matrix_multiply(3,3,3,(float*)W,(float*)dcm,(float*)dcmTmp); Tuple3d dcmXX = new Tuple3d(); Tuple3d dcmXY = new Tuple3d(); Tuple3d dcmXZ = new Tuple3d(); dcmXX.x = dcm_matrix.get(0, 0); dcmXX.y = dcm_matrix.get(1, 0); dcmXX.z = dcm_matrix.get(2, 0); dcmXY.x = dcm_matrix.get(0, 1); dcmXY.y = dcm_matrix.get(1, 1); dcmXY.z = dcm_matrix.get(2, 1); dcmXZ.x = dcm_matrix.get(0, 2); dcmXZ.y = dcm_matrix.get(1, 2); dcmXZ.z = dcm_matrix.get(2, 2); Tuple3d dR = new Tuple3d(); dR.cross(w, dcmXX); dcmXX.add(dR); // System.out.println("WA: " + w.x + " " + w.y + " " + w.z); dR.cross(w, dcmXY); dcmXY.add(dR); dR.cross(w, dcmXZ); dcmXZ.add(dR); // Orthonormalize Tuple3d dcmXXtmp = dcmXX; Tuple3d dcmXYtmp = dcmXY; Tuple3d dcmXZtmp = dcmXZ; // err = X . Y , X = X - err/2 * Y , Y = Y - err/2 * X (DCMDraft2 // Eqn.19) // float err = vector3d_dot((float*)(dcm[0]),(float*)(dcm[1])); float err = (float) dcmXX.Dot(dcmXY); dcmXXtmp.scaleAdd(-err / 2, dcmXY); dcmXYtmp.scaleAdd(-err / 2, dcmXX); dcmXZtmp.cross(dcmXXtmp, dcmXYtmp); dcmXXtmp.normalize(); dcmXYtmp.normalize(); dcmXZtmp.normalize(); dcm_matrix.set(0, 0, (float) dcmXXtmp.x); dcm_matrix.set(1, 0, (float) dcmXXtmp.y); dcm_matrix.set(2, 0, (float) dcmXXtmp.z); dcm_matrix.set(0, 1, (float) dcmXYtmp.x); dcm_matrix.set(1, 1, (float) dcmXYtmp.y); dcm_matrix.set(2, 1, (float) dcmXYtmp.z); dcm_matrix.set(0, 2, (float) dcmXZtmp.x); dcm_matrix.set(1, 2, (float) dcmXZtmp.y); dcm_matrix.set(2, 2, (float) dcmXZtmp.z); } So every time the Gyro get updated I compute dT and I call imuUpdate I achieved to do this code by mixing the theory http://gentlenav.googlecode.com/files/DCMDraft2.pdf and some code found here http://code.google.com/p/picquadcontroller/source/browse/trunk/imu.h?r=7 (thanks to them by the way) But I can make this DCM work... if I try to extract the pitch for example pitch = Math.asin(-dcm_matrix.get(0, 2)); the result it's completly wrong (it's giving me some random angles...) and if i plot the DCM well it's numbers... But I can't figure out where in my calculation I'm wrong... Can somebody give me a hand on this please? EDIT: I have updated my code (i had a sign error). Now I tested my DCM after what ALi suggested (corss product on 2 diferent must be 0 or almost 0 and the square sum must be 1 or almost 1 on my case) Well.. I tried to apply my DCM using opengl gl.glTranslatef(0, 0, -10.0f); // setup code float vertexData[] = new float[16]; for (int i=0;i<16;i++) { vertexData[i] = 0; } vertexData[15] = 1; vertexData[0] = this.main.dcm_matrix.mMat[0]; vertexData[1] = this.main.dcm_matrix.mMat[1]; vertexData[2] = this.main.dcm_matrix.mMat[2]; vertexData[3] = this.main.dcm_matrix.mMat[3]; vertexData[5] = this.main.dcm_matrix.mMat[4]; vertexData[6] = this.main.dcm_matrix.mMat[5]; vertexData[8] = this.main.dcm_matrix.mMat[6]; vertexData[9] = this.main.dcm_matrix.mMat[7]; vertexData[10] = this.main.dcm_matrix.mMat[8]; gl.glMultMatrixf(vertexData,0); I beg pardon for that crap coding I don't wanted to do algorithme error so.. i put the value one by one :). so my DCM is 3x3 but following that video he says that opengl use a 4x4 (with zero on the edge and a ONE on the last diago element) thats why all thos stuff on thos code I just showed. And the result is really bad. depending on how I move my phone I can see a little cube rotating really fast in every direction.... SO I don't know is the mistake now Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7574930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Symbolic link to libraries for compiling java code I have a folder that has the spring libraries. I have a separate folder that contains the java code that contains the code for a simple "HelloSpring" application. In order to compile my HelloSpring application, I need to refer to the Spring libraries present in the separate folder. Is it possible to refer to this external folder during the compilation process such that when I type in javac HelloSpring.java, it properly resolves all the libraries being referred to? Is there a way to setup a symbolic link so that the java compiler can look into that to resolve the dependencies. Thanks A: You need to set the classpath to refer to your library folder. You can either do this on the command line when invoking javac, using the -cp option, or you can define a CLASSPATH environment variable. A better way to work is to use tools like Ant or Maven to handle the build process for you. It takes some time and effort to configure such tools, but certainly when your projects get larger it eventually saves you a lot of hassle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OCR scan of letters. Failed in loading training letters Using the javaocr framework from sourceforge. Trying to scan letters from a image, and training the system to recognize them. Getting this exception when loading trainer: java.io.IOException: Expected to decode 26 characters but actually decoded 33 characters in training: /Developer/MAckan/bin/LETTERS/trainLetters.PNG at net.sourceforge.javaocr.ocrPlugins.mseOCR.TrainingImageLoader.load(TrainingImageLoader.java:111) My code is like this: loader.load(this,ClassLoader.getSystemResource("LETTERS/trainLetters.PNG").getPath(), new CharacterRange('A', 'Z'), images); Another question is how to get it to train Scandinavian letters. If I enter a range A-Ö it expects 150 characters. Then when I scan I try and scan a line in the image at the time: scanner.addTrainingImages(images); final CharacterRange[] cr = new CharacterRange[1]; cr[0] = new CharacterRange('A', 'Z'); // get the first line of letters final int x1 = 0; final int y1 = 130; final int x2 = 640; final int y2 = 170; for (int i = 0; i < 15; i++) { final String text = scanner.scan(boardImage, x1, y1 + (i * 40), x2, y2 + (i * 40), cr); System.out.println("scanned " + text); } And I actually get output, but not the output I expect... Anyone have experience with the javaocr framework? Update: Solved the training issue. The training image was missing a couple of charachters and Scandinavian is not supported (?). Still getting strange output. Update2: Solved the entire issue with writing my own comparison instead. I did some manipulation of the images (reduced colors and transperency) and compared pixel by pixel and returned a diff against alafabet images. The lowest diff "wins". Works for this particular case, but I am still interested in getting OCR running. Thanks. /A A: Well, you won't like my answer but here it is: Javaocr is kind of crappy and very poorly documented. I've tried some of the code from the demo src but on other PNG files than those supplied and it doesn't really recognize all that much. Here's a library that actually worked: http://asprise.com/product/ocr/download.php?lang=java. It's not free however, well if you look at the license prices it's REALLY not free, but there you go. Option 2 would be to try out Google's brand new online ocr service: http://googlesystem.blogspot.com/2009/09/google-docs-ocr.html. I haven't tried it myself, but you should get at least better support than with Java ocr... A: Solved the entire issue with writing my own comparison instead. I did some manipulation of the images (reduced colors and transperency) and compared pixel by pixel and returned a diff against alafabet images. The lowest diff "wins". Works for this particular case, but I am still interested in getting OCR running. Thanks everyone for contributing. /A
{ "language": "en", "url": "https://stackoverflow.com/questions/7574935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strategies in Scala Is there an equivalent to Haskell Control.Parallel.Strategies or a way to achieve the same thing? That allow an existing code to be evaluated in a different way. By separating algorithm from strategy and algorithm from evaluation. A: Yes, but only in Scalaz and not in the standard library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: With the HTML5 Canvas ... how do maintain proportion? // set canvas to fullscreen $("canvas").attr('height',$(document).height()); $("canvas").attr('width', $(document).width()); //load bkgd img to canvas function dwg(){ $("canvas").drawImage({ source: "img/bkgd.jpg", x: 0, y: 0, height : $(document).height(), width : $(document).width(), fromCenter: false }); } dwg(); // resize window event $(window).resize(function(){ //console.log($(window).height()+', '+$(window).width()); $("canvas").attr('height',$(document).height()); $("canvas").attr('width', $(document).width()); dwg(); }); // Stop distort w/ jcanvas $("canvas").scaleCanvas({ x: 100, y: 100, width: 1, height: 1 }) This image should maintain a fullbleed background (some clipping is ok ) even as the background resizes. this is using the jcanvas library http://calebevans.me/projects/jcanvas/ Suggestions Please? There is a drawing function in there as well, for brevity I have omitted it. A: This fiddle shows the code needed to do what you want: http://jsfiddle.net/ctrlfrk/ZGnbb/ It's just a bit of maths on the ratios.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: document.write not working in html I am try to write inside html document. this is my javascript code: <script type="text/javascript">document.write("Hello World!")</script> I am working with chrome and get the following error: Uncaught TypeError: Object # has no method 'write' I tried alert method and it worked. EDIT: this is part of a project in scala/lift that also uses jquery if that may hint something. I suspect document object is redefined. is there a way to know that / to access the original one? A: I had a similar problem, trying to embed the google maps api in my lift application. The script also uses document.write to load external libraries. The Google Chrome console stated that there is no function document.write. The problem seems to be that XHTML does not allow document.write. ( http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite ) A solution could be to change the mime/type of your documents, e.g. by adding the following line to your Boot.scala LiftRules.useXhtmlMimeType = false More solutions are described in the link below http://scala-programming-language.1934581.n4.nabble.com/Google-Maps-API-V2-amp-V3-Ajax-Loading-td1981862.html A: I am using VS code. I was doing the same, so what I did was make the JS file and shift the JS code there, meaning the ... document.write("Printed by JavaScript."); ... part in main.js file. In index.html I just gave the path to my main.js file. It runs perfectly. src = "main.js" A: Do you have another variable called document? A: Did you try <script type="text/javascript">window.document.write("Hello World!")</script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7574943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove Button from Flex Mobile app actionbar with AS3? How exactly would i remove a Button from the actionBar "actionContent" in a flex mobile app? I tried these: this.stage.removeChild(menu_btn); this.removeChild(menu_btn); stage.removeChild(menu_btn); this.stage.removeElement(menu_btn); this.removeElement(menu_btn); stage.removeElement(menu_btn); I'm not having any luck with those. Im guessing where it is located in the actioncontent isn't considered the stage. Any ideas? <s:actionContent> <s:CalloutButton id="menu_btn" icon="@Embed('assets/images/menu/menu_btn.png')" visible="false"> <s:VGroup> <s:Button id="btn_one" label="Button" /> </s:VGroup> </s:CalloutButton> </s:actionContent> The actionContent is setup like that, I know like with most mxml stuff I could give it an ID to reference it but im not sure how how to give the action content an id number <s:actionContent id="testID"> does not work. So how can i access this to remove it? making it invisible isn't cutting it i need to actually remove it. A: Being that actionContent is a property of the ActionBar, it already is the "id" of an object, namely an Array. Try using an Array method to remove it. For instance, you could use actionContent.pop() if the thing you want to remove is the last element. Or use splice(): actionContent.splice(actionContent.indexOf(menu_btn),1); which will remove the element from the Array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to start scalala console? I am starting using scala and I am interested in using the scalala package for doing linear algebra computations. I successfully installed it through sbt but I can't (or better don't know how) start the scalala console. Can anyone point out the steps I have to take to make that possible? Thanks a lot P.S. I have read this quickstart guide but didn't help me. [EDIT] To be more clear I do not want to explicitly make includes with the standard scala console in order scalala to work. A: UPDATE: If you want start Scalala console without explicitly import those package, then maybe you need build a excutable jar directly from the GitHub repo. The following steps should work: * *git clone https://github.com/scalala/Scalala *cd Scalala *./sbt update compile proguard *java -jar target/scala_2.8.1/scalala_2.8.1-1.0.0.RC2-SNAPSHOT.min.jar And now you should get an Scala console with Scalala package imported by default. Since the document says the scalala console just a standard Scala console with default package imported. You could just run sbt under your project directory, and using console command to enter Scala console mode. Finally, type in the following code: import scalala.scalar._; import scalala.tensor.::; import scalala.tensor.mutable._; import scalala.tensor.dense._; import scalala.tensor.sparse._; import scalala.library.Library._; import scalala.library.LinearAlgebra._; import scalala.library.Statistics._; import scalala.library.Plotting._; import scalala.operators.Implicits._; Now you should be able to use Scalala just like the document sayas. A: run java -jar target/scala_2.8.1/scalala*.min.jar or the equivalent for your release of scalala. Optionally, you could run the standard scala console and type in the following includes import scalala.scalar._; import scalala.tensor._; import scalala.tensor.mutable._; import scalala.tensor.dense._; import scalala.tensor.sparse._; import scalala.library.Library._; import scalala.library.LinearAlgebra._; import scalala.library.Statistics._; import scalala.library.Plotting._; import scalala.operators.Implicits._; Was there something beyond the instructions you were having an issue with? Citing specific errors or specific problems encountered is a great way to get a more specific answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 Editor Template for List Not Populating Problem: When I load the EditorTemplate for UserModel the UserRoles list does not generate a list of UserRole editors. My models: public class UserSearchModel { [ScaffoldColumn(false)] public Guid UserId { get; set; } [DisplayName("User Name")] public string UserName { get; set; } [DisplayName("User Roles")] public UserRoles UserRoles { get; set; } } public partial class UserRoles : List<UserRole> { } public class UserRole { public string RoleName { get; set; } public bool IsChecked { get; set; } public string Description { get; set; } } My editor Templates: @model eGate.BackOffice.WebClient.Model.UserModel @Html.LabelFor(m=>m.UserName) @Html.EditorFor(m=>m.UserName) <h1>roles</h1> @Html.EditorFor(m=>m.UserRoles) @model eGate.BackOffice.WebClient.Model.UserRole @Html.LabelFor(m=>m.RoleName) @Html.LabelFor(m=>m.IsChecked) @Html.CheckBoxFor(m=>m.IsChecked) @Html.LabelFor(m=>m.Description) Actual Output Looks like: User Name [ someuser ] roles Expected Output: User Name [ someuser ] roles role1 [x] ischecked role for 1 role2 [x] ischecked role for 2 role3 [x] ischecked role for 3 A: You should just make the type List rather than deriving your own type. A: I expect that the problem is the definition of UserRoles as a separate class. Try changing the property UserRoles in the UserSearchModel class to: public List<UserRole> UserRoles { get; set; } MVC is searching for a template for the UserRoles class. Since the template is for the UserRole class, MVC fails to find any template. UPDATE Also, I overlooked that you are using EditorFor for the UserRoles model. You should use EditorForModel like so: @Html.EditorForModel(m => m.UserRoles) A: This issue looks to be more likely caused by the fact the User EditorTemplate is being served up by the popUp window of a telerik mvc grid. I have tested outside the grid popup to find that the templates work as expected. I will close this question and re-ask the correct question in another entry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flash builder 4.5: Disable shortcut keys in tree component When we have the focus on a item in TREE component in flash builder app, and start to press keys in our keyboard, the focus changes to the item that begins with the letter that we just push. For example, we have the next data in our Tree component "fruits": Fruits --Apple --Orange --Peach if we have a focus on the item 'Peach' and pressing 'a' on your keyboard, the focus will automatically move to the item 'Apples'. I NEED DISABLE THIS FUNCTION I made some attempts with event.Preventdefault() function, called from different triggers such as 'textInput' 'keyDown' 'keyFocusChange' and others but did not get the results I need. I paste some code to explain better protected function tree2_keyDownHandler(event:KeyboardEvent):void { // TODO Auto-generated method stub trace('press key!'); event.preventDefault(); } <mx:Tree id="tree2" keyDown="tree2_keyDownHandler(event)" /> Thanks in advance A: Try mx:Tree id="tree2" selectable="false" A: package yourPackage { import flash.events.KeyboardEvent; import flash.events.TimerEvent; import mx.controls.Tree; public class YourNewTree extends Tree { public var keyNav:Boolean = false; override protected function keyDownHandler(event:KeyboardEvent) : void { if(keyNav){super.keyDownHandler(event);} } override protected function keyUpHandler(event:KeyboardEvent) : void { if(keyNav){ super.keyUpHandler(event); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Splash Page For Users Who Did Not Authorize App Yet We have a facebook game that uses the Facebook C# SDK 5.2.1.0. We would like a splash page for users who have not yet authorized. My code is set up basically like this: https://gist.github.com/879932. I'm guessing I need a way to know if the user is authorized BEFORE I send them off to get authorized. Thanks! A: You can use the Javascript SDK and call FB.getLoginStatus() and let the clientside do the redirection for you. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to improve PHP code against SQL injection and other threats How can I modify this code to improve protection against sql injection and other threats? It is a MS SQL database. <?php include_once("db.php"); ?> <?php $id = $_REQUEST['id']; settype($id, 'string'); $tsql = "SELECT Table1.Fund FROM Table1 WHERE Table1.Fund='%s'"; $tsqlnew=sprintf($tsql, $id); $stmt = sqlsrv_query( $conn, $tsqlnew); if( $stmt === false) { echo "Error in query preparation/execution.\n"; die( print_r( sqlsrv_errors(), true)); } $chd = ''; while( $data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) { $chd .= '[\''.$data['Fund'] .'\'],'; } $chd = substr($chd,0,-1); ?> I'm also wondering if my db connection can be improved. Thanks for your help! <?php $myServer = "server"; $myUser = "userPlaceHolder"; $myPass = "passwordPlaceHolder"; $myDB = "SQL"; $conn = sqlsrv_connect($myServer, array('UID'=>$myUser, 'PWD'=>$myPass, 'Database'=>$myDB)); if( $conn === false ) { echo "Could not connect.\n"; die( print_r( sqlsrv_errors(), true)); } ?> A: You code does exactly NOTHING to prevent injection attacks. Merely forcing variable to have a string-data type is exactly as much protection as a piece of toilet paper provides against a tsunami. To prevent injection attacks, you must escape all data that you insert into a query string, whether it's user-provided or something you yourself have created/inserted. Best option is to use prepared statements, which relieves you of the responsibility of escaping data. Even if the data being inserted isn't "malicious", any SQL metacharacters (quotes in particular) can still destroy the query and cause syntax errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: In Java, how can I construct a File from a resource? File takes String and URI in its constructors. getClass().getResource(...) returns URL and getResourceAsStream(...) returns InputStream. Is there a way to construct a File from a resource? A: You can't. At least not in the standard case where the resource is inside a Jar. Java File Objects must point to actual file system objects (files and folders), whereas a resource is an entry in a Jar File. Trying to construct a File from a Jar resource URI will result in an exception: java.lang.IllegalArgumentException: URI is not hierarchical A: Is there a way to construct a File from a resource? Strictly speaking, no. But if you really need a File (to pass to an API), then you can create a temporary file and write the InputStream to that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Insert Page title into hidden form value with javascript/jquery? I've got a form on every page of my site via a template but I'd like to have the page title included into the emails sent via the forms so we know exactly which page the form was submitted from. Is there a simple way to do this with jquery? Thanks for any tips/ideas. A: Make a hidden element with HTML: <input id="pageTitle" type="hidden" value="" /> Include this javascript on your page (requires jQuery): $("input#pageTitle").val(document.title);
{ "language": "en", "url": "https://stackoverflow.com/questions/7574966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Locating Groovy under STS on Ubuntu I have installed Springsource Tool Suite v2.7.2 with Groovy and Grails support on Ubuntu. This works well. I want to use the Groovy installed with STS from the command line on Ubuntu. When I type which groovy I get nothing. How can I find where groovy is installed so I can add to the path and set up GROOVY_HOME? A: I found the home for my groovy and grails executables by doing this: $ which groovy /usr/bin/groovy $ file /usr/bin/groovy /usr/bin/groovy: symbolic link to '../share/groovy/bin/groovy' $ which grails /usr/bin/grails $ file /usr/bin/grails /usr/bin/grails: symbolic link to '/etc/alternatives/grails' $ file /etc/alternatives/grails /etc/alternatives/grails: symbolic link to '/usr/share/grails/1.3.7/bin/grails' So, on my Ubuntu installation, GROOVY_HOME should be /usr/share/groovy/, while GRAILS_HOME should be /usr/share/grails/1.3.7/ This was a little round-about, especially since grails happened to point to a link under /etc/alternatives/. Maybe someone has a better way! A: I think you are asking about the actual groovy installation used by STS and Eclipse. The Groovy installation used by STS is located in /path/to/sts-2.7.2/plugins/org.codehaus.groovy_1.8.2.XXXX/lib/groovy-all-1.8.2.jar. XXXX is the version of the groovy plugin currently installed. There is also a 1.7.10 version of the plugin that you could use. Just be warned that the XXXX will change whenever you update your Groovy-Eclipse. You must also be the same pPaul who asked this: http://forum.springsource.org/showthread.php?115317-Using-Groovy-installed-with-STS So, apologies in the delay for the response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Indent code in the same way as = in ex mode in Vim How can I indent code in command mode in Vim in the same way as = in visual mode? A: Try the normal command == with a range: {range}normal! == It will apply == to each line in the passed range. You can also try things with the gv= command, to reuse last selection; and take a look in the helpful '< and '> marks. A: == will fix indentation on a single line =% will fix indentation to the matching brace (if the cursor is on a brace) gg=G will go to the top of the file gg and then fix indentation to the bottom of the file =G summary - = is followed by an movement key and will fix indentation in the range specified by the motion. This sheet shows the movement key in green, as you can see there are many options
{ "language": "en", "url": "https://stackoverflow.com/questions/7574969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Security exception when passing .net 3.5 to 4.0 We have some issues while migrating our Asp.Net Web Application .Net 3.5 to .Net 4.0. It seemed that we had a Caspol Security Exception, so we added this to our web.config : <runtime> <NetFx40_LegacySecurityPolicy enabled="true"/> </runtime> and nothing changed. It seem that we cannot execute the assembly "Microsoft.Web.Management.Iis" in AspNet 4.0. We executed the caspol.exe utility in .Net 4.0 to grant full trust permission with no success. When we used the local administrator account on the application pools, all work fine. But when we used a domain adminstrator user account, we got this error below : [PolicyException: Required permissions cannot be acquired.] System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Boolean checkExecutionPermission) +6502926 System.Security.SecurityManager.ResolveCasPolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Int32& securitySpecialFlags, Boolean checkExecutionPermission) +99 [FileLoadException: Could not load file or assembly 'Microsoft.Web.Management.Iis, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)] We are running in win2k8 r2 environment with aspnet 2.0 and 4.0 running on the iis 7.5. Do you have any suggestion to solve our problems. Thanks A: We juste make a call support to microsoft to solve the problem. The problem was because our web site files are hosted on a SAN. There is an hotfix on the framework 4.0 for this issue. The hotfix is not public at the moment but is name is NDP40-KB2580188-x64.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/7574974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to store an object in the viewstate? I am using EWS to develop my email client. I found that if I store ItemId in viewstate it will cause an exception says: Type 'Microsoft.Exchange.WebServices.Data.ItemId' in Assembly 'Microsoft.Exchange.WebServices, Version=14.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable. If I store ItemId as string like: ViewState["itemId"] = id.ToString(); and then try to cast back, ItemId id = (ItemId)ViewState["itemId"]; it says I can not convert from string to ItemId. Any idea? A: You are storing string and expecting ItemId. You should store as ItemId itemId = new ItemId(); ViewState["itemId"] = itemId; However, since ItemId is not seriaziable, it cannot be stored. To store it make your serializable class inherited from ItemId and override all the members and store it in ViewState [Serializable] public class MyItemId: ItemId { // override all properties } Store like this MyItemId itemId = new MyItemId(); ViewState["itemId"] = itemId; and retrieve MyItemId id=(MyItemId)ViewState["itemId"]; A: Did you try: ItemId id = new ItemId( ViewState["itemId"] ); http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.itemid.itemid(EXCHG.80).aspx A: As the error message suggests, you can't store an object in viewstate unless it's marked as serializable. Looking at the documentation here, it seems that the ItemId class has a UniqueId property, which is a string, and a constructor which takes a string 'uniqueId' parameter. So, can you store the uniqueId in viewstate, and regenerate the object using the constructor? A: You cannot store it in ViewState. However you could probably store it in Session, since it uses the binary formatter. ViewState is serialized with the LosFormatter class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jquery mouse scroll change div position How can I use the mouse scroll event to control a div's position? I have 12 lis where only 5 of them are visible at any time. I want to be able to show different li elements when the scroll wheel scrolls. If possible, I'd like this in a circular layout. I don't want scroll my page, but something like a gallery. If you imagine all my li elements as photos, if the mouse is scrolled the photos change position in the horizontal direction, something like http://viralpatel.net/blogs/demo/javascript-mouse-scroll-wheel-event.html I need to do this with jQuery and horizontally, not with vanilla JS in the vertical. Is there a plugin or some working code? fiddle <script src="jquery.js"></script> <script> $(document).ready(function() { //jQuery code }); </script> <style> * { padding: 0; margin: 0; } div, ul { height: 100px; width: 500px; display: block; overflow: hidden; } div { position: relative; } ul { position: absolute; } li { float: left; height: 98px; width: 98px; display: block; list-style: none; border: 1px solid #aaa; } </style> <div> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> <li>12</li> </ul> </div> A: I'm having a bit of trouble figuring out what you're actually looking for. If you want jQuery tools to assist with scrolling you can use these: http://api.jquery.com/scroll/ - Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. http://api.jquery.com/scrollTop/ - Get the current vertical position of the scroll bar for the first element in the set of matched elements. You can control the position of an element during scroll by using those methods. <div id="myDiv" style="position: absolute" /> $(window).scroll(function() { $('#myDiv').css('top', $(window).scrollTop() + 'px') }); However part of your question makes it sound like you want to show 5 list items and when they scroll show 5 more using AJAX ("and if possible, I would like a circle show."). This is similar to the 'endless scrolling' concept which Twitter and other sites use. There are a bunch of plugins for this, one of them can be found here. Edit: Using the jQuery mousewheel plugin by Brandon Aaron you can do something like: CSS: *{padding:0;margin:0;} div { height:120px; width:500px; display:block; overflow:auto; } ul { width: 9999px; } li { float:left; height:98px; width:98px; display:block; list-style:none; border:1px solid #aaa;} Javascript: $('div').mousewheel(function(event, delta) { this.scrollLeft -= (delta * 30); event.preventDefault(); // Prevent the window from scrolling });
{ "language": "en", "url": "https://stackoverflow.com/questions/7574982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Download a PNG file from HTTP endpoint with query string Sorry for the poor title. I have a URL like this: http://testserver:8080/dummy/server?@_1231Fv_C When I access this URL using browser, this returns me a PNG image. But, when I try to fetch it using Jersey client API, I can't download it. (I tried java.nio as well) See my code snippet Client client = Client.create(); client.setFollowRedirects(true); WebResource r = client.resource(url); InputStream in = r.get (InputStream.class); ByteStreams.copy(in, new FileOutputStream(savedFile)); Thanks a lot for your help. A: @ characters are reserved, maybe you should encode them (change it to %40). * *URL Encoding *RFC1738 A: Are you using Guava library? Then it's worth to note that ByteStreams.copy Copies all bytes from the input stream to the output stream. Does not close or flush either stream. You Should flush & close your FileOutputStream. It will be better if you share more details e.g Exceptions etc. A: I am doing like this and its working import java.io.File; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path("/image") public class ImageService { private static final String FILE_PATH = "c:\\az-fu.png"; @GET @Path("/get") @Produces("image/png") public Response getFile() { File file = new File(FILE_PATH); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename=image_from_server.png"); return response.build(); } } Dialog when I hit from web browser:
{ "language": "en", "url": "https://stackoverflow.com/questions/7574983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook App Uncaught OAuthException: An active access token must be used to query information about the current user. thrown Hello I am trying to post to the wall of a user but the following error occurs: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown .... My facebook script is: $appId = 'xxxxxx'; //change as necessary $appUrl = "xxxxx"; //change as necessary $baseUrl = "xxxxx/"; //change as necessary // Create our Application instance. $facebook = new Facebook(array( 'appId' => $appId, 'secret' => 'xxxxxx', //change as necessary 'cookie' => true, )); $session = $facebook->getSession(); $fbme = null; // Session based graph API call. if (!$session) { $login_url = $facebook->getLoginUrl ( array ( "canvas" => true, "fbconnect" => false, "req_perms" => "user_location, email, publish_stream, friends_about_me, offline_access,", ) ); echo "<script type='text/javascript'>top.location.href = '" . $login_url. "';</script>"; } $session = $facebook->getSession(); $me = null; // Session based API call. if ($session) { try { $uid = $facebook->getUser(); $me = $facebook->api('/me'); $mail=$me[email]; } catch (FacebookApiException $e) { error_log($e); } } $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); $token=$data[oauth_token]; $attachment = array('message' => '', 'access_token' =>$token, 'name' => '', 'caption' => "", 'link' => '', 'description' => '', 'picture' => '', 'actions' => array(array('name' => 'Get Social', 'link' => '')) ); $result = $facebook->api('me/feed','post',$attachment); How can i obtain users access token? A: Open this in a browser: https://graph.facebook.com/oauth/authorize? type=user_agent& client_id=[APP ID]& redirect_uri=http%3A%2F%2Fxyz.com& scope=user_photos,email,user_birthday,user_online_presence You’ll be redirected to: http://xyz.com/#access_token=[ACCESS TOKEN]. And you have your access token, you can go ahead and use it: https://graph.facebook.com/me?access_token= [ACCESS TOKEN]
{ "language": "en", "url": "https://stackoverflow.com/questions/7574992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query output, is an input for another query does - not work I want to use the return of one query as the input for another. When I run them individually they work fine, but when I combine them in one, it does not work. The individual queries are:- select ja.id from job_applications ja join users u on u.id = ja.user_id where u.email='xxxxx@gmail.com' order by ja.updated_at desc limit 1 The output being 308480 and when I use this value as an input for another query I get my desired result select * from delayed_jobs dj where handler like "%308480%" BUT, now when I try to run it as one single query it does not work (i get no output) select * from delayed_jobs dj where handler like "%(select ja.id from job_applications ja join users u on u.id = ja.user_id where u.email='xxxxx@gmail.com' order by ja.updated_at desc limit 1)%" Please help. A: You can't execute SQL code inside of a like statement like that. You need to generate the like expression by concatenating the result together something like this: where handler like concat('%', (select ja.id from job_applications ja join users u on u.id = ja.user_id where u.email='xxxxx@gmail.com' order by ja.updated_at desc limit 1), '%') A: For dynamic SQL you should use stored procedure, like mellamokb explained in his answer. However, your query is not really dynamic and therefore you can use a subselect. For example: select * from delayed_jobs dj where handler like (select concat('%', ja.id, '%') from job_applications ja join users u on u.id = ja.user_id where u.email='xxxxx@gmail.com' order by ja.updated_at desc limit 1) UPDATE sorry, apparently i misinterpreted mellamokb's answer ... indeed it's the same as mine ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7575004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is -webkit-focus-ring-color a CSS variable? Browsing through default Webkit CSS here I noticed the following piece of code: :focus { outline: auto 5px -webkit-focus-ring-color } It seems -webkit-focus-ring-color is a variable of some sort. I thought CSS could not have variables. What is going on here? A: That's called a vendor prefix. You can check out a previously answered question about a list of VPs here. Regarding your question of variables in CSS, there is a way to use variables in CSS development. I'm sure there are other ways, but the most popular are {less css} and SASS. A: Just to be technically pedantic, it’s a keyword (just like auto or red), not a variable. And as vonkly says, it’s a keyword with a vendor prefix. Apple’s documented it e.g. here, where they describe it as a constant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I do a half m34 transformation I want to do a full rotation, but with an image swap half way through and I can't seem to be able to do that. The full rotation can be seen below. How can I make a half of this but with the nice z axis stuff? This is in a animateWithDuration block (iOS4) // Create perspective transformation CATransform3D transform = CATransform3DIdentity; transform.m34 = 1.0f / -zDistance; myView.layer.transform = transform; //- 3d myView.layer.transform = CATransform3DMakeRotation(M_PI, -1, 0, 0); A: You can do this with two blocks: // Rotate the second 'backside' view to 90 degrees and hide it CATransform3D transform = CATransform3DIdentity; transform.m34 = 1.0f / -zDistance; mySecondView.layer.transform = transform; mySecondView.layer.transform = CATransform3DMakeRotation(M_PI / 2, -1, 0, 0); mySecondView.hidden = YES; // Animate to 90 degrees [UIView animateWithDuration:0.5 animations:^{ CATransform3D transform = CATransform3DIdentity; transform.m34 = 1.0f / -zDistance; myView.layer.transform = transform; myView.layer.transform = CATransform3DMakeRotation(M_PI / 2, -1, 0, 0); } completion:^{ // Switch to the backside view myView.hidden = YES; mySecondView.hidden = NO; // Animate the remaining 90 degrees [UIView animateWithDuration:0.5 animations:^{ CATransform3D transform = CATransform3DIdentity; transform.m34 = 1.0f / -zDistance; mySecondView.layer.transform = transform; mySecondView.layer.transform = CATransform3DMakeRotation(M_PI, -1, 0, 0); } } You can also experiement with the myView.layer.isDoubleSided property, which hides the back of a view - although you will still need to toggle the hidden flag at the end of the animation otherwise the first view's buttons will still be clickable. Hope this helps! Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# chart show all labels Working on a C# web app, my issue is that only some of the values are appearing on the report (This is the X Axis I'm talking about, it only shows every other value). Its simply showing every other one. How can I show all of them? Thanks My Code: <asp:Chart ID="Chart6" runat="server" DataSourceID="SqlDataSource13" Palette="Chocolate" Width="800px"> <Series> <asp:Series Name="Series1" CustomProperties="DrawingStyle=Cylinder" IsValueShownAsLabel="True" LabelFormat="{C2}" Palette="Chocolate" XValueMember="StartItem" YValueMembers="STDCOST2"> </asp:Series> </Series> <ChartAreas> <asp:ChartArea Name="ChartArea1"> <AxisY IsLabelAutoFit="False" TextOrientation="Rotated90" TitleFont="Verdana, 7pt"> <LabelStyle Font="Microsoft Sans Serif, 6.75pt" Format="{C2}" /> </AxisY> <AxisX IsLabelAutoFit="False" LabelAutoFitMaxFontSize="8" LabelAutoFitMinFontSize="7" LabelAutoFitStyle="None"> <LabelStyle Angle="90" Font="Microsoft Sans Serif, 6pt" Interval="Auto" IsEndLabelVisible="False" /> <ScaleBreakStyle BreakLineStyle="None" /> </AxisX> <AxisX2 IsLabelAutoFit="False" LabelAutoFitMaxFontSize="8" LabelAutoFitStyle="None"> <LabelStyle Angle="45" /> </AxisX2> <Area3DStyle Enable3D="True" /> </asp:ChartArea> </ChartAreas> </asp:Chart> A: I think some are confusing values with labels. The original question refers to labels, which are being skipped. This is a repeat question of MS Chart with ASP.NET chart type “column” not showing axis x label if there are more than 9 bar in the chart The answer is Chart6.ChartAreas["ChartArea1"].AxisX.Interval = 1;
{ "language": "en", "url": "https://stackoverflow.com/questions/7575015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Problem with upgrading rubygems via rvm Trying to updgrade RubyGems to version 1.8.10 via RVM and this error: $ rvm rubygems latest Removing old Rubygems files... Installing rubygems-1.8.10 for ruby-1.9.2-p180 ... ERROR: Error running 'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global" GEM_HOME="/Users/foo/.rvm/gems/ruby-1.9.2-p180" "/Users/foo/.rvm/rubies/ruby-1.9.2-p180/bin/ruby" "/Users/foo/.rvm/src/rubygems-1.8.10/setup.rb"', please read /Users/foo/.rvm/log/ruby-1.9.2-p180/rubygems.install.log WARN: Installation of rubygems did not complete successfully. When checking the log file (rubygems.install.log) this is generated from installation: [2011-09-27 21:16:57] GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2- p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global" GEM_HOME="/Users/foo/.rvm/gems/ruby-1.9.2-p180" "/Users/foo/.rvm/rubies/ruby-1.9.2-p180/bin/ruby" "/Users/foo/.rvm/src/rubygems-1.8.10/setup.rb" unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/f_sync_dir.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_header.rb, skipping unable to convert U+00E1 to US-ASCII in conversion from ISO-8859-1 to UTF-8 to US-ASCII for lib/rubygems/package/tar_input.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_output.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_reader/entry.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_reader.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_writer.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package.rb, skipping unable to convert U+0160 from UTF-8 to US-ASCII for History.txt, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/f_sync_dir.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_header.rb, skipping unable to convert U+00E1 to US-ASCII in conversion from ISO-8859-1 to UTF-8 to US-ASCII for lib/rubygems/package/tar_input.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_output.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_reader/entry.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_reader.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package/tar_writer.rb, skipping unable to convert U+00E1 from UTF-8 to US-ASCII for lib/rubygems/package.rb, skipping unable to convert U+0160 from UTF-8 to US-ASCII for History.txt, skipping ERROR: While executing gem ... (RDoc::Error) error generating index.html: Error while evaluating /Users/foo/.rvm/gems/ruby-1.9.2-p180/gems/rdoc-3.9/lib/rdoc/generator/template/darkfish/index.rhtml: undefined method `[]' for nil:NilClass (RDoc::Error) RubyGems 1.8.10 installed Does anyone have an idea of ​​what could be wrong with the update? Have tried to remove rubygems via the RVM also, and then run the update again but no luck with it. Update: Seems like rvm could not run Ruby 1.9.2. $ rvm use 1.9.2 WARN: ruby ruby-1.9.2-p290 is not installed. To install do: 'rvm install ruby-1.9.2-p290' So after installing 1.9.2-p290 the installation of rubygems completed successfully. $ rvm use 1.9.2 Using /Users/foo/.rvm/gems/ruby-1.9.2-p290 $ rvm rubygems latest Removing old Rubygems files... Installing rubygems-1.8.10 for ruby-1.9.2-p290 ... Installation of rubygems completed successfully. That worked for me. A: Seems like rvm could not run Ruby 1.9.2. $ rvm use 1.9.2 WARN: ruby ruby-1.9.2-p290 is not installed. To install do: 'rvm install ruby-1.9.2-p290' So after installing 1.9.2-p290 the installation of rubygems completed successfully. $ rvm use 1.9.2 Using /Users/foo/.rvm/gems/ruby-1.9.2-p290 $ rvm rubygems latest Removing old Rubygems files... Installing rubygems-1.8.10 for ruby-1.9.2-p290 ... Installation of rubygems completed successfully. That worked for me. A: I fixed it by removing this file .gemrc in root cd ~ rm .gemrc rvm rubygems latest
{ "language": "en", "url": "https://stackoverflow.com/questions/7575023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Grails conditional html I was wondering how I can make this code in my view conditional - output it if there is a comment, but if there isn't a comment, don't output the empty <p class="comment"></p> <p class="comment"> ${progressItem.comment} </p> A: <g:if test="${(progressItem?.comment?.size() > 0)}"> <p class="comment"> ${progressItem.comment} </p> </g:if>
{ "language": "en", "url": "https://stackoverflow.com/questions/7575025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get the desired behavior in my TCP server? > import Network.Socket > import Control.Monad > import Network > import System.Environment (getArgs) > import System.IO > import Control.Concurrent (forkIO) > main :: IO () > main = withSocketsDo $ do > putStrLn ("up top\n") > [portStr] <- getArgs > sock' <- socket AF_INET Stream defaultProtocol > let port = fromIntegral (read portStr :: Int) > socketAddress = SockAddrInet port 0000 > bindSocket sock' socketAddress > listen sock' 1 > putStrLn $ "Listening on " ++ (show port) > (sock, sockAddr) <- Network.Socket.accept sock' > handle <- socketToHandle sock ReadWriteMode > sockHandler sock handle > -- hClose handle putStrLn ("close handle\n") > sockHandler :: Socket -> Handle -> IO () > sockHandler sock' handle = forever $ do > hSetBuffering handle LineBuffering > forkIO $ commandProcessor handle > commandProcessor :: Handle -> IO () > commandProcessor handle = do > line <- hGetLine handle > let (cmd:arg) = words line > case cmd of > "echo" -> echoCommand handle arg > "add" -> addCommand handle arg > _ -> do hPutStrLn handle "Unknown command" > > echoCommand :: Handle -> [String] -> IO () > echoCommand handle arg = do > hPutStrLn handle (unwords arg) > addCommand :: Handle -> [String] -> IO () > addCommand handle [x,y] = do > hPutStrLn handle $ show $ read x + read y > addCommand handle _ = do > hPutStrLn handle "usage: add Int Int" I'm noticing some quirks in it's behavior, but the one I want to address for the moment is what happens when a client disconnects with the server. When that happens, the server throws the following exception endlessly, and will not respond to further client connections. strawboss: : hGetLine: end of file I've tried flushing the handle, and closing the handle. I think that closing the handle is the right thing to do, but I cannot figure out where te correct place to close the handle is. So my first question is: Is the solution to this problem a judicious hClose placement in the code? If not, where does the problem lie? A: There are several problems in this code. The main one is that you have your forever in the wrong place. What I assume you want is to endlessly accept connections, and deal with them in sockHandler, whereas your code currently only ever accepts a single connection, and then endlessly forks off worker threads to handle that single connection in parallel. This causes the mess you're experiencing. sockHandler sock' handle = forever $ do ... forkIO $ commandProcessor handle Instead, you'll want to move the forever to main: forever $ do (sock, sockAddr) <- Network.Socket.accept sock' handle <- socketToHandle sock ReadWriteMode sockHandler sock handle However, you will still get an exception when a client disconnects, because you're not checking if the connection has ended before calling hGetLine. We can fix this by adding using hIsEOF. You can then safely do a hClose on the handle once you know you're done with it. Here's your code with these modifications in place. I also took the liberty of restructuring your code a little. import Network.Socket import Control.Monad import Network import System.Environment (getArgs) import System.IO import Control.Concurrent (forkIO) import Control.Exception (bracket) main :: IO () main = withSocketsDo $ do putStrLn ("up top\n") [port] <- getArgs bracket (prepareSocket (fromIntegral $ read port)) sClose acceptConnections prepareSocket :: PortNumber -> IO Socket prepareSocket port = do sock' <- socket AF_INET Stream defaultProtocol let socketAddress = SockAddrInet port 0000 bindSocket sock' socketAddress listen sock' 1 putStrLn $ "Listening on " ++ (show port) return sock' acceptConnections :: Socket -> IO () acceptConnections sock' = do forever $ do (sock, sockAddr) <- Network.Socket.accept sock' handle <- socketToHandle sock ReadWriteMode sockHandler sock handle sockHandler :: Socket -> Handle -> IO () sockHandler sock' handle = do hSetBuffering handle LineBuffering -- Add the forkIO back if you want to allow concurrent connections. {- forkIO $ -} commandProcessor handle return () commandProcessor :: Handle -> IO () commandProcessor handle = untilM (hIsEOF handle) handleCommand >> hClose handle where handleCommand = do line <- hGetLine handle let (cmd:arg) = words line case cmd of "echo" -> echoCommand handle arg "add" -> addCommand handle arg _ -> do hPutStrLn handle "Unknown command" echoCommand :: Handle -> [String] -> IO () echoCommand handle arg = do hPutStrLn handle (unwords arg) addCommand :: Handle -> [String] -> IO () addCommand handle [x,y] = do hPutStrLn handle $ show $ read x + read y addCommand handle _ = do hPutStrLn handle "usage: add Int Int" untilM cond action = do b <- cond if b then return () else action >> untilM cond action
{ "language": "en", "url": "https://stackoverflow.com/questions/7575026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Connection attempt failed with "EAI_NODATA - No address associated with nodename" in filezilla I get the following error when I try to use Filezilla to connect to newly created domain: Connection attempt failed with "EAI_NODATA - No address associated with nodename" I purchased domain name from "Bigrock.com" and purchased net space from "125mb.com". I have already changed the name servers in the cpanel of "bigrock" to the "125mb" name-servers. I have also uploaded the files in cpanel of "125mb". When I open filezilla, I provide values as shown here: host : koshh.co.in (this is the domain name I purchased) username : ******* password : ******* Port : (default) A: I was getting the same error trying to connect to host name in FileZilla: ftp.news.domain.com I changed to: news.domain.com And worked. A: it simply means your domain name is not resolving, if domain is registered newly, then wait at least 4 to 8 hours (recommended 24-48 hours). If you have been provided with IP address with your web hosting account details, then you can use IP address instead of domain name (ex. ftp.your-domain-name.xom) If everything above is already tried out then you should contact your web hosting provider and your domain name registrar for further assistance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to keep accessory view set when leaving the view then coming back later I have not attempeted this before so would like people opinion on how best to handle tableviewcell tick accessory, I have set this up so that when the user selects their uitableview cell they are directed back to the main view and the value of the cell selected is loaded into the main view, I have done this using protocols and delegates like so My question is, if the user decides to go back to the view where the accessory is how do I make sure the tick stays their? is their a special method I can use? or will i have to pass the indexpath to the main view then back again using delegates and protocols? Anyway any help would be greatly appreciated. A: You have the answer in your question. You will need to keep a reference with what indexPath was selected. And you this value can be saved on to AppDelegate or which ever method you may choose. When the user wishes to go back to the view, you will simply need to check for saved values, and load them on to the UITableView with tableView reloadData. You will have to set the accessoryView in the cellForRowAtIndexPath and provide the check for saved values there. You can reloadData in the viewWillAppear method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework single method for Save/Update The problem is I'm trying to find a single method to save an entity, be it a new entity or an already loaded entity. Most all code samples separate Add and Save methods which goes against so many other current designs of having a single Save() method. Let me state I've read the other posts. I've looked at the team blog on repository pattern as well which has a single AddObject() method that I can't seem to find by assuming it just is an Add(object). If we load an object and save it, the context knows about it. A new object we MUST add. If we add an existing object - it will send it over as an insert. I want one save procedure here. A user shouldn't have to know to call Add or Update, a Save() should suffice. With that said, whats the best route here for a single save solution that covers in the same method (only the save, not the load): 1. loading an entity, saving back to the db. 2. Creating a new entity, saving it to the db. So I'm looking for an implementation that in all cases can just be ICustomerRepository.Save(Customer customer) What solution would you be using that works? The following code in a Save(entity) method seems to work for me //If the primary key is empty, its a new record if (order.OrderId == 0) { _context.Orders.Add(order); } if (_context.Entry(order).State == System.Data.EntityState.Detached) { //Need to set modified so any detached entities are updated otherwise they won't be sent across to the db. Since it would've been outside the context, change tracking wouldn't have occurred anyways so we have no idea about its state - save it! _context.Orders.Attach(order); _context.Entry(order).State = System.Data.EntityState.Modified; } The issue here though is with a Generic Repository implementation there is no clear way here without querying what the key is and checking its value then via reflection which isn't clean. A: Generic repository is fairy tale. The only valid usage of repository pattern is specific repository and specific repository knows what type the key is and what is its default value. In the same way you can complain that your generic code will not work if your keys are not generated in the database but in the application. EF doesn't have any support for single method processing and it cannot be simply added. To make it work correctly you would need something on SQL level to do conditional insert / update (or merge in SQL server 2008). EF doesn't have anything like that and it separates both operations all the way to command execution. That means the only way to achieve that is either using some "knowledge" as you shown in your code sample or by checking existence of the entity in database with separate database call or using stored procedure. A: public abstract class EntityObject { /*Allows for this: T UpdateOrInsert<T>(T item) where T : EntityObject { T foundItem = depDA.Set<T>().Find(item.EntityKey); return foundItem; } etc inherit entity partials from this partial class MyObject : EntityObject { override int EntityKey { get { return MyObjectID; } } } */ public abstract int EntityKey { get; } } pop this method into a Helper class public static T SaveEntity<T>(T item, DbContext context) where T : EntityObject { T foundItem = context.Set<T>().Find(item.EntityKey); if (foundItem == null) { //INSERT foundItem = context.Set<T>().Add(item as T); } else { //UPDATE foundItem = item; } context.SaveChanges(); return foundItem; } Voila! A: If you use self tracking entities then the entity will keep track of the state and Insert or Update as needed without having to have separate methods
{ "language": "en", "url": "https://stackoverflow.com/questions/7575031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Writing verification steps for PL/SQL Sequence I am writing the launch plan for one of my code. In which, for each step i have to write a verification step which will tell if the deployment/change has been made properly. Like if there is an alter table command to add a new column then as a verification, I would be using select column_name from table as verification step. I am looking for a verification step for my sequence script. My sequence scripts is dropping the old sequence and re-creating it with initial value changed. lets say if my last sequece was on 10071 - the new sequece would start from 100710. I wrote the following query SELECT LAST_NUMBER FROM all_sequences WHERE sequence_name = 'SEQNAME'; Now, my question is, would that give the last number of my new sequence or the old sequence? P.S: I can't use sequence NextValue - it would cause the system to miss 1 number and will mess up the whole system. However, I am open for the options in which my *next_value* can be utlizied, automatically. A: Now, my question is, would that give the last number of my new sequence or the old sequence? Err ... Why not just try it as suggested by Randy in the comments ? SQL> !cat /tmp/sql.sql create sequence foo start with 10; select min_value, max_value, increment_by, last_number from user_sequences where sequence_name = 'FOO'; drop sequence foo; create sequence foo start with 20; select min_value, max_value, increment_by, last_number from user_sequences where sequence_name = 'FOO'; drop sequence foo; SQL> @/tmp/sql Sequence created. MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER ---------- ---------- ------------ ----------- 1 1.0000E+28 1 10 Sequence dropped. Sequence created. MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER ---------- ---------- ------------ ----------- 1 1.0000E+28 1 20 Sequence dropped. SQL> A: LAST_NUMBER will not be accurate if your sequence uses a cache (which is the default) SQL> CREATE SEQUENCE seq_1; Sequence created. SQL> SQL> SELECT seq_1.nextval FROM dual; NEXTVAL ---------- 1 SQL> SQL> SELECT sequence_name, 2 min_value, 3 last_number 4 FROM user_sequences 5 WHERE sequence_name = 'SEQ_1'; SEQUENCE_NAME MIN_VALUE LAST_NUMBER ------------------------------ ---------- ----------- SEQ_1 1 21 SQL> SQL> SELECT seq_1.nextval FROM dual; NEXTVAL ---------- 2 SQL> SQL> SELECT sequence_name, 2 min_value, 3 last_number 4 FROM user_sequences 5 WHERE sequence_name = 'SEQ_1'; SEQUENCE_NAME MIN_VALUE LAST_NUMBER ------------------------------ ---------- ----------- SEQ_1 1 21 SQL>
{ "language": "en", "url": "https://stackoverflow.com/questions/7575035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding custom META tag to ActionMailer email in Rails 2.3.8? I'm sending an email using an ActionMailer class in Rails 2.3.8. I need to add a META tag to the HEAD of the email. Specifically, I want to add this (ultimately for handling special CSS3 on mobile devices): <meta name="viewport" content="width=device-width" /> I can't find a way to add this to the HEAD section of the email. Do I need to create a custom email layout that I use? If so, how do I do that? It seems like there should be an easier way than creating a custom layout. A: It sounds like you want to send a HTML email and set the meta tag in the view. Try updating your ActionMailer content-type with something like: class Notifier < ActionMailer::Base default 'content-type' => 'text/html' end Then add the following line to your view's layout or <head> section: <meta name="viewport" content="width=device-width" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7575040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change #hash tag to link on page load How to change # tag + Character to link using javascript This is going #right on the way with This is going <a href="http://twitter.com/#!/search/right">right</a> on the way even this is also acceptable This is going <a href="http://twitter.com/#!/search/right">#right</a> on the way The page lots's of # (hash) tag in different classes and id's A: var string = "This is going #right on the way"; string.replace(/#(\S*)/g,'<a href="http://twitter.com/#!/search/$1">$1</a>') Demo: http://jsfiddle.net/dKm82/ A: here is my suggestion (function(){ $.fn.hashlink = function(){ this.text(this.text().replace(\#(w+)\),"<a href='twitter.com/#!/search/$1'>$1</a>") text = \#w+\g. } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7575041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Mobile: Loading Message not appearing I have made a web app using jQuery Mobile, jQuery and html. It is basically an rss reader for its site. $(document).ready(function() { $('[data-role=button]').click(function() { var $id = $(this).attr('id'); switch($id) { case 'news-button': var type = 'news'; var url = '/tag/news/'; break; //etc... } $.get('http://wiiuandmii.com' + url + 'feed/', function(data) { $('#' + type + '-content').empty(); var i = 0; $(data).find('item').each(function() { i = i + 1; $('#' + type + i).empty().remove(); var $item = $(this); var html = '<li>'; html += '<a href="#'+ type + i + '">'; html += $item.find('image').text(); html += '<h3 style="color: #01acca;">' + $item.find('title').text() + '</h3>'; html += '<p>' + $item.find('pubDate').text() + '</p>'; html += '</a>'; html += '</li>'; $('#' + type + '-content').append($(html)); $('#' + type + '-content').find('img.attachment-thumbnail').removeClass().removeAttr('width').removeAttr('height'); $('#' + type + '-content').listview('refresh'); var page = '<div data-role="page" id="' + type + i + '" data-url="' + type + i + '">'; page += '<div data-role="header" data-theme="c" data-position="fixed"><a href="#home" data-rel="back" data-theme="b" data-icon="arrow-l">Back</a><h1 style="margin-top:0px; margin-bottom:0px;"><img src="images/header.png" title="Wii U and Mii" alt="Wii U and Mii"/></h1></div>'; page += '<div data-role="content" data-theme="c" class="main-' + type + i + '">'; page += '<h1 style="color: #01acca;">' + $item.find('title').text() + '</h1>'; page += '<p>' + $item.find('dc:creator').text() + '</p>'; page += $item.find('desc').text(); page += '</div>'; page += '<div data-role="footer" data-theme="c"></div>'; page += '</div>'; $('body').append($(page)); var test = '#' + type + i; $(test).page(); }); }); }); }); When the button on the home page is clicked it page transitions to the #news page just fine. The problem is, the content section of the #news page remains blank for about 5 seconds as the content is loading. The loading message does not appear. What should happen is the loading message should appear on the #home page whilst all the content is loaded up, and then transition to the #news page after it has been filled. Am I triggering the loading of the content on the wrong event for the effect I want, if so which event should I be using? EDIT on 30/9/2011 I have managed to get the page transition to wait until the list has been fully loaded before it transitions, however the loading message still does not appear. I used: $('#news').live('pagebeforeshow',function(event){ $.mobile.showPageLoadingMsg(); instead of document ready and the .click and I used: $.ajax({ url: 'http://wiiuandmii.com' + url + 'feed/', async: false, success:function(data){ instead of the .get() A: Although there is already an accepted answer, I wanted to add that I had the very same issue and I solved moving the showPageLoadingMsg call from the pagebeforeshow to the pageshow handler. Hope this helps A: A member on the github-jQM forum suggested the following workaround that worked for me. Note, I am using jQM 1.0b1. $('.ui-loader h1').text('my custom loading msg..'); Ref.: https://github.com/jquery/jquery-mobile/issues/1178
{ "language": "en", "url": "https://stackoverflow.com/questions/7575043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the correct procedure for managing OSGi bundle dependencies? I'm about to start working on an application that I'd like to run in an OSGi container, like Virgo. Virgo's core platform supplies many of the dependencies I'm interested in, like the Spring Framework, but I'd also like to use Spring Integration. Spring Integration's jars are ready-to-go OSGi bundles, and are available to me along with many other third-party dependencies in an Ivy repository. To tell the OSGi container that my bundle depends on, say, Spring Integration, I need to add relevant packages or bundles to my Manifest -- I know how to do this and understand how that works. What I'd like to understand is how to develop against, resolve, build and eventually deploy third-party bundles available in some kind of repository (preferably Ivy). In the past I've accomplished this in two ways: * *Add the dependencies to the target platform, or in this case, the Virgo ext repository *Keep a copy of the dependency in my workspace, export it as part of the build Neither of these solutions seem scalable or especially elegant. I'm interested in using Virgo 3.0.0 or Equinox and my development environment is Eclipse, if a different OSGi container or development environment will make my life easier, I'm happy to switch. To make this crystal clear, I'd like to know: * *How do I develop against OSGi bundles in an external repository (e.g. the bundles live in Ivy)? *How do I build and deploy my bundle along with its required external dependencies? A: You can define an external Virgo repository to point at a local copy of an Ivy repo as explained in the Virgo User Guide under "Configuring the Local Provisioning Repository". This repository can also be used when Virgo is launched from Eclipse. Note that we are working on p2 integration for Virgo 3.5 and this will give you some further options. A: AFAIK that is implementation specific. If you are using Equinox, then p2 is the provisioning system you are looking for. I would assume that other implementations would have their own methods/tools for accomplishing similar functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: with :hover or with hover event for buttons? I'm usually using an <a> to make block type buttons for example: a { color:#fff; display:block; background-color:#ff0000; } a:hover { background-color:#c80000; } Then I put href="javascript:void(0);" on the <a> tag. I'm doing this because :hover on a div element is not good for backwards compatibility. This being said I was thinking originally to use as little JavaScript as possible but I'm starting to think doing this approach is not a great thing? What would you guys use? EDIT: I only bring this up because I noticed that Google+ was using for some of their buttons. EDIT #2: I also noticed on Google+ they have a slight animation on their buttons, so maybe that's why they are using 's A: div:hover will work on all browsers except Internet Explorer 6. But that browser is more than 10 years old. The only downside of using div:hover in IE6 is that they won't get the hover effect, but they can still use (click) the button. So it won't break in IE6, just look a little bit different than in other browsers. A: You could just do <a href='#' onclick='return false;'>. (Thanks commenters!) You shouldn't feel constrained to use 'as little javascript as possible', but also I don't think javascript is necessary for this particular bit. EDIT: in case I didn't answer your question directly, I don't think there's anything wrong with using <a>, <input>, or <button>, but I'd stay away from <div> if possible if only because it is not as semantically specific. A: Use the div + jQuery IMO $('.myDivClass').hover( function(){ $(this).css('background-color','#c80000'); }, function(){ $(this).css('background-color','#ff0000'); }); A: I would recommend you use a div. Unless you need to go back to, say, IE 5-6 then it shouldn't be an issue. A: Use whatever html element is semantically correct. If you are making buttons, why not use <button>? A: I use <a>'s quite often for this, actually. Every browser works with them, and it's usually just easier that way. Why use a div when you don't need to? A: Using anchor gives your user ability to right-click on it and open link in another tab. Also if you want for search engines to follow links I'd leave 'a'. I usually use 'div' in case where it is dynamic behavior meaning its not simple redirect to different URL but some AJAX or DOM altering action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: To GC or Not To GC I've recently seen two really nice and educating languages talks: This first one by Herb Sutter, presents all the nice and cool features of C++0x, why C++'s future seems brighter than ever, and how M$ is said to be a good guy in this game. The talk revolves around efficiency and how minimizing heap activity very often improves performance. This other one, by Andrei Alexandrescu, motivates a transition from C/C++ to his new game-changer D. Most of D's stuff seems really well motivated and designed. One thing, however, surprised me, namely that D pushes for garbage collection and that all classes are created solely by reference. Even more confusing, the book The D Programming Language Ref Manual specifically in the section about Resource Management states the following, quote: Garbage collection eliminates the tedious, error prone memory allocation tracking code necessary in C and C++. This not only means much faster development time and lower maintenance costs, but the resulting program frequently runs faster! This conflicts with Sutter's constant talk about minimizing heap activity. I strongly respect both Sutter's and Alexandrescou's insights, so I feel a bit confused about these two key questions * *Doesn't creating class instances solely by reference result in a lot of unnecesseary heap activity? *In which cases can we use Garbage Collection without sacrificing run-time performance? A: To directly answer your two questions: * *Yes, creating class instances by reference does result in a lot of heap activity, but: a. In D, you have struct as well as class. A struct has value semantics and can do everything a class can, except polymorphism. b. Polymorphism and value semantics have never worked well together due to the slicing problem. c. In D, if you really need to allocate a class instance on the stack in some performance-critical code and don't care about the loss of safety, you can do so without unreasonable hassle via the scoped function. *GC can be comparable to or faster than manual memory management if: a. You still allocate on the stack where possible (as you typically do in D) instead of relying on the heap for everything (as you often do in other GC'd languages). b. You have a top-of-the-line garbage collector (D's current GC implementation is admittedly somewhat naive, though it has seen some major optimizations in the past few releases, so it's not as bad as it was). c. You're allocating mostly small objects. If you allocate mostly large arrays and performance ends up being a problem, you may want to switch a few of these to the C heap (you have access to C's malloc and free in D) or, if it has a scoped lifetime, some other allocator like RegionAllocator. (RegionAllocator is currently being discussed and refined for eventual inclusion in D's standard library). d. You don't care that much about space efficiency. If you make the GC run too frequently to keep the memory footprint ultra-low, performance will suffer. A: It's not either "garbage collection" or "tedious error prone" handwritten code. Smart pointers that are truly smart can give you stack semantics and mean you never type "delete" but you aren't paying for garbage collection. Here's another video by Herb that makes the point - safe and fast - that's what we want. A: Another point to consider is the 80:20 rule. It is likely that that vast majority of the places you allocate are irrelevant and you won't gain much over a GC even if you could push the cost there to zero. If you accept that, then the simplicity you can gain by using a GC can displace the cost of using it. This is particularly true if you can avoid doing copies. What D provides is a GC for the 80% cases and access to stack allocation and malloc for the 20%. A: Even if you had ideal garbage collector, it still would have been slower than creating things on stack. So you have to have a language that allows both at the same time. Furthermore, the only way to achieve the same performance with garbage collector as with manually managed memory allocations (done the right way), is to make it do the same things with memory as experienced developer would have had done, and that in many cases would require a garbage collector decisions to be made in compile-time and executed in run-time. Usually, garbage collection makes things slower, languages working with dynamic memory only are slower, and predictability of execution of programs written in those languages is low while latency of execution is higher. Frankly, I personally don't see why one would need a garbage collector. Managing memory manually is not hard. At least not in C++. Of course, I won't mind compiler generate code that clean-ups all things for me as I would have done, but this doesn't seem possible at the moment. A: In many cases a compiler can optimize heap-allocation back to stack allocation. This is the case if your object doesn't escape the local scope. A decent compiler will almost certainly make x stack-allocated in the following example: void f() { Foo* x = new Foo(); x->doStuff(); // Assuming doStuff doesn't assign 'this' anywhere // delete x or assume the GC gets it } What the compiler does is called escape analysis. Also, D could in theory have a moving GC, which means potential performance improvements by improved cache usage when the GC compacts your heap objects together. It also combats heap fragmentation as explained in Jack Edmonds' answer. Similar things can be done with manual memory management, but it's extra work. A: The reason creating an object on the heap is slower than creating it on the stack is that the memory allocation methods need to deal with things like heap fragmentation. Allocating memory on the stack is as simple as incrementing the stack pointer (a constant-time operation). Yet, with a compacting garbage collector, you don't have to worry about heap fragmentation, heap allocations can be as fast as stack allocations. The Garbage Collection page for the D Programming Language explains this in more detail. The assertion that GC'd languages run faster is probably assuming that many programs allocate memory on the heap much more often than on the stack. Assuming that heap allocation could be faster in a GC'd language, then it follows that you have just optimized a huge part of most programs (heap allocation). A: A incremental low priority GC will collect garbage when high priority task are not running. The high priority threads will run faster since no memory deallocation will be done. This is the idea of Henriksson's RT Java GC see http://www.oracle.com/technetwork/articles/javase/index-138577.html A: An answer to 1): As long as your heap is contiguous, allocating on it is just as cheap as allocating on the stack. On top of that, while you allocate objects that lie next to each other, your memory caching performance will be great. As long as you don't have to run the garbage collector, no performance is lost, and the heap stays contiguous. That's the good news :) Answer to 2): GC technology has advanced greatly; they even come in real-time flavors nowadays. That means that guaranteeing contiguous memory is a policy-driven, implementation-dependent issue. So if * *you can afford a real-time gc *there are enough allocation-pauses in your application *it can keep your free-list a free-block You may end up with better performance. Answer to unasked question: If developers are freed from memory-management issues, they may have more time to spend on real performance and scalability aspects in their code. That's a non-technical factor coming into play, too. A: Garbage collection does in fact slow code down. It's adding extra functionality to the program that has to run in addition to your code. There are other problems with it as well, such as for example, the GC not running until memory is actually needed. This can result in small memory leaks. Another issue is if a reference is not removed properly, the GC will not pick it up, and once again result in a leak. My other issue with GC is that it kind of promotes lazyness in programmers. I'm an advocate of learning the low level concepts of memory management before jumping into higher level. It's like Mathematics. You learn how to solve for the roots of a quadratic, or how to take a derivative by hand first, then you learn how to do it on the calculator. Use these things as tools, not crutches. If you don't want to hit your performance, be smart about the GC and your heap vs stack usage. A: My point is that GC is inferior to malloc when you do normal procedural programming. You just go from procedure to procedure, allocate and free, use global variables, and declare some functions _inline or _register. This is C style. But once you go higher abstraction layer, you need at least reference counting. So you can pass by reference, count them and free once the counter is zero. This is good, and superior to malloc after the amount and hierarchy of objects become too difficult to manage manually. This is C++ style. You will define constructors and destructors to increment counters, you will copy-on-modify, so the shared object will split in two, once some part of it is modified by one party, but another party still needs the original value. So you can pass huge amount of data from function to function without thinking whether you need to copy data here or just send a pointer there. The ref-counting does those decisions for you. Then comes the whole new world, closures, functional programming, duck typing, circular references, asynchronouse execution. Code and data start mixing, you find yourself passing function as parameter more often than normal data. You realize that metaprogramming can be done without macros or templates. Your code starts to soak in the sky and loosing solid ground, because you are executing something inside callbacks of callbacks of callbacks, data becomes unrooted, things become asynchronous, you get addicted to closure variables. So this is where timer based, memory-walking GC is the only possible solution, otherwise closures and circular references are not possible at all. This is JavaScript way. You mentioned D, but D is still improved C++ so malloc or ref counting in constructors, stack allocations, global variables (even if they are compicated trees of entities of all kinds) is probably what you choose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: How to do another action, but still show the same url in browser in cakephp I want to call another action in cakephp . I want to run all the code in the action and render the view of that action. I know this can be done using $this->requestAction(), but the problem here is that it is not setting my title for the page which im doing in the called action. And i don't want to use redirect because it changes the url in my browser(ie it sends http 302). A: From inside any action, you can manually render any view using $this->render (see api docs). Of course, you'll have to set the variables required on the other view beforehand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exception message: no such file to load in rails application I have included test_helper.rb under test in my rails application. I have even included require 'test_helper' in my test.rb files under test->unit. When I run all the test in RubyMine for the application, I get the following error: I have the latest versions of all RubyMine 3.2, ruby 1.9.2p290 and Rails 3.1.0. /Users/im/.rvm/rubies/ruby-1.9.2-p290/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb Testing started at 3:19 PM ... Work directory: /Users/im/RubymineProjects/BackChannelApp} Loading files.... ========================================= Fail to load: /Users/im/RubymineProjects/BackChannelApp/test/performance/browsing_test.rb:1 Exception message: no such file to load -- test_helper /Users/im/RubymineProjects/BackChannelApp/test/performance/browsing_test.rb:1:in `require' /Users/im/RubymineProjects/BackChannelApp/test/performance/browsing_test.rb:1:in `<top (required)>' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `require' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `block in load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `each' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:101:in `<top (required)>' -e:1:in `load' -e:1:in `<main>' Fail to load: /Users/im/RubymineProjects/BackChannelApp/test/unit/helpers/posts_helper_test.rb:1 Exception message: no such file to load -- test_helper /Users/im/RubymineProjects/BackChannelApp/test/unit/helpers/posts_helper_test.rb:1:in `require' /Users/im/RubymineProjects/BackChannelApp/test/unit/helpers/posts_helper_test.rb:1:in `<top (required)>' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `require' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `block in load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `each' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:101:in `<top (required)>' -e:1:in `load' -e:1:in `<main>' Fail to load: /Users/im/RubymineProjects/BackChannelApp/test/unit/helpers/users_helper_test.rb:1 Exception message: no such file to load -- test_helper /Users/im/RubymineProjects/BackChannelApp/test/unit/helpers/users_helper_test.rb:1:in `require' /Users/im/RubymineProjects/BackChannelApp/test/unit/helpers/users_helper_test.rb:1:in `<top (required)>' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `require' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `block in load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `each' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:101:in `<top (required)>' -e:1:in `load' -e:1:in `<main>' Fail to load: /Users/im/RubymineProjects/BackChannelApp/test/unit/post_test.rb:1 Exception message: no such file to load -- test_helper /Users/im/RubymineProjects/BackChannelApp/test/unit/post_test.rb:4:in `require' /Users/im/RubymineProjects/BackChannelApp/test/unit/post_test.rb:4:in `<top (required)>' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `require' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `block in load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `each' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:101:in `<top (required)>' -e:1:in `load' -e:1:in `<main>' Fail to load: /Users/im/RubymineProjects/BackChannelApp/test/unit/user_test.rb:1 Exception message: no such file to load -- test_helper /Users/im/RubymineProjects/BackChannelApp/test/unit/user_test.rb:1:in `require' /Users/im/RubymineProjects/BackChannelApp/test/unit/user_test.rb:1:in `<top (required)>' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `require' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:48:in `block in load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `each' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:40:in `load_scripts_to_object_space' /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:101:in `<top (required)>' -e:1:in `load' -e:1:in `<main>' Creating sqlite :memory: database -- create_table("posts", {:force=>true}) -> 0.0346s -- create_table("users", {:force=>true}) -> 0.0010s -- initialize_schema_migrations_table() -> 0.0008s -- assume_migrated_upto_version(20110926132602, ["db/migrate"]) -> 0.0005s 1. /Users/im/RubymineProjects/BackChannelApp/test/test_helper.rb:1 1 files were loaded. ========================================= Searching test suites... ========================================= DEPRECATION WARNING: ActiveSupport::JSON::CircularReferenceError is deprecated! Use ActiveSupport::JSON::Encoding::CircularReferenceError instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) DEPRECATION WARNING: ActiveSupport::JSON::CircularReferenceError is deprecated! Use ActiveSupport::JSON::Encoding::CircularReferenceError instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) DEPRECATION WARNING: Fixtures is deprecated! Use ActiveRecord::Fixtures instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) DEPRECATION WARNING: Fixtures is deprecated! Use ActiveRecord::Fixtures instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) DEPRECATION WARNING: Fixture is deprecated! Use ActiveRecord::Fixture instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) DEPRECATION WARNING: Fixture is deprecated! Use ActiveRecord::Fixture instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) Test suite #1: ActionDispatch::IntegrationTest Ignored because it is default rails empty test suite ========================================= Test suite #1: ActiveSupport::TestCase Ignored because it is default rails empty test suite ========================================= Test suite #1: ActionController::TestCase Ignored because it is default rails empty test suite DEPRECATION WARNING: ActiveSupport::SecureRandom is deprecated! Use SecureRandom instead. (called from is_test_case_class? at /Applications/RubyMine 3.2.4.app/rb/testing/runner/tunit_in_folder_runner.rb:80) ========================================= Test suite #1: ActiveRecord::TestCase Ignored because it is default rails empty test suite ========================================= 0 test suites, 0 tests, 0 assertions, 0 failures, 0 errors Process finished with exit code 0 What am I missing? Thanks! A: test_helper.rb is located within the test directory. You are running the tests from the root directory, which means the path to the file is wrong. Try running your tests from the test directory. If you want to run your tests from the root directory, you would have to change this to require File.join(File.dirname(__FILE__), '..', 'test_helper.rb'), where FILE is the path to the file that contains this line (your test case), and the rest is the path of test_helper.rb, relative to that file. This way, where you run the test from is irrelevant. A: In my situation (RM 7.1 / Win7 / Rails 3.0), I had to do the following: Add "-Itest" at the beginning of "Ruby arguments" Note: Changing the working directory to 'test' didn't work for me. Source: https://devnet.jetbrains.com/message/5490675#5490675
{ "language": "en", "url": "https://stackoverflow.com/questions/7575057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Delegates as Properties: Bad Idea? Consider the following control (snipped for brevity): public partial class ConfigurationManagerControl : UserControl { public Func<string, bool> CanEdit { get; set;} public Func<string, bool> CanDelete { get; set; } public Dictionary<string, string> Settings { get { return InnerSettings; } set { InnerSettings = value; BindData(); } } private Dictionary<string, string> InnerSettings; private void OnListIndexChanged(object sender, EventArgs e) { this.EditButton.Enabled = false; this.DeleteButton.Enabled = false; var indices = this.List.SelectedIndices; if (indices.Count != 1) { return; } var index = indices[0]; var item = this.List.Items[index]; if (this.CanEdit != null) { this.EditButton.Enabled = this.CanEdit(item.Text); } if (this.CanDelete != null) { this.DeleteButton.Enabled = this.CanDelete(item.Text); } } } There's more to this control, but suffice it to say that it allows a user to add, edit, and delete the entries in a Dictionary<string, string>. In order to determine whether or not it should allow the user to edit or delete the entries, it uses the delegate method properties, CanDelete and CanEdit, which are provided by the form or control that hosts it: public class SetupWizard : Form { public SetupWizard() { InitializeComponent(); this.SettingManager.CanEdit = CanEditSetting; this.SettingManager.CanDelete = CanDeleteSetting; } private static bool CanEditSetting(string item) { var lockedSettings = new[] { "LicenseHash", "ProductHash" }; return !lockedSettings.Contains(item.ToLower()); } private static bool CanDeleteSetting(string item) { var lockedSettings = new[] { "LicenseHash", "ProductHash", "UserName", "CompanyName" }; return !lockedSettings.Contains(item.ToLower()); } } I find that this design is both satisfactory and worrisome at the same time. On the one hand, it seems to solve the problem using the simplest solution that works (it certainly separates the concerns nicely). On the other hand, I have this nagging concern that I am using delegates improperly and should be using an event, instead (even though I do not need multiple listeners, and only need the caller to tell me if the item is editable). And then, on the other other hand, there's the chance that there's a completely different design that I haven't even considered that might solve the problem in a vastly superior way. So. Is this design technically correct, maintainable, and flexible? Or should I be doing something better? A: It may be this is what @Daniel Hilgarth is suggesting when he says "use an interface" (n.b. - his answer now reflects a more general/flexible approach to implementing the interface). Instead of assigning delegates to your method directly, why not give the control a property, such as DataState or whatever you want to call it, using an interface that encapsulates the information you need, and leave it up to the owner to decide how to implement that. interface IDataState { bool CanEdit(string item); bool CanDelete(string item); } public partial class ConfigurationManagerControl : UserControl { public IDataState DataState {get;set;} // your code checks DataState.CanEdit & DataState.CanDelete } public class SetupWizard : Form, IDataState { public SetupWizard() { InitializeComponent(); SettingManager.DataState =this; } public bool CanEdit(string item) { ... implement directly or return from your private function } public bool CanDelete(string item) { } } But this gives you the flexibility to implement that interface any way you choose, with another object, etc. and it makes it easy to also just pass the owner itself (implementing the interface). A: I suggest the use of an interface with these two methods. That's a lot cleaner: interface ICantThinkOfAGoodName { bool CanEdit(string item); bool CanDelete(string item); } You could create something similar to the RelayCommand used in many MVVM frameworks: public class RelayObject : ICantThinkOfAGoodName { public RelayObject() : this(null, null) {} public RelayObject(Func<string, bool> canEdit, Func<string, bool> canDelete) { if(canEdit == null) canEdit = s => true; if(canDelete == null) canDelete = s => true; _canEdit = canEdit; _canDelete = canDelete; } public bool CanEdit(string item) { return _canEdit(item); } public bool CanDelete(string item) { return _canDelete(item); } } Use it like this: public SetupWizard() { InitializeComponent(); this.SettingManager.PropertyName = new RelayObject(CanEditSetting, CanDeleteSetting); // or (all can be deleted) this.SettingManager.PropertyName = new RelayObject(CanEditSetting, null); // or (all can be edited) this.SettingManager.PropertyName = new RelayObject(null, CanDeleteSetting); // or (all can be edited and deleted) this.SettingManager.PropertyName = new RelayObject(); } BTW: I am using Property injection here, because it is a control. Normally, I would pass the ICantThinkOfAGoodName dependency in the constructor of the ConfigurationManagerControl.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Prevent temporary from extending its lifetime? This may be impossible, but I was wondering if it was possible to keep a temporary from ever lasting past its original expression. I have a chain of objects which point to parent objects, and a member function which will create a child object, a simplified example is here class person{ string name; person * mommy; public: person(const string & nam, person * m = 0) : name(nam), mommy(m) {} person baby(const string & nam){ return person(nam, this); } void talk() const{ if (mommy) mommy->talk(); cout << name << endl; } }; int main(){ person("Ann").baby("Susan").baby("Wendy").talk(); // fine const person & babygirl = person("Julie").baby("Laura"); // not fine babygirl.talk(); // segfault return 0; } The way I want to use person is to pass it to a function, and something like this: void use(const person & p) { p.talk(); } use(person("Anna").baby("Lisa")); Is fine. This will work fine as long as none of the temporaries survive past the original expression, but if I bind one of the final temporaries to a const reference, its parents don't survive, and I get a segfault. I can hide person's copy constructor and assignment operator, but is there any way I can prevent this kind of error from happening? I'd like to avoid dynamic allocation if possible. A: It looks like you are creating a data structure here where children have pointers to their parents. Using temporaries is guaranteed to cause you grief in this case. In order to make this safe, you will need to dynamically allocate and possibly use some sort of reference counting. Have you considered using boost::shared_ptr? It is an implementation of a reference counted smart pointer class. Using shared_ptr and perhaps some factory methods, you might be able to get the effect you want and reduce the pain of dynamic memory allocation. I tried it out and it seems to work. Once the code exits the scope, the objects are all destroyed because there are no references left to the shared_ptrs. Edit: In response to zounds' comment, I have modified the example so that the root object controls the data structure's lifetime. #include <iostream> #include <string> #include <vector> #include <boost\shared_ptr.hpp> #include <boost\weak_ptr.hpp> using boost::shared_ptr; using boost::weak_ptr; using std::string; using std::cout; using std::endl; using std::vector; class person; typedef shared_ptr<person> Person; typedef weak_ptr<person> PersonWk; class person { PersonWk pThis; friend Person makePerson(const string & nam, Person m = Person()); string name; PersonWk mommy; // children should not affect parent lifetime, so store weak ptr vector<Person> children; // parents affect children lifetime so store child shared ptrs // make constructor private so that you can only make a person using factory method person(const string & nam, Person m) : name(nam), mommy(m) { // for demo purposes printf("creating %s\n", nam.c_str()); ++personCount; } // undefined copy constructor and assignment operators person(const person&); person& operator=(const person&); public: // for demo purposes static int personCount; ~person() { // for demo purposes printf("destroying %s\n", name.c_str()); --personCount; } Person baby(const string & nam){ Person child = makePerson(nam, Person(pThis)); children.push_back(child); return child; } void talk() const{ if (Person mom = mommy.lock()) mom->talk(); cout << name << endl; } }; int person::personCount = 0; // factory method to make a person Person makePerson(const string & name, Person m) { Person p = Person(new person(name, m)); p->pThis = p; // stash weak_ptr so I can use it to make a shared_ptr from "this" in the baby method return p; } void use(const Person p) { printf("In method use...\n"); p->talk(); } int _tmain(int argc, _TCHAR* argv[]) { printf("personCount=%d\n", person::personCount); { Person ann = makePerson("Ann"); // ann has baby and grandbaby, pass grandbaby to use method use(ann->baby("Susan")->baby("Wendy")); ann.reset(); // remove reference from root object. Destruction ensues... } printf("personCount=%d\n", person::personCount); return 0; } A: You'll have to do something like this: void use(const person & p) { p.talk(); } person a("Anna"); use(a.baby("Lisa")); That way, the parent "a" doesn't go out of scope until you're truly done with it (after the call to "use"). The problem with the original code is that the parent "Anna" only has to stay around long enough to call "baby" and the parent can be discarded before making the function call. By making the parent a variable with scope, you can control when it's destructed. Does this look dangerous to me? Yes. Therefore I'd suggest a look at m-sharp's answer on dynamic allocation. But if you wanting a method that doesn't need reference counting, etc. then you can do it this way...
{ "language": "en", "url": "https://stackoverflow.com/questions/7575070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: why i can't pass parameters to flash using 'file://' protocol? system info flash player version: 10_1_102_65 OS: linux debian, 6.0.2 web browser: Mozilla Iceweasel 3.5.16 problem description I have a flash file that uses parameters to show output on the screen. unfortunately i don't have sources and can't modify/review it. i can successfully run flash and pass parameters to it using http:// protocol. for example, #> iceweasel http:///localhost/40.swf?channel_id=1 shows correct flash in the browser. but when i try to load flash from file #> iceweasel file:///home/user/40.swf?channel_id=1 flash can't read passed parameter and shows invalid output it's really strange. because when i downgraded flash plugin (from 10_1_102_65 to 9) both protocols works! That is something occurred in the flash player above 9. unfortunately i can't use Flash Player 9 in my production environment so i should resolve the issue with Flash Player 10. question how can i pass parameters to flash using 'file://' protocol? any help is appreciated. thanks. A: As Ignacio says, GET parameters are part of HTTP and won't work with the file:// protocol, but one thing you could try is to supply the channel_id is a a FlashVar. Internally in the swf, the ActionScript code normally access GET parameters and FlashVars the same way (using loaderInfo.parameters). A: GET only exists in HTTP. You cannot use a query string when accessing a local file. And since you don't have the source, it's near impossible to provide an alternative.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does 1 / 10 equal zero unless I use variables? Possible Duplicate: Why can't I return a double from two ints being divided This statement in C with gcc: float result = 1 / 10; Produces the result 0. But if I define variables a and b with values 1 and 10 respectively and then do: float result = a / b; I get the expected answer of 0.1 What gives? A: That happens because 1 and 10 are integer constants, so the division is done using integer arithmetic. If at least one of your variables a and b is a float, it will be done using floating-point arithmetic. If you want to do it with number literals, use the notation to make at least one of them a float literal, for example: float result = 1.0f / 10; Or cast one of them to float, that would be a bit more elaborate: float result = 1 / (float)10; A: 1 and 10 are both integers and will return an integer, when you define a and b you're defining as a float. If you use 1.0 and 10.0 it will return the correct result A: When the / operator is applied to two integers, it's an integer division. So, the result of 1 / 10 is 0. When the / operator is applied to at least one float variable, it's a float division. The result will be 0.1 as you intend. Example : printf("%f\n", 1.0f / 10); /* output : 0.1 (the 'f' means that 1.0 is a float, not a double)*/ printf("%d\n", 1 / 10); /* output : 0 */ Example with variables : int a = 1, b = 10; printf("%f\n", (float)a / b); /* output : 0.1 */ A: If you want float than just cast it as follow. float result = (float)a/b;
{ "language": "en", "url": "https://stackoverflow.com/questions/7575074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SSRS OracleClient Error in VS2008 I've searched around for an answer to this, but have thus far been unsuccessful finding something that works for me. I am attempting to connect to an Oracle database in an SSRS report within VS2008, but always get the following error: System.Data.OracleClient requires Oracle client software version 8.1.7 or greater I'm guessing it is a configuration issue (I have 11g client stuff installed on my system), but I can't seem to figure it out. The connection string also appears to be correct, as it works correctly on other machines. A: In case this helps someone in the future, I will answer it here instead of deleting the question. I had multiple versions of Oracle installed on this PC, some added by another user (it's a work laptop that I inherited and no control of what was installed previously). I had to uninstall and reinstall the Oracle client (I chose the 11g R2 Client). At that point, everything appears to have been cleaned up, and I can run SSRS inside VS2008.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is It possible to run stylecop on a single file in VS2010? I've tried looking for command line options etc. I'm trying to lower the time I have to wait to see if a build fails due to stylecop. This option does not appear in any context menus or the tools menu: Is it possible to run StyleCop on just 1 file in a project? A: The following context menus should contain commands for running StyleCop: * *At solution item in Solution Explorer (rescans the entire solution) *At project item in Solution Explorer (rescans a project) *At any single .cs file in Solution Explorer (scans single file) *Inside text editor of any single .cs file (scans single file) By the way, which StyleCop version do you use? Have you considered any issues about wrong installation?
{ "language": "en", "url": "https://stackoverflow.com/questions/7575080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why are erlang lib changes not being incorporated into my project? I'm using eclipse 3.6.2 with erlang 5.8.1.1 on a fairly large project that we're not ready to move to a more modern version of the language, so I'm stuck with a bug in eprof: string_bp_mfa([{Mfa, {Count, Time}}|Mfas], Tus, {MfaW, CountW, PercW, TimeW, TpCW}, Strings) -> Smfa = s(Mfa), Scount = s(Count), Stime = s(Time), Sperc = s("~.2f", [100*(Time/Tus)]), Stpc = s("~.2f", [Time/Count]), string_bp_mfa(Mfas, Tus, { erlang:max(MfaW, length(Smfa)), erlang:max(CountW,length(Scount)), erlang:max(PercW, length(Sperc)), erlang:max(TimeW, length(Stime)), erlang:max(TpCW, length(Stpc)) }, [[Smfa, Scount, Sperc, Stime, Stpc] | Strings]). Which crashes for me all the time because whoever wrote this didn't guard against dividebyzero. I've hacked in a change: SafeTus = case Tus of 0 -> 1; _ -> Tus end, SafeCount = case Count of 0 -> 1; _ -> Count end, Sperc = s("~.2f", [100*(Time/SafeTus)]), Stpc = s("~.2f", [Time/SafeCount]), ...but it is never executed by my project. I've manually recompiled the .erl and placed the .beam in the ebin directory, but after a total shutdown of my project, closing eclipse, opening eclipse, refreshing, cleaning, and restarting, the new version of the method is not executed. I've tried sticking expressions like "foo + 1" into the method to see if I get a different exception than the badarith that is taking me down now, but to no effect. I can only guess that the .beams are being consolidated or cached somewhere that I'm going to have to nuke or rebuild? A: Look at the documentation for code module, which explains code path search. Since eprof is in the tools application, it should be picked up from any additional library directories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating meta language with Java guys! I need to create some sort of meta language which I could embed in XML and then parse with Java. For example: <code> [if value1>value2 then "Hello, Bob!" else "Hello, Jack"] </code> or <code> [if value1+2>value2 return true] </code> I need to implement conditional statements,arithmetics. Any suggestions where should I start looking? A: Java has a built-in JavaScript interpreter: ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript"); jsEngine.put("value1", 8); jsEngine.put("value2", 9); String script = "if(value1 + 2 > value2) {'Foo'} else {'Bar'}"; final Object result = jsEngine.eval(script); System.out.println(result); //yields "Foo" String Of course you are free to both load the script from anywhere you need and to provide it with any context (value and value2 in this example) you want. See also Scripting for the Java Platform article. A: A user here, Bart Kiers. Wrote a tutorial about creating a simple language in Java with ANTLR. A: Java has a scripting API that you could use for this. Lookup the API documentation of the package javax.script. You could include code in for example JavaScript in the code element, and execute that using the scripting API. A: If you really want to develop your own language, start off with the interpreter pattern. If you just want to leverage somebody else's language in your Java code, look to integration ala JSP style embedded languages. A: It is almost certain that a homemade language would suck, especially in the long run, so don't roll something on your own. There are several jsp-like frameworks available, maybe one of those would do the trick: JSTL/JSP EL (Expression Language) in a non JSP (standalone) context
{ "language": "en", "url": "https://stackoverflow.com/questions/7575085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filling a date between a data range in array? I have to arrays of dates like this: [6/13/2011, 7/15/2011, 7/18/2011, 8/13/2011] what i want to do is to fill the date between the date array so if theres days missing between any of the date like 7/15/2011, 7/18/2011 i want to add 7/16/2011, 7/17/2011 between them, is there a way or a lib can help do this ? A: This should work in JavaScript. It basically just dismisses any dates in the middle of the array, and generates all dates in between the first and last items. var dates = ["6/13/2011", "7/15/2011", "7/18/2011", "8/13/2011"]; var minDate = new Date(dates[0]).getTime(), maxDate = new Date(dates[dates.length - 1]).getTime(); var newDates = [], currentDate = minDate, d; while (currentDate <= maxDate) { d = new Date(currentDate); newDates.push((d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear()); currentDate += (24 * 60 * 60 * 1000); // add one day } console.log(newDates);
{ "language": "en", "url": "https://stackoverflow.com/questions/7575086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSTimer target and userInfo parameter questions I've read around SO as well as looked at the Apple documentation for the NSTimer class, and it seems like the easiest way to create a timer is by using the following method: [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(fireThisMethod:) userInfo:nil repeats:NO]; I understand that this will create a timer that fires after 15 seconds. The method that will be fired will be whatever method is passed into the "selector" (in this case "fireThisMethod"). Since the "repeats" is "NO," this means that it will only be fired once. My questions are: 1) Is it possible to pass in a method to "selector" that has more than one parameter? I've seen methods without any parameters, or in this case 1 (since a ":" is present after the method name). A method such as fireThisMethod:anotherParameter:? 2) I'm not sure if I truly understand what the "target" and "userInfo" parameters are for. Will you ever have a "target" that isn't "self?" Will you have a "userInfo" that isn't nil? If so, in what scenarios? Thanks A: Question 1 No. Take a look in the docs. Quoting: The selector must have the following signature: - (void)timerFireMethod:(NSTimer*)theTimer Selectors for methods without arguments are wrong. The argument to be passed is the timer, so you can do things like distinguishing which timer fired from you method (in case more than one timer calls the same method). Question 2a The target can be any object that implements the given method. Sometimes you may want a specific object (other than self) to do the task after the timer fires. Question 2b This is exactly what you're looking for. userInfo can be any object, maybe a data container, a NSValue, or any other thing. Use this to pass extra information to your method which will extract it as follows: - (void)timerFireMethod:(NSTimer*)theTimer { id info = [theTimer userInfo]; /* give it an appropriate type */ ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7575105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: what is the usage of fork while invoke mongod? ./mongod –shardsvr –replSet shard1 –port 27017 –dbpath /data/shard12 –fork fork: for server process ( from mongod document). In plain english, what does fork here mean? Thank you A: It starts mongodb as a daemon. Meaning that it will not stop running when you close the terminal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }