text
stringlengths
8
267k
meta
dict
Q: Android: way to check if a string contains any values from array? I've tried searching for "Java check if string contains values from array", and other variations on that, but have not come up with anything so hoping someone can help me. I've got the following code that I would like to clean up: if (dateint.contains("th")){ dateint=dateint.substring(0, dateint.length()-2); } else if (dateint.contains("st")){ dateint=dateint.substring(0, dateint.length()-2); } else if (dateint.contains("nd")){ dateint=dateint.substring(0, dateint.length()-2); } else if (dateint.contains("rd")){ dateint=dateint.substring(0, dateint.length()-2); } I'm wondering if I can do something like the following (not true code, but thinking in code): String[] ordinals = {"th", "st", "nd", "rd"}; if dateint.contains(ordinals) { dateint=dateint.substring(0, dateint.length()-2); } basically checking if any of the values in the array are in my string. I'm trying to use the least amount of code reuqired so that it looks cleaner than that ugly if/else block, and without using a for/next loop..which may be my only option. A: Try this: for (String ord : ordinals) { if (dateint.contains(ord)) { dateint = dateint.substring(0, dateint.length() - 2); break; } } A: If you are up to using other libraries, the Apache StringUtils can help you. StringUtils.indexOfAny(String, String[]) if(StringUtils.indexOfAny(dateint, ordinals) >= 0) dateint=dateint.substring(0, dateint.length()-2); A: Use an extended for loop : String[] ordinals = {"th", "st", "nd", "rd"}; for (String ordinal: ordinals) { if dateint.contains(ordinal) { dateint=dateint.substring(0, dateint.length()-2); } } A: you can use for loop for that for(int i = 0;i < ordinals.length;i++){ if dateint.contains(ordinals[i]) { dateint=dateint.substring(0, dateint.length()-2); break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to change the connection string during an Azure VIP Swap I'm trying to setup Staging and Live environments in Azure (September toolkit) and I want a separate Staging and Live database - with different connection strings. Obviously I can do this with web.config transformations back in Visual Studio, but is there a way I can automate a change of connection string during a VIP-swap - so that the staging site points to staging data and the live site to live data? I'd prefer not to have to deploy twice. A: I don't believe anything changes as far as the role is concerned when you do a VIP swap. Rather, it alters the load balancer configuration. So nothing happens in your app to cause it to change configuration. The only thing I can think of is that the URL changes between the two. You could implement code that chose one of two connection strings, based on the URL with which it was accessed (assuming that we're only talking about a web role), but it seems messy. Fundamentally, I think the issue is that staging isn't a separate test environment; it's a stepping stone into production. Thus, Microsoft's assumption is that the configuration doesn't change. A: With the management APIs and the PowerShell Cmdlets, you can automate a large amount of the Azure platform and this can include coordinating a VIP switch and a connection string change. This is the approach: * *Add your database connection string to your ServiceConfiguration file. *Modify your app logic to read the connection string from the Azure specific config by using RoleEnvironment.GetConfigurationSettingValue rather than the more typical .NET config ConfigurationManager.ConnectionStrings API *Implement RoleEnvironmentChanging so that your logic will be notified if the Azure service configuration ever changes. Add code to update your app's connection string in here, again using RoleEnvironment.GetConfigurationSettingValue. *Deploy to staging with a ServiceConfiguration setting for your "staging" DB connection string *Write a PowerShell script that will invoke the VIP switch (build around the Move-Deployment cmdlet from the Windows Azure Platform PowerShell Cmdlets 2.0) and invoke a configuration change with a new ServiceConfiguration file that includes your "production" DB connection string (see Set-DeploymentConfiguration) Taken together, step 5 will perform the VIP switch and perform a connection string update in a single automated operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: GL_CLAMP_TO_EDGE resize behavior with PythonMagick Is it possible to resize an image with PythonMagick in the same way GL_CLAMP_TO_EDGE works for texture mapping in OpenGL, where the border colors are extended like this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Assign/cast to object fields in a struct Sorry for this newbie question, I'm very new to C# and it's semantics. I have the following struct: public struct MT5Command{ public MT5CommandType Type{ get; set;} public AutoResetEvent ThreadWaitHandle { get; set; } public object InParam { get; set; } public object OutParam { get; set; } } And this code snippet: MT5Command Cmd = new MT5Command(); Cmd.Type = MT5CommandType.GetServerInformation; Cmd.ThreadWaitHandle = waitHandle.Value; attributes = new ServerAttributes(); Cmd.OutParam = attributes; .... ServerAttributes SrvAttributes = new ServerAttributes(); Cmd.OutParam = (ServerAttributes)SrvAttributes; The last line does not compile: Cannot modify members of 'command' because it is a 'foreach iteration variable' How is it possible to assign the OutParam field to another ServerAttributes struct? This is the outer for-each loop: foreach (MT5Command Cmd in mCommandQueue.GetConsumingEnumerable()) { ... } Thanks, Juergen A: You can't, in this case. You haven't given the full snippet, but I suspect it's something like this: foreach (MT5Command command in someCollection) { // Code as posted } Now because MT5Command is a struct, you're getting a copy of whatever value is in someCollection. Changing the property almost certainly wouldn't do what you wanted it to anyway. The compiler is protecting you from yourself, by making the command variable read-only. You could do this: MT5Command copy = command; copy.OutParam = SrvAttributes; ... but I strongly suspect that's not what you want. As a rule, it's a really bad idea to have mutable structs like the one you've come up with - and it doesn't sound like that should be a struct in the first place. For more information: * *My article on value types and reference types *MSDN guidelines on when it's appropriate to create a struct
{ "language": "en", "url": "https://stackoverflow.com/questions/7600575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I tell the index of an array of objects in Ruby on Rails 3? I have an array of todos [Todo1, Todo2, Todo3] Each object has an attribute, :done_date I need to find the first instance of the object where :done_date => null THEN I need to know what index it is todos[N] so I can find the object before todos[N-1] How can I do that? A: You could try going about it in a slightly different way. Making use of Ruby's Enumerable#take_while: # assuming 'todos' holds your todo objects todos.take_while { |todo| todo.done_date != nil }.last This will get all todo objects from todos until it sees a nil done_date, and then grab the last one. You'll have the last todo item before the first nil done_date. So, if you have todos = [todo1, todo2, todo3, todo4_with_null_done_date] the code example above will return todo3. That said, if you're really looking for something that makes use of the array's indicies, you could try something like this as well: first_nil_index = todos.find_index { |todo| todo.done_date.nil? } todos[first_nil_index - 1]
{ "language": "en", "url": "https://stackoverflow.com/questions/7600577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Bind Columns Property of a DataGrid Inside a UserControl? I have a user control with a datagrid inside. I want the caller to be able to do something like this: <local:MyControl> <local:MyControl.GridColumns> <DataGridTextColumn Header="Id" /> </local:MyControl.GridColumns> </local:MyControl> I tried to do something like this in my usercontrol definition: <UserControl ...> <DataGrid Columns={Binding GridColumns} /> </UserControl> I have a GridColumns property in the user control. It does not work. How to do this correctly? Thanks. A: You cannot bind that property as it is not a dependency property, so just forward it: <DataGrid Name="datagrid" /> public ObservableCollection<DataGridColumn> Columns { get { return datagrid.Columns; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VS2008 project only compiles 1 C++ file in x64 target This is very strange, as mostly it compiles everything well, but this one project (the main DLL project, which links in many library projects) just refuses. It compiles only CK20_Test.cpp, then proceeds to link. If I exclude that one, it compiles only DebugInfo.cpp and links. Et cetera. If I switch to Win32 target, it compiles all fine. Microsoft Visual Studio 2008 Version 9.0.21022.8 RTM, Microsoft .NET Framework, Version 3.5 SP1, Microsoft Visual C++ 2008 91605-130-0691883-60531 and a bunch of standard hotfixes installed. 1>------ Rebuild All started: Project: XMD, Configuration: DebugR x64 ------ 1>Deleting intermediate and output files for project 'XMD', configuration 'DebugR|x64' 1>Compiling... 1>stdafx.cpp 1>Compiling manifest to resources... 1>Microsoft (R) Windows (R) Resource Compiler Version 6.0.5724.0 1>Copyright (C) Microsoft Corporation. All rights reserved. 1>Linking... 1>LINK : D:\prj\alpha\64\shared\x64\DebugR\XMDCore.dll not found or not built by the last incremental link; performing full link 1>Embedding manifest... 1>Microsoft (R) Windows (R) Resource Compiler Version 6.0.5724.0 1>Copyright (C) Microsoft Corporation. All rights reserved. 1>Build log was saved at "file://d:\prj\alpha\64\shared\xmd\x64\DebugR\BuildLog.htm" 1>XMD - 0 error(s), 0 warning(s) ========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ========== Edit: configured another computer. Same problem. I feel like the project file must be broken (see my comment below on content), or the compiler is messed up. But I can't imagine what I would do to unbreak it. A: Problem solved! The C++ Output Files Object File Name setting (/Fo) was $(IntDir). When I compile in x64, the program generated DebugR.obj. In Win32 compilers, the same setting produced DebugR\$(InputName).obj. Likewise for Release or Debug configuration. Solution: Change $(IntDir) to $(IntDir)\
{ "language": "en", "url": "https://stackoverflow.com/questions/7600583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compare elements in an array of string in Java I have to write a method that will compare elements in an array of strings and return the index of the largest element. It's going to be done recursively using a divide and conquer approach. I have an idea, and I was just looking to see if my idea was right or if it should be done in a different way. I was planning on looking at the array from the left side to mid -1, then look at mid, and then look at mid +1 to right. I have a variable that will keep track of the largest index, and then after that make the recursive call for the left side and the right side. Does that sound like a good way to approach this problem? This is what I have so far: public int longest() { longest(0, a.length-1); return longestIndex; } private int longest( int left, int right) { int longestIndex; int mid; if(left > right) { longestIndex = -1; } else if(left == right) { longestIndex = 0; } else { longestIndex = 0; mid = (left + right) / 2; longest(left, mid - 1); if (a[mid].compareTo(a[longestIndex]) > 0) { longestIndex = mid; } longest(mid + 1, right); } return longestIndex; } Also, since the methods are supposed to return an int, how would I pass the longestIndex n the private method up to the public method so that it would show up in my test program when longest is called? A: Does it have to be recursive? Using recursion for this sounds like a case of: And your recursion looks totally wrong anyways, because not only you are not keeping track of the actual index but also your base cases and recursive calls don't make any sense. If I were compelled to use recursion, I would do something like: int longest(array): return longest_helper(0, 0, array) int longest_helper(max_index, curr_idx, array): # base case: reached the end of array if curr_idx == array.length: return max_index if array[curr_idx].length > array[max_index].length: max_index = curr_idx # recursive call return longest_helper(max_index, curr_idx + 1, array) And then I would proceed to drop the class and tell the professor to give students problems where recursion is actually helpful next time around. Since it doesn't look like the array is sorted, the easiest (and fastest) way to do this would just be go through the whole thing (pseudocode): max_index = 0 max_length = array[0].length for index in 1 .. array.length: if array[index].length > max_length: max_length = array[index].length max_index = index return max_index A: This is your fourth question in two days on recursion. It is good that you are putting homework tag but your time would be better spent understanding how recursion works. My recommendation is to take a few colored discs (poker chips or playing cards of a single suite work well), work out manually the recursive solution to Towers of Hanoi and then come back and look at the individual questions you have been asking. In all likelihood you will be able to answer all the questions yourself. You would also be able to accept the answers, increasing you chances in future of getting responses when you face tougher questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: git - manual replay of commits from git log to a different repository? I have a repository with some commits. I want these commits replayed on a different copy of the repository in the exact same order, same commit messages, etc. I'm hoping there is some combination of git-log, patch, and git-commit that can re-run the commits on the new repository. A: You can add the other repository as a remote and fetch all changes. That way you will have the exact same commits in the same order, same hashes. I don't understand why you would want to go the route of format-patch + am. git bundle might also be an option for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use windows DLL (late bound) methods in C++? I've basically been trying to get this working for the last couple of days, but all of my attempts and all the examples/suggestions found online have failed. I'm trying to use Microsoft's "setupapi.dll" methods in implementing my own .dll to access a peripheral device I have created. Right now I'm simply trying to use the method "SetupDiGetClassDevs" found in "setupapi.dll" to retrieve a list of attached HID devices on my computer. I've tried everything from "AfxLoadLibrary" to "__declspec(dllimport)" and pretty much everything else I've found online to no avail. I've found working examples in C# but have not found anything that even compiles in C++. I am running Microsoft visual C++ 2010 express on Windows 7 64-bit if that makes a difference (ideally I'd want it to be OS independent - at least across more recent versions of windows). Any code samples that can successfully import/use this method would be greatly appreciated. (Also don't forget to mention any configuration settings/resource files/etc as I need to figure out a holistic process to make this work.) UPDATE!!!: so i finally got my code to compile using a combination of suggestions from the responses given here + some more googling. my current code is as follows (and fyi the main issue here was that an "L" had to be prefixed to the .dll in quotes): GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}; HDEVINFO hDevInfo = INVALID_HANDLE_VALUE; PSP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA; SP_DEVINFO_DATA DevInfoData; DWORD InterfaceIndex = 0; DWORD StatusLastError = 0; DWORD dwRegType; DWORD dwRegSize; DWORD StructureSize = 0; PBYTE PropertyValueBuffer; bool MatchFound = false; DWORD ErrorStatus; BOOL BoolStatus = FALSE; DWORD LoopCounter = 0; HINSTANCE dllHandle = LoadLibrary(L"setupapi.dll"); if(dllHandle) { typedef HDEVINFO (WINAPI *pFUNC)(LPGUID, PCTSTR, HWND, DWORD); pFUNC SetupDiGetClassDevs = (pFUNC) GetProcAddress(dllHandle, #ifdef UNICODE "SetupDiGetClassDevsW" #else "SetupDiGetClassDevsA" #endif ); if(SetupDiGetClassDevs) hDevInfo = SetupDiGetClassDevsW(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); FreeLibrary(dllHandle); unfortunately i wasn't able to get this working using the "safeloadlibrary" function remy mentioned. and my impression from other forums is that the standard "loadlibrary" function is non-ideal. so i'd like to know what is needed to implement it (header files, etc) or if there is another better way to do this. apparently there are also some issues that may arise using "loadlibrary" in a DLL (particularly in DLLMain entry point) but given my lack of experience using .dll's i'm not really sure what they are. A: Your code fails because you are passing the wrong function name to GetProcAddress(). Like most API functions that have string parameters, SetupDiGetClassDevs() has separate Ansi and Unicode flavors available (SetupDiGetClassDevsA() and SetupDiGetClassDevsW(), respectively), and the API header files transparently hide this detail from you. So you need to adjust your string value according to which flavor you actually want to use, eg: HINSTANCE dllHandle = SafeLoadLibrary("setupapi.dll"); if (dllHandle) { typedef HDEVINFO WINAPI (*pFUNC)(LPGUID, PCTSTR, HWND, DWORD); pFUNC SetupDiGetClassDevs = (pFUNC) GetProcAddress(dllHandle, #ifdef UNICODE "SetupDiGetClassDevsW" #else "SetupDiGetClassDevsA" #endif ); if (SetupDiGetClassDevs) hDevInfo = SetupDiGetClassDevs(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); FreeLibrary(dllHandle); } Here is a simply trick to make the mapping easier to work with if you have multiple functions to load dynamically: #if defined(UNICODE) #define _MAP_WINNAME_STR(n) n "W" #else #define _MAP_WINNAME_STR(n) n "A" #endif pFUNC SetupDiGetClassDevs = (pFUNC) GetProcAddress(dllHandle, _MAP_WINNAME_STR("SetupDiGetClassDevs"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7600590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using rails to place markers on google maps from locations stored in DB OK so I added a google map into my site that lets users search for locations based on either city, state or by zip code that shows all shops of a certain type around them. It uses the places API to grab them, BUT I also have a table in my DB that has a bunch of shop locations set up by users. The table stores the shop details, as well as the address and the latLng (and soon the place reference number if they have a places account). What I want to do is have my google map display all the user added shop locations as well. Im not sure how to have rails find the shops in the DB that are in proximity to the location searched for by the user. So if I went to the site and typed in 20175 for the zip code, rails would find all the records that are close to that zip code. I guess the query would have to be based on the latLng. This site was able to do it: http://www.checkoutmyink.com/shops and is pretty much what I want to do. A: If you want to perform spatial algebra with rails, i would recommend using rGeo. It fits well with ActiveRecord and adapts to a bunch of spatial DB's (including Postgis). Still, using spatial DB stored procedures will be far more efficient to retrieve points within a radius (using GIST index), e.g. using ST_DWithin with Postgis
{ "language": "en", "url": "https://stackoverflow.com/questions/7600593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating stop-motion videos from images with PHP Is it possible, using PHP, to create a video file (Format doesn't matter at the moment) from a series of images? I'm not talking about making animated GIFs but real videos. A: Yes, but why would you want to? PHP isn't suitable for writing video compression software (e.g. implementing an H.264 encoder yourself), much as a chainsaw isn't suitable for neuro-surgery. Use external tools like ffmpeg to do it for you with far less hassle/pain. A: there is the ffmpeg-libary that can encode videos in php: http://ffmpeg-php.sourceforge.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/7600595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to publish a Netbeans Update Center on Java.net? I created a NetBeans based application and I want t publish its update center in the Java.net project's page. Any idea on how to do this? The page suggests using Webdav but is not working. Edit: I was able to do it by adding then in a folder in the downloads section but it is a manual process. Any easier way? A: The only way I have done it so far is loading all the files into a folder one by one, manually. I just hoped for a better way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to draw textures using stb_image.c I want to load this picture into a 2d texture and then draw it onto the screen. The main problem is loading the picture into a texture variable. The follow code output the correct width and height and rgba but how do I put the data into a 3d texture. #include <OpenGL/gl.h> #include <OpenGL/glu.h> /* more includes... */ #include "stb_image.h" using namespace std; int main(int argc, char** argv) { int x,y,n; unsigned char *data = stbi_load("png.png", &x, &y, &n, 0); if (data == NULL) { // error cout << "Error, data was null"; } else { // process cout << data << endl << endl; } stbi_image_free(data); cout << x << endl << y << endl << n; return 0; } A: First you need * *a drawable (window, PBuffer, framebuffer) *a OpenGL context associated with the drawable You can use GLFW, SDL or GLUT for getting those (personally I recommend GLFW, if you need only one single window). Create a texture name with GLuint texture_name; void somefunction(…) { glGenTextures(1, &texture_name); glBindTexture(GL_TEXTURE_2D, texture_name); glPixelStorei(…); /* multiple calls to glPixelStorei describing the layout of the data to come */ glTexImage2D(GL_TEXTURE_2D, miplevel, internal_format, width, height, border, format, type, data); } This was the quick and dirty explanation how to load it. Drawing is another business. I suggest you read some OpenGL tutorials. Google for "NeHe" or "Lighthouse3D", or "Arcsynthesis OpenGL tutorial".
{ "language": "en", "url": "https://stackoverflow.com/questions/7600602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CAAnimation without animation? I am trying to switch view controllers in my app using CAAnimation. When I switch between these 2 particular view controllers I do not want any animation. Is this possible? If so, how would I achieve this? Thanks! A: How about setting the duration to 0: BOOL shouldAnimate = // here you set your condition whether to animate or not CFTimeInterval standartDuration = 1.0; CAAnimation *animation = [CAAnimation animation]; animation.duration = shouldAnimate ? standartDuration : 0.0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7600605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delay in Thread execution+Android After many trials of solutions (including posting questions on SO) I thouht will work fine. But no improvement. Coming to my problem, I am implementing an App that have a countdown timer. I am showing this on a button (Just using like a canvas by disabling the click event). I start the timer when user clicks a button (which is a separate button). Below is the countdown timer code, public class DigitalTimer extends Button{ -------------------------------- -------------------------------- -------------------------------- -------------------------------- -------------------------------- -------------------------------- private String timerText; public DigitalTimer (Context context,int hourstime,int mintime,int sectime){ super(context); Log.d(TAG,"DigiTimer constructor"); this.context = context; initialize(hourstime,mintime,sectime,timerType); setClickable(false); } public void initialize(int hourstime,int mintime,int sectime,int timerType){ Log.d(TAG,"DigiTimer initialize"); this.hourstime = hourstime; this.mintime = mintime; hour = hourstime; min = mintime; sec = sectime; //Just Thread version **digiThread = new Thread(){ @Override public void run(){ while(!isPauseTimer()){ updateTimes(); SystemClock.sleep(UPDATEDELAY); } } };** //Handler version /* handleRunnable = new Runnable(){ public void run(){ updateTimes(); } }; */ } private void updateTimes(){ timerText = String.format(timerFormat,hour,min,sec ); postInvalidate(); sec--; if(sec < 0){ sec = 59; min--; } if(min < 0){ min = 59; hour--; } if(hour < 0){ //when hour is negative it means the given time completed so we stop the timer & alarm permanantely hour = 0; min = 0; sec = 0; } } @Override protected void onDraw(Canvas canvas){ super.onDraw(canvas); Log.d(TAG,"DigiTimer onDraw"); setBackgroundResource(R.drawable.button9patch); setText(timerText); } public void startUpdateTheread(){ //digiHandler.postDelayed(handleRunnable, UPDATEDELAY); **digiThread.start();** } private void startTimersAndAlarms(){ ----------------------- ----------------------- ----------------------- ----------------------- **startUpdateTheread();** --------------------- --------------------- } } Initially the timer is woking fine . But if no.of hours for the countdown is higher (say 5:00:00) then its running fine until sometime (say 4:00:00) from then it is delaying the timer update. (just to countdown a minute it is taking more time ..particularly when the user is out of the App) First I tried with the Handler. I had the problem. I thought the delay is because of keeping the UI thread busy. So I developed a separate thread. But still the problem persist. Sorry for the long post. Please someone point what's happening. Is that something I am missing or putting the code in wrong place? Thanks EDIT: I read SystemClock.sleep documentation. It says "{This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input) }". I understand that I should keep CPU on while I run this thread. So according to the answer by @Brandon I should implement partial POWERLOCK to keep the CPU on. Is my understanding correct? A: If you want to have an accurate timer, I think you'll need to get a wake lock. Check out the documentation of PowerManager You can either get a FULL_WAKE_LOCK to keep the screen on, or a PARTIAL_WAKE_LOCK to keep the CPU running. Don't forget to add the permission to your AndroidManifest file too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically position a div under a fixed position div? I've got photo gallery app with a fluid layout. The #header & #controls are set to position:fixed so that when the user scrolls, they stay on the top of the window. The div that contains all the photos, #people, is positioned below the controls with padding. On a standard 1280 x 1024 window everything looks fine. However, when the window gets smaller, the controls wrap, and #controls gets taller. Consequently, #people then gets partially hidden. Is there a CSS only way to make #people move to accommodate the height change? I'm fairly certain there isn't, as fixed elements get taken out of the document flow. I thought I'd ask anyway. Update Here's an example: http://jsfiddle.net/hbms2/9/. At the default display, all the blue controls are on one line. When you resize the pane narrower, and they jump onto multiple lines, you can see "#1#,"#2",etc get covered. A: Well, this is pretty simple. You set #controls to width:100% that means it will only be as wide as the window. What you should do, since it is fixed positioned, is set the sides to left:0; right:0; (so it covers the page) and the min-width wide enough to fit your controls. body { min-width:700px } #controls { left:0; right:0; min-width: 700px; } Now when you resize the window to less than 700px, your controls will not squish together, and you can use the scrollbar to access off-screen content. Here it is using your jsfiddle: http://jsfiddle.net/hbms2/14/ Note: I only applied the fix to the controls section, content in the other div's will still squish together since you specified their width with a percentage. (You should avoid doing that) However, you can fix it using the same method. The control elements will still be hidden if the viewport is smaller than their width. There is no way to fix this using CSS; you would have to use javascript (which would be complicated, cumbersome, and probably wouldn't even yield the desired result) or you can make another site designed for smaller viewports. The latter is by far the better option. Thanks for making the example like I suggested, it makes answering the question a lot easier. A: The only pure CSS solution I know that will even come close are media queries, and you'll have to do a lot of trial and error, and eventually the result might not be 100 perfect. Therefore, I resorted to JavaScript (jQuery for comfort). You can achieve this by testing $(window).resize and changing the margin-top of the #people element to match #header's height. Here's an example! What I did: $(function() { $people = $('#people'); //Cache them to not waste $header = $('#header'); //browser resources. $(window).resize(function() { //When window size changes //Check if the height changed if ($people.css('margin-top') != $header.height() + 5) { //Change height if it has. $people.css('margin-top', $header.height() + 5 + 'px'); } }); }); A: I am just giving it a try and I am playing around, but would something like this with dynamic heights work? http://jsfiddle.net/hbms2/10/ Or am I completely on the wrong track here?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WinRT - Start an application on Windows boot? I'm working on a Metro style application in the new WinRT (.NET 4.5) framework for Windows 8, and I was wondering if it would be possible somehow for an application (through the registry or some other means) to register itself to start up when Windows starts as well. I haven't been able to find anything about this anywhere else, only for Windows 7 or below, with normal-style applications. A: There is no way to make a Metro style application launch at boot. The user will have to invoke the application from the start screen. Metro style applications cannot be services and so launching them at boot time doesn't seem like the right approach any more than launching Microsoft Word or Adobe Photoshop at boot time would be. A: Microsoft's goal with Metro-style apps is that the user is always in control. Therefore, Metro-style apps cannot activate themselves when a machine boots up. Furthermore, traditional Win32/.NET desktop code cannot interact with Metro-style apps and so cannot start a Metro-style app behind the scenes. That said, if your app has registered itself as the handler for the rendering of its own tile, then it gets called periodically and is asked to re-render its tile's content so it should always be able to show its latest status/news/info to the user when they view their start page. A: I think you could have all your star tup stuff running as a service that exposes the appropriate WinRT level connectivity. Then the user only needs to fir up the client app. Goo separation too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Use an Ajax response in JSP I have a JSP page which has nothing but a normal HTML table with five rows and five columns. Now I am making an Ajax call and get a response back. Now once I have the response back, I need the data to be filled in appropriate cells of the table. So my question is; * *Should I use JSON for building the response? *How do I handle the data back at the JSP level. That is, once I have the response from the server? Just as additional information, I am using DWR which is nothing but calling a Java method (which builds the response) from inside JavaScript code. A: Let's consider this Java class. class Employee { int id; String eName; // Setters and getters } In JavaScript, the JSON object: var employee = { id : null, name : null }; This is the call to a Java method from a JavaScript function: EmployeeUtil.getRow(employee,dwrData); In getRow() of the EmployeeUtil class, the return type of method will be Employee: Employee getRow(); So using the setters of Employee set the data. dwrData is the callback function. function dwrData(data) { employee=data; } The data returned, which is an Employee bean, will be in the callback function. Just initialize this in the JavaScript JSON object. Use a JSON object accordingly to populate the table. EDIT : You can use List getRow() instead of Employee getRow(), returning a list of rows as a List instead of a Bean. Now the response contains list as data. Refer to Populate rows using DWR. Check these examples to populate data in table: * *DWR + Dojo Demo *Dynamically Editing a Table Should I use JSON for building the response? * *No need to pass JSON in response. Instead return a Bean of a class as mentioned above. *A list can be passed as a response, also as mentioned above. How do I handle the data back at the JSP level. That is, once I have the response from the server. Check the explanation above and the examples of the given links to handle the response in JSP and display the response data in a table. * *DWR basics on YouTube A: JSP pages are dynamically generated servlets. Once a user hits a JSP page, they receive dynamically generated HTML that no longer talks to the JSP page that generated it unless they complete an action such as hitting "refresh" or submitting a form. Check out the JSP Page at Oracle for more info and Wikipedia for a decent high level explanation of JSP technology. To handle the AJAX, you're going to need to define a new network endpoint capable of processing the XML requests coming up from the Javascript. See this example, this library, or this JSON Example. A: What I do quite frequently is setup two servlets for this situation: MyServlet MyAJAXServlet MyServlet handles the normal HTTP requests and (usually) ends up using a RequestDispatcher to forward the request to a JSP. Example: public class MyServlet extends HttpServlet { private static final long serialVersionUID = -5630346476575695999L; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGetAndPost(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGetAndPost(req, res); } private final void doGetAndPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* * Handle the response here, manipulate the 'MODEL' */ /* * Forward to the 'VIEW' (No Baba Wawa jokes please) */ RequestDispatcher rdis = req.getRequestDispatcher("Path/To/My/JSP"); rdis.forward(req, res); } } Where as the AJAX servlet checks the request's parameter list for presence of a 'command': public class MyAJAXServlet extends HttpServlet { private static final long serialVersionUID = -5630346476575695915L; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGetAndPost(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGetAndPost(req, res); } private final void doGetAndPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String cmd = req.getParameter("cmd"); if (cmd == null || cmd.length() < 1) { /* Custom fail mode here, perhaps toss back failure HTML */ return; } /* Easily implement command pattern here, but for simplicity, we will use an if tree */ if (cmd.equalsIgnoreCase("getSomeData")) { String out = "<tr><td>ExampleCell in ExampleRow</td></tr>"; res.getWriter().append(out); return; } else if (cmd.equalsIgnoreCase("someOtherCommand")) { /* Do something else */ } } } If you format your JSP to allow for bulk replacement of html elements like so: <table id="pleaseReplaceMyContentsTABLE"> <tr><td>&nbsp;</td></tr> </table> Then it becomes very easy to dynamically modify a web pages content (I use JQuery for this example): var url = "http://mydomain.whatever/myapp/MyAJAXServletMappedURL?cmd=getSomeData"; $.post(url, function(data) { //Message data a bit & display $("#pleaseReplaceMyContentsTABLE").html(data); }); Some limitations with sending back preformatted HTML from the AJAX Servlet: * *If you are sending back a moderate to large amount of data, then your webserver will easily become overloaded when the number of clients starts to rise. Aka, it won't scale well. *Java code that is formatting HTML to send to a client can get ugly and hard to read. Quickly. A: * *If you use DWR you don't need to use JSON, it uses internally. *Use javascript , the jsp code is out-of-scope. The page has been generated so you only can modify the DOM using javascrip There are lot of examples doing what you need in DWR tutorials. I suppose you need just do something as: dwrobject.funtionAjax(param,returnFunction); ... function returnFunction(data) { // use javascript to change the dom } A: Ajax part: We return a list of objects: public List<IdTexto> getPaisesStartingBy(String texto,String locale){ List<IdTexto> res = new ArrayList<IdTexto>(); // Fill the array return res; } The IdTexto is a simple bean with geters and setters: public class IdTexto { private int id; private String texto; private String texto2; // getters and setters } And it is defined in the dwr.xml as bean: <convert converter="bean" match="com.me.company.beans.IdTexto"/> And the class containing the java function is defined as creator: <create creator="new" javascript="shopdb"> <param name="class" value="com.me.company.ajax.ShopAjax"/> </create> In the jsp, we define a function javascript to retrieve the List of starting by some text object in this way: shopdb.getPaisesStartingBy(req.term,'<s:text name="locale.language"/>', writePaises); And the corresponding function to write down the texts: function writePaides (data) { var result="<table>"; for (i=0; i<data.length;i++) { id = data[i].id; texto=data[i].texto; texto2=data[i].txto2; // now we write inside some object in the dom result+="<tr><td>"+id+"</td><td>"+texto+"</td><td>"+texto2+"</td></tr>"; } result+="</table>"; $("tabla").innerHTML=result; } If you, instead of a bean have some other object you'll access the properties in the same way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Export project to a zip with all sources, dlls, etc? Is there a tool that inspects a CS 2008 project and created a bundle of all files that can unpacked on a different machine to build the project? Basically I would like to give this to a smarter colleague and so he can help me figure out why it is not fetching the records it should :) A: I ended up writing a little utility to grab <HintPath>, <Content Include=.../> and <Compile Include=...> from the .csproj file. I am sure it is missing lots of stuff but I can add it as I go along. Until something more useful comes up, this will have to do to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Public key accepted with SSH, fails with git I am using gitosis for repository management. I have two other keys that work perfectly. I've recently added a third key. All keys work when I SSH into the machine (I get the error mentioned here as normal, and the server's auth.log says "Found matching RSA key..."). However, when I run the command: git clone -b <branch> ssh://gitosis@<server>/<project> with the new third key the server's auth.log shows "Failed publickey for gitosis...". The same "git clone" command works for the other keys. The permissions on the .ssh files are set correctly since I am able to SSH into the machine. Both machines are Ubuntu. What would cause the "git clone" to be rejected, while the SSH is accepted? A: That should mean that you have a ssh config file (~/.ssh/config), with: * *a section Host <server> *a different IdentityFile (ie a public key full path) than the one the gitosis user should have
{ "language": "en", "url": "https://stackoverflow.com/questions/7600617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Replace content with jQuery.fn.load I'm trying to write a client script to use .load in a non-typical way. I'm working with another site and I don't have access to change their generated code, so I have to do everything on the client side. The page looks something like <html> <!-- the head --> <body> <div id="body"> <!-- the content --> </div> </body> </html> Now, I want to update the page with an XHR. I want to replace the contents of #body with the new contents of #body from the XHR. My first instinct was to do this: $('#body').load('/ #body') But that gives me a DOM that looks like this: <html> <!-- the head --> <body> <div id="body"> <div id="body"> <!-- the content --> </div> </div> </body> </html> That's clearly not what I want. I want <!-- the content --> from the newly fetched copy to just overwrite <!-- the content --> from the current copy. I have also tried things along the lines of $.get('/', function(data) { $('#body').html($(data).find('#body').html()); } to no avail. When I play with it, I find that $(data).find('#body') never finds anything. A: You can wrap the result of your XHR, assuming it is html in a jquery object, grab the body of the calling page and use replaceWith. //snip var xhrResult = $("<html><div id='body'>blah</div></html>"), // pretend this was returned newContent = xhrResult.filter("#body"), placeHere = $("#body"); placeHere.replaceWith(newContent); Edited Based on this fiddle: http://jsfiddle.net/bstakes/VmhBW/
{ "language": "en", "url": "https://stackoverflow.com/questions/7600619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make universal class method? Is there any way to make a class template function? So for example //Warning: this is conceptual pseudo-code template<typename TemplateClass, TemplateItem> TemplateClass &TemplateClass::operator=(TemplateItem &B) { Item = B.Item; return *this; } //or... template<typename TemplateClass, TemplateItem> TemplateClass &TemplateClass::Assignment(TemplateItem &B) { Item = B.Item; return *this; } Assignment<TestA,TestB>(B); Or something along those lines. It isn't just for assignments, I'll comment. A: I'm sure I'll get bashed by the "preprocessor is evil" group, but I think you are looking for something like this: #define DEFINE_ASSIGNMENT(mainClass,memberClass,member) \ mainClass & mainClass::operator = (const memberClass & rhs) \ { \ member=rhs.member; \ return *this; \ } DEFINIE_ASSIGNMENT(TestA,TestB,Item) A: You cannot add something into a class's definition. You can't force a class to have a particular member function. Once you put the ; on a class definition, it has been defined, and it cannot be altered. So if you want to have a member of a class, it has to be declared within the class definition. Now, the general way to extend functionality like this is to use a non-member function: template<typename ClassName, typename Other> ClassName &SomeFunc(ClassName &myType, const Other &theOther); This function would return myType. Obviously, that's not going to help with operators that have to be members of a class, like assignment. But there's nothing you can do about that. The most you can do is have the assignment operator call the non-member function, so all of the actual work goes on in there. But that's the best you can do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - get color name from rgb i work now with GD library on PHP and i'm trying to get the pixel color name ,i mean : green , red , blue , etc... i'm getting the color this way : $rgb = ImageColorAt($image, $X, $y); $r = ($rgb >> 16) & 0xFF ; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; now , how can i find it this color is green light , dark blue , normal blue or red and etc.. A: you have to create an associative-array that maps value => colorname (or inverse). fill this array with the data of this table: http://en.wikipedia.org/wiki/Web_colors then you can lookup the color names, that are available in CSS too. additionally you can add more, own, colornames A: Are you suppose that every color has its own name? It's 16^6>16.7 millions. So, it seems to be impossible. But you may create your own database (format rgb => human-readable)
{ "language": "en", "url": "https://stackoverflow.com/questions/7600622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Dynamically created divs aren't clickable Can't dynamically create a div with a clickable class: HTML: <div id="line1"> <div class='clickMe'>old clickable text</div> </div> <div id="line2"> <div class='dontClickMe'>old unclickable text</div> </div> <div id='button'>button</div> Javascript: $('.clickMe').click(function() { alert("foo"); }); $('#button').click(function() { $('#line2').html("<div class='clickMe'>new clickable text</div>"); }); Clicking the button replaces the code in line2. It looks fine in debugging tools, i.e. Chrome dev elements. But the "new clickable text" in line2 is not clickable. A: Use delegate or live. Dynamically added divs wont have handlers bound unless you explicitly bind a new handler to them. A: Use .delegate() var body = $("body"); body.delegate('.clickMe', 'click', function() { alert("foo"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7600626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Iterate array using range This is what I want to do a = [1, 2, 3, 4] a[1] = 0 a[2] = 0 one way to do this is to loop (1..2).each { |x| x = 0 } is there a way to do this somehow with ranges or splats? something like a[(1..2)] = 0 A: a = [1, 2, 3, 4] a[1..2] = [0] * 2 p a #[1, 0, 0, 4] You can't just type a[1..2] = 0 at line 2, cause the array a will become [1, 0, 4] A: Or, with Array#fill a.fill(0, 1..2) A: With range ary = [1, 2, 3, 4] ary[1..2] = [0,0] Using [start, length] a = [1,2,3,4] a[1,2] = [0,0]
{ "language": "en", "url": "https://stackoverflow.com/questions/7600628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Gradually or smoothly change object size (Checkboxlist)? C# question Here is what I am trying to do. When I click a button, I want the checkboxlist to smoothly change from say (200,10) to (200,100) in size. I am successful at getting to size to change instantaneously, but I want it to look smooth. Here is the code I wrote: private void Form1_Load(object sender, EventArgs e) { timer1.Interval = 1; } private void button1_Click(object sender, EventArgs e) { timer1.Enabled = true; } private void timer1_Tick(object sender, EventArgs e) { if (checkedListBox1.Height < 100) { checkedListBox1.Size = new Size(checkedListBox1.Size.Width, checkedListBox1.Size.Height + 1); } else { timer1.Enabled = false; } } I have used this coding to move objects smoothly, but never to change sizes. So when you run this code, the box just flickers and it seems like its trying to change size, but it doesn't, and the loop never ends. Thanks! A: You need to set IntegralHeight to false to that the box can be a height that is not a multiple of the item height. For the flickering, you should probably double-buffer the form which contains this control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone Core Data - cannot fulfill a fault error I have three classes, A, B and C. A is the main class. When the user wants to see the list of all objects that were purchased, Class B is called from A and shows the list of objects in a core data entity. Inside class B, the user can buy new objects (in-app purchase). When the user wants to buy another object, class C is called. When class C is called, a new object is created on the core data entity using anObject = [NSEntityDescription insertNewObjectForEntityForName:@"Objects" inManagedObjectContext:context]; this object is then assigned to a local reference on Class C, using something like self.object = anObject; this object variable was declared like this: .h MyObjects *object; @property (nonatomic, retain) MyObjects *object; and @synthesized on .m MyObjects is a core data class representing the entity. In theory, object will retain anything assigned to it, so the line self.object = anObject I typed previously will retain anObject reference on self.object, right? The problem is that when I try to access self.object in the same class after buying the new object, I receive an error "CoreData could not fulfill a fault for XXX", where XXX is exactly self.object. At no point in the code there's any object removal from the database. The only operation to the database I could identify was a saving operation done by another class moments before the crash. The save is done by something like if (![self.managedObjectContext save:&error]) ... Is there any relation? what may be causing that? A: CoreData manages the lifetime of managed objects and you should not retain and release them. If you want to keep a reference to the object so that it can be retrieved later then you have to store the object's id (obtained using -[NSManagedObject objectID]). Then use that to retrieve the object later using -[NSManagedObjectContext objectWithID:]. Make sure you understand about CoreData faulting. Read the documentation. A: I had a similar issue a few days ago (using NSFetchedResultsController) where I was placing my fetchedObjects into an array and gathering attributes to populate tables from the array objects. It seems that if the objects in the array are faulted, you cannot unfault it unless you are acting on the direct object. In my case, I solved the issue by taking the lines of code in question and calling [[_fetchedResultsController objectAtIndexPath:indexPath] someAttribute]. I would assume that doing something similar would fix your problem as well. It seems a bit tedious to need to fetch from the managedObjectContext to obtain a faulted value, but this was the only way I could personally get past the issue. A: Core Data is responsible for managing the lifetime of managed objects in memory. It's really important to understand Managed Object Contexts - Read the documentation. Apple also provides an entire troubleshooting section here, and it contains among other things the causes for your error. But it's really only useful if you understand how core data works. A: Most likely error is that the object you are saving does not belong to the managed object context. Say you use the same object on different threads and those different threads use different managed object context, then this will happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concatenate fields from one column in one table into a single, comma delimited value in another table Any help that can be provided to a Access and VB noob would be greatly appreciated. What I'm trying to do is concatenate the values from one table and insert it as a comma delimited value into a field in another table. I'm trying to take all the server names that are say Linux boxes and concatenate them into a different field. Table A looks like this Machine Name | Zone | Operating System ---------------------------------------- Server01 Zone A Linux Server02 Zone B Linux Server03 Zone A Windows Server04 Zone C Windows Server05 Zone B Solaris Table B has the field I want to insert into: Affected_Machine_Names. Now, I've tried looking through the Concatenate/Coalesce posts, but the SQL view in Access doesn't like the Declare statements. My VB skills suck badly and I can't seem to get the code to work in VB for Applications. Unfortunately, I can't get this database converted into our SQL farm cause I don't have a server available at the moment to host it. Can anyone point me in the right direction? A: You can use Concatenate values from related records by Allen Browne for this. Copy the function code from that web page and paste it into a new standard module. Save the module and give the module a name different from the function name; modConcatRelated would work. Then I think you should be able to use the function in a query even though you're not proficient with VBA. First notice I changed the field names in TableA to replace spaces with underscores. With that change, this query ... SELECT sub.Operating_System, ConcatRelated("Machine_Name", "TableA", "Operating_System = '" & sub.Operating_System & "'") AS Machines FROM [SELECT DISTINCT Operating_System FROM TableA]. AS sub; ... produces this result set: Operating_System Machines Linux Server01, Server02 Solaris Server05 Windows Server03, Server04 If you can't rename the fields as I did, use a separate query to select the distinct operating systems. SELECT DISTINCT TableA.[Operating System] FROM TableA; Save that as qryDistinctOperatingSystems, then use it in this version of the main query: SELECT sub.[Operating System], ConcatRelated("[Machine Name]", "TableA", "[Operating System] = '" & sub.[Operating System] & "'") AS Machines FROM qryDistinctOperatingSystems AS sub; A: This is a fairly basic VBA function that will loop through every row in a column, and concatenate it to a comma-delimited result string. i.e., for your example, it will return "Server01, Server02, Server03, Server04, Server05". (Don't forget to replace the column and table names) Function ConcatColumn(OS As String) As String Dim rst As DAO.Recordset Set rst = CurrentDb.OpenRecordset("Select * from TableA") Dim result As String 'For every row after the first, add a comma and the field value: While rst.EOF = False If rst.Fields("Operating System") = OS Then _ result = result & ", " & rst.Fields("MyValue") rst.MoveNext Wend 'Clean it up a little and put out the result If Left(result, 2) = ", " Then result = Right(result, Len(result) - 2) Debug.Print result ConcatColumn = result End Function To use this, 1. ConcatColumn("Windows") will return "Server04, Server03" 2. ConcatColumn("Linux") will return "Server01, Server02" 3. ConcatColumn("Solaris") will return "Server05" 4. ConcatColumn("") will return "".
{ "language": "en", "url": "https://stackoverflow.com/questions/7600637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: backbone's delegateEvents issue I have this situation with backbone: events: { 'click': 'test1', 'click .modify': 'test2' } When I click on .modify is fired both test1 and test2. How to solve? http://jsfiddle.net/keepyourweb/VU8pE/1/ A: I would have thought that e.preventDefault() would have worked too... But, I found that e.stopImmediatePropagation() does the trick for you. My guess is that both event callbacks have been queued by this point which is why preventDefault didn't work. Thanks for the jsFiddle. It really helped! A: The first click event is being attached to el so any clicks to .modify will bubble up to test1 as well. If you really want to do this then set up your event handlers like this: test1: function(e) {}, test2: function(e) { // this will stop "test1" // from being called e.preventDefault(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In JavaScript, what does the term 'side-effect' refer to? Does it mean, exclusively, that a variable is being written? A: I don't think the term has a special, exclusive defined meaning in JavaScript. It can mean the same as everywhere else. A: This isn't a formally defined term in JavaScript, but I see it most commonly used to refer to some change in state outside of the immediate context. For example, the following code will cause no changes in state after execution, so it would be considered "side-effect free": (function() { // no side-effects, foo won't exist once this function is done executing var foo = 'bar'; })(); ... whereas in the following code there are side-effects, because a global variable is introduced: (function() { // no var keyword, so global variable created foo = 'bar'; })(); A: I would word it as "state being changed", but yes, basically that's it. The polar opposite of it is read-only access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MySQL Subquery Optimization The Query: SELECT a FROM table1 WHERE b IN (SELECT b FROM table1 WHERE c = 2); If the subquery returns zero results, mysql takes a long time to realize it before it finally returns an empty result. (2.5s when subquery is empty, 0.0005s when there is a subquery result). My question: is there a way to modify the query such that it will still return an empty result but take the same time as it did when there was a result? I tried: SELECT a FROM table1 WHERE b IN ((SELECT b FROM table1 WHERE c = 2), 555); ...but it only works WHEN the subquery is empty. If there is a result, the query fails. -- I don't want to change the query format from nested to join/etc. Ideas..? Thanks! -- EDIT: Also, I forgot to add: The subquery will likely result in a decent-sized list of results, not just one result. --- ALSO, when I type '555', I am referring to a value that will never exist in the column. -- EDIT 2: I also tried the following query and it "works" but it still takes several orders of magnitude longer than the original query when it has results: SELECT a FROM table1 WHERE b IN (SELECT 555 AS b UNION SELECT b FROM table1 WHERE c = 2); A: Wild guess (I can't test it right now): SELECT a FROM table1 WHERE EXISTS (SELECT b FROM table1 WHERE c = 2) AND b IN (SELECT b FROM table1 WHERE c = 2);
{ "language": "en", "url": "https://stackoverflow.com/questions/7600651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PlotCanvas on a wx.Panel? I'm having difficulties with the wx.lib.plot.PlotCanvas module, getting it to display in a panel. Can someone please help me understand what I'm doing wrong? #!/usr/bin/python import wx import logging import wx.lib.plot as plot class PlotCanvasExample(wx.Panel): def __init__(self, parent, id, size): ''' Initialization routine for the this panel.''' wx.Panel.__init__(self, parent, id, style=wx.BORDER_NONE, size=desiredSize) self.data = [(1,2), (2,3), (3,5), (4,6), (5,8), (6,8), (10,10)] canvas = plot.PlotCanvas(self, size=desiredSize) line = plot.PolyLine(self.data, legend='', colour='pink', width=2) gc = plot.PlotGraphics([line], 'Line Graph', 'X Axis', 'Y Axis') canvas.Draw(gc, xAxis=(0,15), yAxis=(0,15)) if __name__ == '__main__': ''' Simple main program to display this panel. ''' # Create a simple wxFrame to insert the panel into desiredSize = wx.Size(300,200) app = wx.App() frame = wx.Frame(None, -1, 'PlotCanvasExample', size=desiredSize) example = PlotCanvasExample(frame, -1, size=desiredSize) frame.Show() app.MainLoop() A: This works by subclassing PlotCanvas. I do not put it in a panel but directly in the Frame !/usr/bin/python import wx import logging import wx.lib.plot as plot class PlotCanvasExample(plot.PlotCanvas): def __init__(self, parent, id, size): ''' Initialization routine for the this panel.''' plot.PlotCanvas.__init__(self, parent, id, style=wx.BORDER_NONE, size=desiredSize) self.data = [(1,2), (2,3), (3,5), (4,6), (5,8), (6,8), (10,10)] line = plot.PolyLine(self.data, legend='', colour='pink', width=2) gc = plot.PlotGraphics([line], 'Line Graph', 'X Axis', 'Y Axis') self.Draw(gc, xAxis=(0,15), yAxis=(0,15)) class MyFrame(wx.Frame): def __init__(self, parent, id ,size): wx.Frame.__init__(self, parent, id, size=desiredSize) sizer = wx.BoxSizer(wx.VERTICAL) self.canvas = PlotCanvasExample(self, 0, size) sizer.Add(self.canvas, 1, wx.EXPAND, 0) self.SetSizer(sizer) self.Layout() if __name__ == '__main__': ''' Simple main program to display this panel. ''' # Create a simple wxFrame to insert the panel into desiredSize = wx.Size(300,200) app = wx.PySimpleApp() frame = MyFrame(None, -1, size=desiredSize) frame.Show() app.MainLoop()
{ "language": "en", "url": "https://stackoverflow.com/questions/7600652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can someone write this code with better logic? I am stuck with this problem for 2 days. Can someone help me with the logic ? I am working on C++ programs for good algorithms. I am now working on the Danielson-Lanczos Algorithm to compute the FFT of a sequence. Looking at mmax=2; while (n>mmax) { istep = mmax<<1; theta = -(2*M_PI/mmax); wtemp = sin(0.5*theta); wpr = -2.0*wtemp*wtemp; wpi = sin(theta); wr = 1.0; wi = 0.0; for (m=1; m < mmax; m += 2) { for (i=m; i <= n; i += istep) { j=i+mmax; tempr = wr*data[j-1] - wi*data[j]; tempi = wr * data[j] + wi*data[j-1]; data[j-1] = data[i-1] - tempr; data[j] = data[i] - tempi; data[i-1] += tempr; data[i] += tempi; } wtemp=wr; wr += wr*wpr - wi*wpi; wi += wi*wpr + wtemp*wpi; } mmax=istep; } Source: http://www.eetimes.com/design/signal-processing-dsp/4017495/A-Simple-and-Efficient-FFT-Implementation-in-C--Part-I Is there any way to logically write a code such that the whole for-loop portion is reduced to just 4 lines of code (or even better)? A: Better indentation would go a long way. I fixed that for you. Also, this seems to beg for better locality of the variables. The variable names are not clear to me, but that might be because I don't know the domain this algorithm belongs to. Generally, if you want to make complex code easier to understand, identify sub-algorithms and put them into their own (inlined) functions. (Putting a code snippet into a function effectively gives it a name, and makes the passing of variables into and out of the code more obvious. Often, that makes code easier to digest.) I'm not sure this is necessary for this piece of code, though. Merely condensing code, however, will not make it more readable. Instead, it will just make it more condensed. A: Do not compress your code. Please? Pretty please? With a cherry on top? Unless you can create a better algorithm, compressing an existing piece of code will only make it look like something straight out of the gates of Hell itself. No one would be able to understand it. You would not be able to understand it, even a few days later. Even the compiler might get too confused by all the branches to properly optimize it. If you are trying to improve performance, consider the following: * *Premature optimization is the source of all evils. *Work on your algorithms first, then on your code. *The line count may have absolutely no relation to the size of the produced executable code. *Compilers do not like entangled code paths and complex expressions. Really... *Unless the code is really performance critical, readability trumps everything else. *If it is performance critical, profile first, then start optimizing. A: You could use a complex number class to reflect the math involved. A good part of the code is made of two complex multiplications. You can rewrite your code as : unsigned long mmax=2; while (n>mmax) { unsigned long istep = mmax<<1; const complex wp = coef( mmax ); complex w( 1. , 0. ); for (unsigned long m=1; m < mmax; m += 2) { for (unsigned long i=m; i <= n; i += istep) { j=i+mmax; complex temp = w * complex( data[j-1] , data[j] ); complexref( data[j-1] , data[j] ) = complex( data[i-1] , data[i] ) - temp ; complexref( data[i-1] , data[i] ) += temp ; } w += w * wp ; } mmax=istep; } With : struct complex { double r , i ; complex( double r , double i ) : r( r ) , i( i ) {} inline complex & operator+=( complex const& ref ) { r += ref.r ; i += ref.i ; return *this ; } }; struct complexref { double & r , & i ; complexref( double & r , double & i ) : r( r ) , i( i ) {} inline complexref & operator=( complex const& ref ) { r = ref.r ; i = ref.i ; return *this ; } inline complexref & operator+=( complex const& ref ) { r += ref.r ; i += ref.i ; return *this ; } } ; inline complex operator*( complex const& w , complex const& b ) { return complex( w.r * b.r - w.i * b.i , w.r * b.i + w.i * b.r ); } inline complex operator-( complex const& w , complex const& b ) { return complex( w.r - b.r , w.i - b.i ); } inline complex coef( unsigned long mmax ) { double theta = -(2*M_PI/mmax); double wtemp = sin(0.5*theta); return complex( -2.0*wtemp*wtemp , sin(theta) ); } A: * *I don't believe you would be able to make it substantially shorter. *If this code were made much shorter, I would guess that it would significantly diminish readability. *Since the logic is relatively clear, number of lines does not matter — unless you're planning on using this on codegolf.stackexchange.com, this is a place where you should trust your compiler to help you (because it will) *This strikes me as premature optimization.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery validation code for all checkboxes on a form I have a Form that generates a list of records with a checkbox for each record next to it. If the user does not check any of the records and hits submit, then a dialog box should warn him saying "you did not check any records". If he chooses to continue, then he will be redirected to the next page, otherwise he will be held on the same page to select the rest of the records. I am not so good with jQuery and javascript. Any help would be greatly appreciated. The logic i am looking for is something like this on submit button <script> if( (input:checkbox).count = (input:checkbox).is(checked).count //proceed to the next page else( dialogue("Message") ) </script> A: first, let's assume your form has id="myForm": $('#myForm').submit(function() { if($('#myForm input:checkbox:checked').length == 0) { //Tell the user he/she needs to check some boxes return false; // this stops the form from being submitted } }); EDIT: Remember to put all of this inside $('document').ready(function(){ }); A: in jQuery this will be: $(function(){ $('#submit').click(function(){ if($('input:checkbox:checked').length > 0){ // next }else{ alert('check a box'); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7600655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Good compression algorithm for small chunks of data? (around 2k in size) I have a system with one machine generate small chunks of data in the form of objects containing arrays of integers and longs. These chunks get passed to another server which in turn distributes them elsewhere. I want to compress these objects so the memory load on the pass-through server is reduced. I understand that compression algorithms like deflate need to build a dictionary so something like that wouldn't really work on data this small. Are there any algorithms that could compress data like this efficiently? If not, another thing I could do is batch these chunks into arrays of objects and compress the array once it gets to be a certain size. But I am reluctant to do this because I would have to change interfaces in an existing system. Compressing them individually would not require any interface changes, the way this is all set up. Not that I think it matters, but the target system is Java. Edit: Would Elias gamma coding be the best for this situation? Thanks A: If you think that reducing your data packet to its entropy level is at best as it can be, you can try a simple huffman compression. For an early look at how well this would compress, you can pass a packet through Huff0 : http://fastcompression.blogspot.com/p/huff0-range0-entropy-coders.html It is a simple 0-order huffman encoder. So the result will be representative. For more specific ideas on how to efficiently use the characteristics of your data, it would be advised to describe a bit what data the packets contains and how it is generated (as you have done in the comments, so they are ints (4 bytes?) and longs (8 bytes?)), and then provide one or a few samples. A: It sounds like you're currently looking at general-purpose compression algorithms. The most effective way to compress small chunks of data is to build a special-purpose compressor that knows the structure of your data. The important thing is that you need to match the coding you use with the distribution of values you expect from your data: to get a good result from Elias gamma coding, you need to make sure the values you code are smallish positive integers... If different integers within the same block are not completely independent (e.g., if your arrays represent a time series), you may be able to use this to improve your compression (e.g., the differences between successive values in a time series tend to be smallish signed integers). However, because each block needs to be independently compressed, you will not be able to take this kind of advantage of differences between successive blocks. If you're worried that your compressor might turn into an "expander", you can add an initial flag to indicate whether the data is compressed or uncompressed. Then, in the worst case where your data doesn't fit your compression model at all, you can always punt and send the uncompressed version; your worst-case overhead is the size of the flag... A: Elias Gamma Coding might actually increase the size of your data. You already have upper bounds on your numbers (whatever fits into a 4- or probably 8-byte int/long). This method encodes the length of your numbers, followed by your number (probably not what you want). If you get many small values, it might make things smaller. If you also get big values, it will probably increase the size (the 8-byte unsigned max value would become almost twice as big). Look at the entropy of your data packets. If it's close to the maximum, compression will be useless. Otherwise, try different GP compressors. Tho I'm not sure if the time spent compressing and decompressing is worth the size reduction. A: I would have a close look at the options of your compression library, for instance deflateSetDictionary() and the flag Z_FILTERED in http://www.zlib.net/manual.html. If you can distribute - or hardwire in the source code - an agreed dictionary to both sender and receiver ahead of time, and if that dictionary is representative of real data, you should get decent compression savings. Oops - in Java look at java.util.zip.Deflater.setDictionary() and FILTERED.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MySQL error when inserting data containing apostrophes (single quotes)? When I an insert query contains a quote (e.g. Kellog's), it fails to insert a record. ERROR MSG: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's','Corn Flakes 170g','$ 15.90','$ 15.90','$ 14.10','--')' at line 1MySQL Update Error: The first 's', should be Kellogg's. Is there any solution? A: Replace mysql with mysqli. Use this mysqli_real_escape_string($connection,$_POST['Description']) A: You should pass the variable or data inside mysql_real_escape_string(trim($val)), where $val is the data on which you are getting an error. If you enter the text, i.e., "I love Kellog's", we have a ' in the string so it will break the query. To avoid it you need to store data in a variable like this $val = "I love Kellog's". Now, this should work: $goodval = mysql_real_escape_string(trim($val)); A: You can also use the addslashes() function which automatically puts \ before ' to avoid error A: Escape the quote with a backslash. Like 'Kellogg\'s'. Here is your function, using mysql_real_escape_string: function insert($database, $table, $data_array) { // Connect to MySQL server and select database $mysql_connect = connect_to_database(); mysql_select_db ($database, $mysql_connect); // Create column and data values for SQL command foreach ($data_array as $key => $value) { $tmp_col[] = $key; $tmp_dat[] = "'".mysql_real_escape_string($value)."'"; // <-- escape against SQL injections } $columns = join(',', $tmp_col); $data = join(',', $tmp_dat); // Create and execute SQL command $sql = 'INSERT INTO '.$table.'('.$columns.')VALUES('. $data.')'; $result = mysql_query($sql, $mysql_connect); // Report SQL error, if one occured, otherwise return result if(!$result) { echo 'MySQL Update Error: '.mysql_error($mysql_connect); $result = ''; } else { return $result; } } A: You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string) using a \. Add a \ before the apostrophe in Kellogg's, giving you Kellogg\'s. A: In standard SQL, you use two single quotes to indicate one single quote, hence: INSERT INTO SingleColumn(SingleChar) VALUES(''''); The first quote opens the string; the second and third are a single quote; and the fourth terminates the string. In MySQL, you may also be able to use a backslash instead: INSERT INTO SingleColumn(SingleChar) VALUES('\''); So, in your example, one or both of these should work: INSERT INTO UnidentifiedTable VALUES('Kellog''s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--'); INSERT INTO UnidentifiedTable VALUES('Kellog\'s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--'); In PHP, there is a function to sanitize user data (mysql_real_escape_string) before you embed it into an SQL statement -- or you should use placeholders. Note that if you do not sanitize your data, you expose yourself to SQL Injection attacks. A: User this one. mysql_real_escape_string(trim($val)); A: Optimized for multiple versions of PHP function mysql_prep($value){ $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysql_real_escape_string");//i.e PHP>=v4.3.0 if($new_enough_php){//php v4.3.o or higher //undo any magic quote effects so mysql_real_escape_string( can do the work if($magic_quotes_active){ $value = stripslashes($value); } $value = mysql_real_escape_string(trim($value)); }else{//before php v4.3.0 //if magic quotes arn't already on, add slashes if(!$magic_quotes_active){ $value = addslashes($value); //if magic quotes are already on, shashes already exists } } return $value; } Now just use: mysql_prep($_REQUEST['something']) A: Escape it by using a helper function like: function safeDBname($table_name) { $outputText=str_replace("&#39;","",$outputText); return strtolower($outputText); } A: i did it as below- in my case description field contains apostrophe('). and here is code: $description=mysql_real_escape_string($description); "insert into posts set name='".$name."', address='".$address."', dat='".$dt."', description='".$description."'"; it solved my problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7600661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: backbone event trigger I want to trigger a custom event from my backbone view class then where I Instantiate the view I want to listen for the event. Simplified Example: var view = Backbone.View.extend({ render:function(){ this.trigger('customEvent', "working"); } }); // Separate js file with jquery ready method. $(function() { var myView = new view(); myView.bind('customEvent', this.customEventHandler); function customEventHandler() { // do stuff } }); A: If the error you're getting is "callback[0] is undefined", then your problem is in the event binding. Where you have: myView.bind('customEvent', this.customEventHandler); What does this refer to, and does it have a customEventHandler method? If this is all happening in the global scope, you can just pass in a plain function, no this required: var view = Backbone.View.extend({ render:function(){ _this.trigger('customEvent', "working"); } }); // define your callback function customEventHandler() { // do stuff } myView = new view(); myView.bind('customEvent', customEventHandler); This will work even with a $(document).ready() function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to make a small transparent modal overal to signify loading data? I'm sure this has been asked before, but I've had no luck finding it. In my app data is loading synchronously, which locks up the app. I've tried asynch loading, but that doesn't work with the JSON parser. To denote that the app isn't frozen, just working on downloading data, I was hoping to present the user with a small transparent overlay with the loading icon. I was wondering how to go about this - do I need to put it on another thread? To clarify, I want to do something very similar to the Netflix iPad app - their loading overlay is perfect for the projet I'm working on. Edit: I've added some async code below I first call this function: NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSURLConnection *c = [[NSURLConnection alloc] init]; [self connectionWorks:c didReceiveData:data]; connectionworks -(void)connectionWorks:(NSURLConnection *)connection didReceiveData:(NSData *)data{ OLWork *newWork; NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSDictionary *results = [jsonString JSONValue]; NSArray *rawBooks = [results objectForKey:@"works"]; for (NSDictionary *work in rawBooks) { newWork = [[OLWork alloc] init]; newWork.title = [work objectForKey:@"title"]; newWork.author = [[[work objectForKey:@"authors"] objectAtIndex:0] objectForKey:@"name"]; newWork.key = [work objectForKey:@"key"]; [self.works setValue:newWork forKey:newWork.title]; } } A: This will do the job for you, it's well documented and easy to use https://github.com/jdg/MBProgressHUD Out of intrest which JSON parser are you using? Getting asynchronous requests working would be a much better solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need more precision from fprintf - Matlab M-File fprintf('\n\nn!\n') for i=[1:length(timearray)] fprintf('%s \t %d \n', stringarray{i},factorial(timearray(i))) end Output n! microsecond 1 minute Inf hour Inf day Inf month Inf year Inf century Inf I'm trying to calculate the number of steps an algorithm that runs at n! takes at the above intervals (assuming 1 step = 1 microsecond). However, I am unable to get fprintf to display meaningful results. Switching to fprintf('%s \t %bu \n', stringarray{i},factorial(timearray(i))) gave me some numbers, but I suspect they are wrong. %bu Output n! microsecond 04607182418800017408 minute 09218868437227405312 hour 09218868437227405312 day 09218868437227405312 month 09218868437227405312 year 09218868437227405312 century 09218868437227405312 Disclaimer: I wrote this program to solve a homework problem, however the homework never specified to write a program. Thanks for any help! Mike A: The problem is likely not with printing per se, but that the factorial computation itself is overflowing. Try just evaluating the value instead of printing it in the loop; you'll find that the factorial function overflows after 170!. One simple way to circumvent this is by returning the log-factorial instead: log_factorial = @(n) sum(log(1:n)); Then you can compare values on vastly different scales without worrying about overflow. Note: the above function is not vectorized so it will only work with a single value input; if you need to work with array values then there appear to be other solutions already available. A: It looks like Matlab probably has 64 bit integers and that number is the largest that factorial could fit into it before the integer ran out of room. I don't have Matlab so can't test it out, but just stop and think about how big a number factorial(century) is going to be...
{ "language": "en", "url": "https://stackoverflow.com/questions/7600678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining two functions not working I attempted to combine two functions in the code below. All seems to be working except I cannot get the variable currentImage.metaData.something to work in the second function. I appreciate your advice. <script type="text/javascript" src="code.photoswipe-2.1.5.min.js"></script> <script type="text/javascript"> (function(window, PhotoSwipe){ document.addEventListener('DOMContentLoaded', function(){ var options = { getImageMetaData: function(el){ return { href: el.getAttribute('href'), something: el.getAttribute('data-something'), anotherThing: el.getAttribute('data-another-thing') } } }, instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options ); instance.addEventHandler(PhotoSwipe.EventTypes.onDisplayImage, function(e){ var currentImage = instance.getCurrentImage(); console.log(currentImage.metaData.something); console.log(currentImage.metaData.anotherThing); }); }, false); }(window, window.Code.Util, window.Code.PhotoSwipe)); (function(window, Util, PhotoSwipe){ document.addEventListener('DOMContentLoaded', function(){ var sayHiEl, sayHiClickHandler = function(e){ alert('yo!!!'); } options = { getToolbar: function(){ return '<div class="ps-toolbar-close" style="padding-top: 12px;">Close</div><div class="ps-toolbar-play" style="padding-top: 12px;">Play</div><div class="ps-toolbar-previous" style="padding-top: 12px;">Previous</div><div class="ps-toolbar-next" style="padding-top: 12px;">Next</div><div class="say-hi" style="padding-top: 12px;">Say Hi!</div>'; // NB. Calling PhotoSwipe.Toolbar.getToolbar() wil return the default toolbar HTML } }, instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options ); // onShow - store a reference to our "say hi" button instance.addEventHandler(PhotoSwipe.EventTypes.onShow, function(e){ sayHiEl = window.document.querySelectorAll('.say-hi')[0]; }); // onToolbarTap - listen out for when the toolbar is tapped instance.addEventHandler(PhotoSwipe.EventTypes.onToolbarTap, function(e){ if (e.toolbarAction === PhotoSwipe.Toolbar.ToolbarAction.none){ if (e.tapTarget === sayHiEl || Util.DOM.isChildOf(e.tapTarget, sayHiEl)){ alert(currentImage.metaData.anotherThing); } } }); // onBeforeHide - clean up instance.addEventHandler(PhotoSwipe.EventTypes.onBeforeHide, function(e){ sayHiEl = null; }); }, false); }(window, window.Code.Util, window.Code.PhotoSwipe)); A: You're declaring the currentImage variable within the first function. Variables created with the var keyword are function-scoped, meaning that it isn't visible outside of the function (and hence not visible in your second function, in this case). I would probably suggest some more general code reorganization, but an easy fix would be to declare the variable above both of your functions, making it visible to both.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RootViewController - tableView:cellForRowAtIndexPath - Load image from assetsLibrary StackOverflow friends and colleague programmers, My RootViewController (a flowerTableView on a view) should display cell's with title, subtitle and an image thumbnail (loaded from the camera roll). A very basic table I guess. All content is stored in 'Core Data' but the images are stored as imagePaths to the camera roll. Example: flower.imagePath = assets-library://asset/asset.JPG?id=1000000002&ext Using the code at the bottom everything should run smoothly but it doesn't . When starting the App the title's and subtitle's are shown, but the images are not. When I press a cell, which display's the detail view, and pop back again to the main view the image for this specific cell is shown. When I press 'Show All', a button on a toolbar which executes the following code NSFetchRequest *fetchRequest = [[self fetchedResultsController] fetchRequest]; [fetchRequest setPredicate:nil]; NSError *error = nil; if (![[self fetchedResultsController] performFetch:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } [self.flowerTableView reloadData]; and reloads the table, all the beautiful flowers are now shown. Why didn't the flowers be displayed the first time? Is this a caching problem? When debugging this code the string: 'This debug string was logged after this function was done' was logged after loading the table on starting the app, not after pressing 'Show All' This means that all images are loaded from the camera roll successfully but attached to the cell after the cell was displayed and therefore not shown. The same line is printed as intended when pressing 'Show All' Hope someone can tell me what's going on here and even better, what to change in my code to make this work. I'm stuck at the moment... Thank for helping me out! Edwin :::THE CODE::: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath *)indexPath { Flower *flower = [fetchedResultsController_ objectAtIndexPath:indexPath]; static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell... // Display the image if one is defined if (flower.imagePath && ![flower.imagePath isEqualToString:@""]) { // Should hold image after executing the resultBlock __block UIImage *image = nil; ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *asset) { NSLog(@"This debug string was logged after this function was done"); image = [[UIImage imageWithCGImage:[asset thumbnail]] retain]; }; ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) { NSLog(@"Unresolved error: %@, %@", error, [error localizedDescription]); }; [assetsLibrary_ assetForURL:[NSURL URLWithString:flower.imagePath] resultBlock:resultBlock failureBlock:failureBlock]; [cell.imageView setImage:image]; } return cell; } A: -[ALAssetsLibrary assetForURL:resultBlock:failureBlock] runs asynchronously. That means that the call returns immediately in your tableView:cellForRowAtIndexPath: method. The cell is displayed in the table view before the actual loading of the asset has taken place. What you need to do is set the image for the cell in the result block. Something like this: if (flower.imagePath && ![flower.imagePath isEqualToString:@""]) { ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *asset) { NSLog(@"This debug string was logged after this function was done"); [cell.imageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]]; //this line is needed to display the image when it is loaded asynchronously, otherwise image will not be shown as stated in comments [cell setNeedsLayout]; }; ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) { NSLog(@"Unresolved error: %@, %@", error, [error localizedDescription]); }; [assetsLibrary_ assetForURL:[NSURL URLWithString:flower.imagePath] resultBlock:resultBlock failureBlock:failureBlock]; } A: Fellow Overflowist let me propose the following solution: rather than creating your cells in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath *)indexPath create an NSMutableArray populated with UITableViewCells (the same ones you create in the cellForRowAtIndexPath method) that you want to display in the table and simply return the relevant UITableViewCell (which will be an object in the NSMutableArray) in the cellForRowAtIndexPath method. This way the cellForRowAtIndexPath method will show cells which have already been loaded and are ready to be shown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rspec testing conditional routing constraints I'm trying to write some rspec integration tests to test that my conditional routes are routing correctly, but I'm getting a bunch of problems. In routes.rb: root :to => "error#ie6", :constraints => {:user_agent => /MSIE 6/} root :to => "protocol_sets#index", :constraints => UserRoleConstraint.new(/doctor/i) root :to => "refill_requests#create", :constraints => UserRoleConstraint.new(/member/i) root :to => "refill_requests#create", :constraints => {:subdomain => "demo"} root :to => "site#index" In spec/requests/homepage_routing_spec.rb require 'spec_helper' describe "User Visits Homepage" do describe "Routings to homepage" do it "routes / to site#index when no session information exists" do visit root_path end end end I get the following error when I try to run the test. Failures: 1) User Visits Homepage Routings to homepage routes / to site#index when no session information exists Failure/Error: visit root_path NoMethodError: undefined method `match' for nil:NilClass # :10:in `synchronize' # ./spec/requests/homepage_routings_spec.rb:6:in `block (3 levels) in ' Finished in 0.08088 seconds 1 example, 1 failure Failed examples: rspec ./spec/requests/homepage_routings_spec.rb:5 # User Visits Homepage Routings to homepage routes / to site#index when no session information exists From Googling around I'm guessing there may be a problem with how rspec/capybara handle conditional routes. Is there anyway to test constraints on routes with rspec and capybara? A: As this drove me nuts over the last days, I found the solution with the help of a colleague. When using named route constraints, like UserRoleConstraint in the example, I resorted to actually stubbing the matches? method of the constraint int he specs that needed it, i.e.: describe 'routing' do context 'w/o route constraint' do before do allow(UserRoleConstraint).to receive(:matches?).and_return { false } end # tests without the route constraint end context 'w/ route constraint' do before do allow(UserRoleConstraint).to receive(:matches?).and_return { true } end end # tests with the route constraint end Note that this requires you to have named constraints, which might not apply to your case. A: For the protocol constraint you can just specify an entire url with dummy domain. See this answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is this design in 5NF? A user can have only one blog (the user owns the blog) Blogs can have multiple posts. Groups can have only one blog (but no particular user owns the blog, it is assumed the group owner created the blog thus userid is only an attribute of user blogs not group blogs so subtyping is needed) When group_blog_post is deleted, the underlying blog_posts row should be deleted as well, is this best accomplished using a trigger? A: For a table to be in 5NF, it must first be in 4NF. To be in 4NF, it must first be in 3NF. And so on, down to 1NF. Loosely speaking, the lower normal forms have to do with dependencies between candidate keys and non-prime attributes. But the only non-prime attributes we can see are "title" and "is_private". So there's really no way to tell. To take one table as an example, "group_users" is in 5NF if it has no other columns. Later If you extend the table group_users like this create table group_users ( group_id integer not null references groups (group_id), user_id integer not null refrences users (user_id), user_type_id integer not null references user_types (user_type_id), primary key (group_id, user_id) ); then you're still in 5NF. The column "user_type_id" isn't dependent only on user_id--if it were, you wouldn't be in 2NF. But the user_type_id isn't an attribute of the user alone; it's an attribute of the user in this particular group. No partial key dependencies; no transitive dependencies; no independent, multi-valued facts; no join dependencies; so it's in 5NF. That structure allows only one user_type_id per user per group. If you think users should have multiple user types in each group, then this create table group_users ( group_id integer not null references groups (group_id), user_id integer not null refrences users (user_id), user_type_id integer not null references user_types (user_type_id), primary key (group_id, user_id, user_type_id) ); is also in 5NF. No partial key dependencies; no transitive dependencies; no independent, multi-valued facts; no join dependencies; so it's in 5NF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Order/limit By issue i have a problem with a script i'm creating. I am using the PHP/SQL Statement ORDER BY. I have a topsite where i use the script below $sql = "SELECT * FROM topsites WHERE categorie = '".$_GET['c']."' ORDER BY in DESC, out DESC LIMIT ".$perpage.""; And i need to know if there's a way i can create different pages, say first page is 1-50, second is 50-100 I have searched google for a solution to this question, but i can't seem to find anything. A: SELECT .... LIMIT CountToSkip, CountToSelect The first page will be LIMIT 0,50, LIMIT 50,50 on the second, etc. A: The technique you are looking for is called pagination. You will likely want to use SQL's LIMIT operator to achieve this, but there are many links on the web to point you to PHP pagination resources. A: LIMIT 0,100 , LIMIT 100,100 Pretty easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Editor to handle merge conflict Is there an editor that recognizes merge conflict tags and displays the sections side by side? Preferably something like p4merge? <<<<< local ... ========= .... >>>>> remote A: our tool ECMerge (http://www.elliecomputing.com) does that, it has a Open Conflict file menu which works with markers from SVN, CVS, Mercurial, Bazaar, Git and Perforce. the menu is present also in the explorer plugins for Windows Exlorer, Nautilus, Konqueror and Thunar on Linux. A: My approach to this has been to use KDiff3 (an extremely useful tool for diff/merge) and feed it 3 files extracted with git cat-file and git ls-files -u. It is a bit of work, but then I get to know exactly what is going on. Git have added support for configuring a specific merge tool, so probably it should be possible to do the operation more simpler than
{ "language": "en", "url": "https://stackoverflow.com/questions/7600714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to use 2 different examples table in Cucumber/Cuke4Duke Is it possible to somehow construct a Scenario which uses two different Example tables in different steps? Something like this: Given I log in When I view a page Then I should see <goodText> Examples: |goodText| |abc| And I should not see <badText> Examples: |badText| |xyz| The scenario above doesn't work, also in reality there would be more rows to each table. A: It looks like you're confusing tables with scenario examples. You can mix them, but from your example I'm not sure what you're trying to achieve. Why not just write: Given I log in When I view a page Then I should see "abc" But I should not see "xyz" or if you wanted to check for multiple strings: Given I log in When I view a page Then I should see the following text: | abc | | def | But I should not see the following text: | xyz | | uvw | A: You say that in reality there would be many more rows to the table; but of course a table can also have many columns. Would this not work for you? Given I log in When I view a page Then I should see <goodText> But I should not see <badText> Examples: |goodText| badText | |abc | xyz |
{ "language": "en", "url": "https://stackoverflow.com/questions/7600715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Objective C: Accessing constants from other classes I have a constant in one class that I want to access from another. I want to access these: #define kStateRunning 1 #define kStateGameOver 2 #define kStateMenu 3 which are in my GameController.h from Level1.m. In Level1.h I have @class GameController as well as an import in the implementation file. I tried searching for an answer, but I'm not sure if I'm wording all this correctly. A: If you use #define myConstant, myConstant will be known since you import your file. Define them at the beginning of your GameController.h between the import and the @Interface for example. Then if you import GameController.h in one of your other files (let's take Level1.m for example). You can use it, without prefixing it. Just use myConstant A: I wouldn't use #define as you lose any checking from the compiler. Generally you use a constant to avoid using magic values throughout your code that can be spelt wrong or typed wrong. In the Apple docs for Coding Guidelines they tell you how you should approach each type of constant. For simple integers like you have, they suggest enums are the best option. They are used extensively in the Apple frameworks so you know they are good. You would still need to define it in your header. e.g. (Use your own prefix instead of PS) typedef enum { PSGameStateRunning = 1, PSGameStateGameOver, PSGameStateMenu, } PSGameState; This also has the advantage of being a type that you can pass into/return from functions if you require
{ "language": "en", "url": "https://stackoverflow.com/questions/7600717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cleaning up $PATH in bash My path has a lot of entries that were added long ago by scripts. They are not in my .bashrc, .bash_profile, or .bash_login. I'm worried that resetting my path in .bashrc will have undesirable long-term results. Is there a way to find where things have been added to my path and remove them manually? Are things always added by file or is path cached somewhere? If the latter, is it easy to clean that up? A: You shouldn't let some random sysadmin decide what's in your PATH anyway, you should set it to the PATH you need. You begin with # POSIX way of getting the system's PATH to POSIX tools: PATH=$(getconf PATH) # Or /usr/bin/getconf PATH. followed by whatever you require in addition, e.g. PATH="$PATH:/usr/local/bin" PATH="$PATH:/usr/local/sbin" PATH="$PATH:$HOME/bin" and put this in your shell's .profile or equivalent. Note that you do not want . or world-writable directories in your PATH for security reasons. A: You're always at liberty to look at the directory contents for each component of $PATH and decide whether you use the programs therein. If you don't use the programs, the chances are, you won't be hurt by removing the directory from $PATH. If the directory doesn't exist, then you can completely safely remove it. It is puzzling that the directories show up in your profile and related files. You should check for ~/.profile too. You should also look at material like /etc/profile. Personally, I consider I am in charge of my PATH. I set it from scratch according to my rules, picking the directories I need. You're not obliged to accept what the system admins set for you, though you should not idly remove PATH components that they've added. But their views on what's desirable may be different from yours. The only long-term undesirable effect might be that some program you use stops working because it relied on something from the old version of $PATH. So, keep a record of what you had before you started messing with PATH - but don't be afraid to adjust PATH to suit yourself. A: The easiest way to find who modified your PATH is to run: $ bash --login -i -xv 2>&1 | grep ' \. ' For example I got: + . /etc/profile.d/bash_completion.sh . /etc/bash_completion ++ . /etc/bash_completion +++ . /etc/bash_completion.d/abook +++ . /etc/bash_completion.d/ant + . /etc/profile.d/lapack0.sh + . /etc/profile.d/openssl.sh + . /etc/profile.d/qt3-devel.sh + . /etc/profile.d/tetex-profile.sh + . /etc/profile.d/xinit.sh + . /etc/bash.bashrc ... A: Check your /etc/profile file, and, depending on your OS version, /etc/profile.d/ directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: hive sql aggregate I have two tables in Hive, t1 and t2 >describe t1; >date_id string >describe t2; >messageid string, createddate string, userid int > select * from t1 limit 3; > 2011-01-01 00:00:00 2011-01-02 00:00:00 2011-01-03 00:00:00 > select * from t2 limit 3; 87211389 2011-01-03 23:57:01 13864753 87211656 2011-01-03 23:57:59 13864769 87211746 2011-01-03 23:58:25 13864785 What I want is to count previous three-day distinct userid for a given date. For example, for date 2011-01-03, I want to count distinct userid from 2011-01-01 to 2011-01-03. for date 2011-01-04, I want to count distinct userid from 2011-01-02 to 2011-01-04 I wrote the following query. But it does not return three-day result. It returns distinct userid per day instead. SELECT to_date(t1.date_id), count(distinct t2.userid) FROM t1 JOIN t2 ON (to_date(t2.createddate) = to_date(t1.date_id)) WHERE date_sub(to_date(t2.createddate),0) > date_sub(to_date(t1.date_id), 3) AND to_date(t2.createddate) <= to_date(t1.date_id) GROUP by to_date(t1.date_id); `to_date()` and `date_sub()` are date function in Hive. That said, the following part does not take effect. WHERE date_sub(to_date(t2.createddate),0) > date_sub(to_date(t1.date_id), 3) AND to_date(t2.createddate) <= to_date(t1.date_id) EDIT: One solution can be (but it is super slow): SELECT to_date(t3.date_id), count(distinct t3.userid) FROM ( SELECT * FROM t1 LEFT OUTER JOIN t2 WHERE (date_sub(to_date(t2.createddate),0) > date_sub(to_date(t1.date_id), 3) AND to_date(t2.createddate) <= to_date(t1.date_id) ) ) t3 GROUP by to_date(t3.date_id); UPDATE: Thanks for all answers. They are good. But Hive is a bit different from SQL. Unfortunately, they cannot use in HIVE. My current solution is to use UNION ALL. SELECT * FROM t1 JOIN t2 ON (to_date(t1.date_id) = to_date(t2.createddate)) UNION ALL SELECT * FROM t1 JOIN t2 ON (to_date(t1.date_id) = date_add(to_date(t2.createddate), 1) UNION ALL SELECT * FROM t1 JOIN t2 ON (to_date(t1.date_id) = date_add(to_date(t2.createddate), 2) Then, I do group by and count. In this way, I can get what I want. Although it is not elegant, it is much efficient than cross join. A: You need a subquery: try something like this (i cannot test because i don't have hive) SELECT to_date(t1.date_id), count(distinct t2.userid) FROM t1 JOIN t2 ON (to_date(t2.createddate) = to_date(t1.date_id)) WHERE t2.messageid in ( select t2.messageid from t2 where date_sub(to_date(t2.createddate),0) > date_sub(to_date(t1.date_id), 3) AND to_date(t2.createddate) <= to_date(t1.date_id) ) GROUP by to_date(t1.date_id); the key is that with subquery FOR EACH date in t1, the right records are selected in t2. EDIT: Forcing subquery in from clause you could try this: SELECT to_date(t1.date_id), count(distinct t2.userid) FROM t1 JOIN (select userid, createddate from t2 where date_sub(to_date(t2.createddate),0) > date_sub(to_date(t1.date_id), 3) AND to_date(t2.createddate) <= to_date(t1.date_id) ) as t2 ON (to_date(t2.createddate) = to_date(t1.date_id)) GROUP by to_date(t1.date_id); but don't know if could work. A: I am making an assumption that t1 is used to define the 3 day period. I suspect the puzzling approach is due to Hive's shortcomings. This allows you to have an arbitrary number of 3 day periods. Try the following 2 queries SELECT substring(t1.date_id,1,10), count(distinct t2.userid) FROM t1 JOIN t2 ON substring(t2.createddate,1,10) >= date_sub(substring(t1.date_id,1,10), 2) AND substring(t2.createddate,1,10) <= substring(t1.date_id,1,10) GROUP BY t1.date_id --or-- SELECT substring(t1.date_id,1,10), count(distinct t2.userid) FROM t1 JOIN t2 ON t2.createddate like substring(t1.date_id ,1,10) + '%' OR t2.createddate like substring(date_sub(t1.date_id, 1) ,1,10) + '%' OR t2.createddate like substring(date_sub(t1.date_id, 2) ,1,10) + '%' GROUP BY t1.date_id The latter minimizes the function calls on the t2 table. I am also assuming that t1 is the smaller of the 2. substring should return the same result as to_date. According to the documentation, https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions, to_date returns a string data type. Support for date data types seems minimal but I am not familiar with hive. A: The following should seem to work in standard SQL... SELECT to_date(t1.date_id), count(distinct t2.userid) FROM t1 LEFT JOIN t2 ON to_date(t2.createddate) >= date_sub(to_date(t1.date_id), 2) AND to_date(t2.createddate) < date_add(to_date(t1.date_id), 1) GROUP BY to_date(t1.date_id) It will, however, be slow. Because you are storing dates as strings, the using to_date() to convert them to dates. What this means is that indexes can't be used, and the SQL engine can't do Anything clever to reduce the effort being expended. As a result, every possible combination of rows needs to be compared. If you have 100 entries in T1 and 10,000 entries in T2, your SQL engine is processing a million combinations. If you store these values as dates, you don't need to_date(). And if you index the dates, the SQL engine can quickly home in on the range of dates being specified. NOTE: The format of the ON clause means that you do not need to round t2.createddate down to a daily value. EDIT Why your code didn't work... SELECT to_date(t1.date_id), count(distinct t2.userid) FROM t1 JOIN t2 ON (to_date(t2.createddate) = to_date(t1.date_id)) WHERE date_sub(to_date(t2.createddate),0) > date_sub(to_date(t1.date_id), 3) AND to_date(t2.createddate) <= to_date(t1.date_id) GROUP by to_date(t1.date_id); This joins t1 to t2 with an ON clause of (to_date(t2.createddate) = to_date(t1.date_id)). As the join is a LEFT OUTER JOIN, the values in t2.createddate MUST now either be NULL (no matches) or be the same as t1.date_id. The WHERE clause allows a much wider range (3 days). But the ON clause of the JOIN has already restricted you data down to a single day. The example I gave above simply takes your WHERE clause and put's it in place of the old ON clause. EDIT Hive doesn't allow <= and >= in the ON clause? Are you really fixed in to using HIVE??? If you really are, what about BETWEEN? SELECT to_date(t1.date_id), count(distinct t2.userid) FROM t1 LEFT JOIN t2 ON to_date(t2.createddate) BETWEEN date_sub(to_date(t1.date_id), 2) AND date_add(to_date(t1.date_id), 1) GROUP BY to_date(t1.date_id) Alternatively, refactor your table of dates to enumerate the dates you want to include... TABLE t1 (calendar_date, inclusive_date) = { 2011-01-03, 2011-01-01 2011-01-03, 2011-01-02 2011-01-03, 2011-01-03 2011-01-04, 2011-01-02 2011-01-04, 2011-01-03 2011-01-04, 2011-01-04 2011-01-05, 2011-01-03 2011-01-05, 2011-01-04 2011-01-05, 2011-01-05 } SELECT to_date(t1.calendar_date), count(distinct t2.userid) FROM t1 LEFT JOIN t2 ON to_date(t2.createddate) = to_date(t1.inclusive_date) GROUP BY to_date(t1.calendar_date)
{ "language": "en", "url": "https://stackoverflow.com/questions/7600726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Personalize the Google Maps badge I would like to personalize the position badge on a Google Map (with API). I know it's possible to change the appeareance of the badge with CSS or image. But how I can do that ? This is what I want : The small rectangle is the normal view, and the big rectangle is the clicked view (with informations). Thanks !!! A: The 'big rectangle' and 'small rectangle' are both infowindows. Styling infowindows has been asked here before: Styling Google Maps InfoWindow You'd need to have an event listener, so initially the small infowindows are all displayed on load. Then when you click on a point or on an infowindow, you then show the large infowindow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: asp.net c# ExecuteReader() error The following code produces an error. dbo.getit works fine when I call it directly on the server. The error occurs at cmd.ExecuteReader() . What am I doing wrong? string user; string pw; SqlDataReader dr = null; SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=myDB; Integrated Security=True"); user = Username.Text.Trim(); pw = Password.Text.Trim(); conn.Open(); try { SqlCommand cmd = new SqlCommand("dbo.getit", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@param1", user); cmd.Parameters.AddWithValue("@param2", pw); dr = cmd.ExecuteReader(); while ( dr.Read() ) { Session["username"] = user; // Session["admin"] = // Session["completed"] = Server.Transfer("all_is_well.aspx"); } conn.Close(); conn.Dispose(); } catch (Exception ex) { if (dr != null) { dr.Close(); conn.Close(); } Server.Transfer("ERROR.aspx"); } SOLUTION: Replace the two corresponding lines above with these: SqlCommand cmd = new SqlCommand("select * from dbo.getit(@param1, @param2);", conn); cmd.CommandType = CommandType.text; A: This just seems questionable, Session["username"] = user; Server.Transfer("all_is_well.aspx"); inside the while loop! Can you at least finish iterating on the reader, using a temporary object to store the result of the query, and then initialize you session and do the Server.Transfer. . A: Server.Transfer terminates execution of the current page and starts execution of a new page for the current request. Also, Transfer calls End, which throws a ThreadAbortException exception upon completion. I think what you are trying to do (and I am answering based on what you are trying to do - not necessarily best pratice) is verify that the user is authorized/authenticated in some way based on a data store. You'd be better off not using ExecuteReader at all. Use ExecuteScalar. If the result of ExecuteScalar is not null, the user was found. if (cmd.ExecuteScalar() != null) { Server.Transfer("all_is_well.aspx"); } else { Server.Transfer("someErrorPage.aspx"); } A: SOLUTION: Replace the two corresponding lines above with these: SqlCommand cmd = new SqlCommand("select * from dbo.getit(@param1, @param2);", conn); cmd.CommandType = CommandType.text; That worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL - Get matches where match is NULL or parameter with one-to-many Table Rule: RuleID RuleName 1 Rule1 2 Rule2 3 Rule3 4 Rule4 Table Equipment: EquipmentID EquipmentName EquipmentCode 1 Equip1 E1 2 Equip2 E2 3 Equip3 E3 Table RuleEquipment: EquipmentRuleID RuleID EquipmentID 1 1 1 2 1 2 3 2 1 4 2 3 5 3 2 A user will query using one and only one EquipmentCode. I want to return the Rules which either have no associated Equipment or have the matching equipment. So, if a user queries for E1, the result set should be RuleID RuleName 1 Rule1 2 Rule2 4 Rule4 I cannot put my finger on the WHERE clause for this. Any suggestions? A: SELECT * FROM Rule WHERE Rule.ID NOT IN (SELECT RuleID FROM RuleEquipment) OR Rule.ID IN ( SELECT RuleID FROM RuleEquipment INNER JOIN Equipment ON RuleEquipment.EquipmentID = Equipment.EquipmentID WHERE Equipment.EquipmentCode = @inputEquipmentCode ) A: select * from [Rule] as R where R.RuleID in (select RE.RuleID from RuleEquipment as RE inner join Equipment as E on RE.EquipmentID = E.EquipmentID where E.EquipmentCode = 'E1') or R.RuleID not in (select RE.RuleID from RuleEquipment as RE) A: SELECT Rule.* FROM Rule LEFT OUTER JOIN RuleEquipment ON RuleEquipment.RuleID = Rule.RuleID Where Rule.RuleID = 1 or RuleID IS NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/7600731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using 'printf' to return string, not print it This may sound strange, but here goes. I like using this technique of building a string in php printf(__('This is %1$s, this is %2$s'), myFunction1(), myFunction2()); Obviously this directly prints the results whenever the function is called, but I would like to use this technique to just build a string, and then use it later elsewhere. Is this possible? Thanks guys. A: Use sprintf to do this: $var = sprintf(__('This is %1$s, this is %2$s'), myFunction1(), myFunction2());
{ "language": "en", "url": "https://stackoverflow.com/questions/7600732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: how to pass mysql_insert_id() to either $_POST or form action? I have a form page in which either an INSERT or an UPDATE query is submitted, depending on the presence/absence of an ID (and when there's an ID it's used to retrieve the record and pre-populate the form). In either case, the processing is in form.php so the form's action is itself (action="/form.php">). My problem is that when form.php reloads post-submit, the URL has an empty ID so the page enters 'INSERT' mode, rather than 'UPDATE' mode. What's the best practice way to resolve this? * *What operator/condition should I add to this 'if' ... if (isset($_GET['ID']) && is_numeric($_GET['ID'])) { ... to include post-submit empty ID URL (i.e., form.php?ID=) OR, * *How do I pass `$newID = mysql_insert_id();1 to the form's action? (I've tried a number of variations here w/out success) $newID = mysql_insert_id(); ... [ snip ] ... <form method="post" action="/html/form.php?ID=<?php echo $newID; ?>"> I'm reading about hidden inputs and sessions but it's not yet clear to me how to use either to solve this problem. Lastly, since it isn't absolutely necessary that I reload the form page, I'm increasingly tempted to move the form processing/db queries to another page (e.g., process.php) to hopefully simplify; any opinions on this? What's best/common practice? Many thanks in advance, svs A: Common practice should be to keep data posting separate from data displaying. This prevents accidental adds on a user's first arrival to the page as well as accidental double-posts if the user hits refresh. In addition, keeping the logic separate makes the code more readable and maintainable in the future. The approach you should probably look for is: view.php?ID=<record to view> // Only displays a record already in the DB add.php // The add record form with action="process_add.php" process_add.php?Field1=<>&Field2=<>... // Receives data from add.php, puts it in // the database and then forwards back to // view.php or add.php as you see fit. EDIT: While I have GET arguments on process_add.php, they are only there to demonstrate that they are being passed. They should be sent as POST arguments in and actual implementation. A: here is an example of such a code, using templates. working CRUD application based on the idea of passing id dunno, though, why do you need to pass freshly generated id. <? mysql_connect(); mysql_select_db("new"); $table = "test"; if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part: $name = mysql_real_escape_string($_POST['name']); if ($id = intval($_POST['id'])) { $query="UPDATE $table SET name='$name' WHERE id=$id"; } else { $query="INSERT INTO $table SET name='$name'"; } mysql_query($query) or trigger_error(mysql_error()." in ".$query); header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); exit; } if (!isset($_GET['id'])) { //listing part: $LIST=array(); $query="SELECT * FROM $table"; $res=mysql_query($query); while($row=mysql_fetch_assoc($res)) $LIST[]=$row; include 'list.php'; } else { // form displaying part: if ($id=intval($_GET['id'])) { $query="SELECT * FROM $table WHERE id=$id"; $res=mysql_query($query); $row=mysql_fetch_assoc($res); foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v); } else { $row['name']=''; $row['id']=0; } include 'form.php'; } ?> templates: form.php <? include TPL_TOP ?> <form method="POST"> <input type="text" name="name" value="<?=$row['name']?>"><br> <input type="hidden" name="id" value="<?=$row['id']?>"> <input type="submit"><br> <a href="?">Return to the list</a> </form> <? include TPL_BOTTOM ?> and list.php: <? include TPL_TOP ?> <a href="?id=0">Add item</a> <? foreach ($LIST as $row): ?> <li><a href="?id=<?=$row['id']?>"><?=$row['name']?></a> <? endforeach ?> <? include TPL_BOTTOM ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7600733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set a UIWebView's base URL I have a UIWebView where relative links fail to load properly, because the view was loaded from a data object after the html data has been locally manipulated, not direct from a URL. Now all the relative links on the page fail, because the UIWebView doesn't know what they're relative to. For example: <IMG SRC="img/foo.jpg"> wouldn't load because rather than looking to http://theoriginalsite.com/img/foo.jpg for the file, the UIWebView looks in iphonefilesystem/thisapp/tempdir/img/foo.jpg Is there a way to reset the UIWebView's base URL, so that these links will work? Am I stuck with adding another pass to the html data manipulation to rewrite all the relative URLs within? A: That's exactly what the baseURL parameter in the following UIWebView methods is for: - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL Have a look at the documentation here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Logical && operator Having an unpredicted outcome using the && logical operator. If I link more than 2 expressions, the if clause fails. Is there some limit to the number of expressions that can be concatenated using &&? if (tTellerProN.checked && tCareProN.checked && tSalesProN.checked) { $(flListEmpty).empty(); $(flListEmpty).append($('<option></option>').val(0).html("Select Role")); $('.fl_list1 .list4').each(function (index) { $(flListEmpty).append($('<option> </option>').val(index).html($(this).text())); }) } A: && is not a jQuery operator, it is Javascript. jQuery is a library that builds on Javascript. I'm not sure what the ** is in your IF statment but this code works: var x = true; var y = true; var z = true; alert(x && y && z); // true alert(x && y && !z); // false I would alert the values of your 3 .checked parameters and make sure they are being set as you expected. A: No, there is no limit. Your expression requires that all three checked values are true, otherwise it will return false. One of them must be false (or not true), that's why your if is failing. For the record: && is part of the javascript language, not the jQuery library. A: No, there is no limit. However looking at your code (what little there is of it and with such descriptive variable names used), I would venture a guess that you actually mean ||, not &&. A: i made a test case here with both && and ||: http://jsfiddle.net/VcmCM/
{ "language": "en", "url": "https://stackoverflow.com/questions/7600755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF Service Config File? Can someone please help with how I configure my WCF service. The environment is IIS6 and the service can only be accessed via https (the firewall only allows connections to the server on port 443). So, when I access https://myservice.com/Service.svc it gives me the URL of the WSDL file, which is the correct https address (I got this working by enabled httpsget, i think, there has been a lot of guess work!) However, if I then consume the service, the end point address is http://localservername/Service.svc. I assume I need to configure my web.config file to return the correct soap address, but having googled and read so many posts about endpoints, binding and behaviours, I am confused. Can someone please clear this up for me, how do I configure my service to allow https connection and get the correct SOAP address? Cheers Chris A: Does this help? http://weblogs.asp.net/srkirkland/archive/2008/02/20/wcf-bindings-needed-for-https.aspx Quote the Note: "Just one note: after 3 hours we realized that webHttpBinding is not suitable for regular SOAP-based clients (one has to watch these bindings :) We switched webHttpBinding to basicHttpBinding and our SOAP-based clients were able to parse the generated WSDL and to consume the web service."
{ "language": "en", "url": "https://stackoverflow.com/questions/7600756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TabView missing in MFMailComposeViewController I am using MFMailComposeViewController to send emails, and the screen looks like this I have a TabViewController in my view, so now when the MFMailComposeViewController pops out the TabView cann't be seen. What should i do to get the TabView bottom of the screen. A: You cannot change the default behavior of MFMailComposeViewController. It normally comes in full screen mode only and you cannot set any frame for that. Ideally it is always presented as a model view controller which covers everything which is on the screen. A: The mail composer interface is not customizable. See the MFMailComposeViewController class reference. You can try to change the frame size, but it will be ignored.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: does python's urllib2 do connection pooling? Really what I'm wondering: is python's urllib2 more like java's HttpUrlConnection, or more like apache's HttpClient? And, ultimately I'm wondering if urllib2 scales when used in a http server, or if there is some alternate library that is used when performance is an issue (as is the case in the java world). To expand on my question a bit: Java's HttpUrlConnection internally holds one connection open per host, and does pipelining. So if you do the following concurrently across threads it won't perform well: HttpUrlConnection cxn = new Url('www.google.com').openConnection(); InputStream is = cxn.getInputStream(); By comparison, apache's HttpClient can be initialized with a connection pool, like this: // this instance can be a singleton and shared across threads safely: HttpClient client = new HttpClient(); MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams p = new HttpConnectionManagerParams(); p.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION,20); p.setMaxTotalConnections(100); p.setConnectionTimeout(100); p.setSoTimeout(250); cm.setParams(p); client.setHttpConnectionManager(cm); The important part in the example above being that the number of total connections and the per-host connections are configurable. In a comment urllib3 was mentioned, but I can't tell from reading the docs if it allows a per-host max to be set. A: As of Python 2.7.14rc1, No. For urllib, urlopen() eventually calls httplib.HTTP, which creates a new instance of HTTPConnection. HTTPConnection is tied to a socket and has methods for opening and closing it. For urllib2, HTTPHandler does something similar and creates a new instance of HTTPConnection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there pure virtual functions in PHP like with C++ I would have thought lots of people would have wondered whether this is possible but I can't find any duplicate questions... do correct me. I just want to know whether PHP offers pure virtual functions. I want the following class Parent { // no implementation given public function foo() { // nothing } } class Child extends Parent { public function foo() { // implementation of foo goes here } } Thanks very much. A: Declare the method as abstract in the Parent class: abstract public function foo(); A: There are abstract classes! abstract class Parent { // no implementation given abstract public function foo(); } } class Child extends Parent { public function foo() { // implementation of foo goes here } } A: You can create abstract functions, but you need to declare the parent class as abstract, too: abstract class Parent { // no implementation given abstract public function foo(); } class Child extends Parent { public function foo() { // implementation of foo goes here } } A: Yes, that type of solution is possible, it's called polymorphism, you can do it without declaring an abstract class or an interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: ThreadPool not starting new Thread instantly I have a C# Windows Service that starts up various objects (Class libraries). Each of these objects has its own "processing" logic that start up multiple long running processing threads by using the ThreadPool. I have one example, just like this: System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(WorkerThread_Processing)); This works great. My app works with no issues, and my threads work well. Now, for regression testing, I am starting those same objects up, but from a C# Console app rather than a Windows Service. It calls the same exact code (because it is invoking the same objects), however the WorkerThread_Processing method delays for up to 20 seconds before starting. I have gone in and switched from the ThreadPool to a Thread, and the issue goes away. What could be happening here? I know that I am not over the MaxThreads count (I am starting 20 threads max). A: The thread pool's maximum number of threads value is the maximum number that it can create. It is not the maximum number that are already created. The thread pool has logic that prevents it from spinning up a whole bunch of threads instantly. If you call ThreadPool.QueueUserWorkItem 10 times in quick succession, the thread pool will not create 10 threads immediately. It will start a thread, delay, start another, etc. I seem to recall that the delay was 500 milliseconds, but I can't find the documentation to verify that. Here it is: The Managed Thread Pool: The thread pool has a built-in delay (half a second in the .NET Framework version 2.0) before starting new idle threads. If your application periodically starts many tasks in a short time, a small increase in the number of idle threads can produce a significant increase in throughput. Setting the number of idle threads too high consumes system resources needlessly. You can control the number of idle threads maintained by the thread pool by using the GetMinThreads and SetMinThreads Note that this quote is taken from the .NET 3.5 version of the documentation. The .NET 4.0 version does not mention a delay. A: The ThreadPool is specifically not intended for long-running items (more specifically, you aren't even necessarily starting up new threads when you use the ThreadPool, as its purpose is to spread the tasks over a limited number of threads). If your task is long running, you should either break it up into logical sections that are put on the ThreadPool (or use the new Task framework), or spin up your own Thread object. As to why you're experiencing the delay, the MSDN Documentation for the ThreadPool class says the following: As part of its thread management strategy, the thread pool delays before creating threads. Therefore, when a number of tasks are queued in a short period of time, there can be a significant delay before all the tasks are started. You only know that the ThreadPool hasn't reached its maximum thread count, not how many threads (if any) it actually has sitting idle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Which browsers allow popups on which events Could we list how each of the major browsers support popups (i.e. open a new window, target="_blank", etc.) For ex: most allow popups on the click event A: The basic rule of thumb is that popups are allowed ONLY in response to user-triggered events, of which click is the big one. Anything else gets blocked. Most browsers will further restrict things such that onmouseover would not trigger a popup, even though it's a user generated event. Basically, if the root cause of an event is NOT a physical click by the user, then it's blocked. This includes trying to do things like $('#spam_me_to_death').click(), as the click was not initiated by the user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Programmatically convert (save) files (i.e. docx, xlsx, txt) to XPS by sending them to the “Microsoft XPS Document Writer” printer Using C# 3.5, I’m trying to programmatically create XPS files by sending them to the “Microsoft XPS Document Writer” printer. I’m able to set the print queue, but I’m unable to add a job to the print queue using the PrintQueue.AddJob() because it’s expecting a XPS file. I’ve also tried setting the PrintSystemInfo JobStream to a byte array to no avail. Basically I want to mimic what a user does manually when printing to the “Microsoft XPS Document Writer”: 1. Select “Microsoft XPS Document Writer” from the list of printers. 2. Specify the new XPS file name. 3. Print it (which saves it as a .xps file) I would think with the System.Printing and System.Windows.Xps namespaces there would be an easy way to do this. I’ve spent lots of time researching this and have seen other people trying to accomplish the same task, but no was able to provide an elegant solution. Any insight would be much appreciated. Thanks. A: What you should be seeking for is how to ask applications, that know how to read this files, to print them. I mean, Excel can render xslt, so you should ask Excel to print it to XPS writer (via COM maybe). System.Windows.Xps namespace can help if you know how to read & render a document - then you make corresponding calls to XpsDocuments methods similar to this https://stackoverflow.com/a/352551/332528, rendering your document to xps and then printing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript not clearing box in IE Internet Explorer, the bane of my development life, refusing again to do what other browsers seem to do effortlessly. I am trying to clear the browse code/value if the user selects a file type that isn't allowed. Works in FF but not IE 9. Thanks <script type="text/javascript"> <!-- extArray = new Array(".jpg", ".png"); function LimitAttach(form, file) { allowSubmit = false; if (!file) return; while (file.indexOf("\\") != -1) file = file.slice(file.indexOf("\\") + 1); ext = file.slice(file.indexOf(".")).toLowerCase(); for (var i = 0; i < extArray.length; i++) { if (extArray[i] == ext) { allowSubmit = true; break; } } if (allowSubmit) { return true; } else { alert("Please only upload files that end in types: " + (extArray.join(" ")) + "\nPlease select a new " + "file to upload and submit again."); document.getElementById('photobrowser').value = ""; return false; } } --> </script> <form action="process.php" method="POST" enctype="multipart/form-data" name="formUpload"> <label>Picture:</label> <input type="file" name="photo" id="photobrowser" onchange="return LimitAttach(formUpload, formUpload.photo.value)" tabindex="4"> <input type="hidden" name="subphoto" value="<?php echo $newCount ?>" /> <input type="image" src="styling/images/button-add-photo.png" id="subBtn" tabindex="6" /> </form A: Browsers differ greatly on their restrictions with file inputs. File inputs allow the user to interact with and select files within their file system. So all browsers restrict JS from selecting files automatically. IE goes further to disallow changing the input select at all, even to a blank string. This actually makes sense since, if you are not allowing the selection of a given file, why should you be allowed to change it at all? And, rather than validating it in JS you should be validating the files on the backend. Frontend validation is okay for ease of use, but even when it is in place there should always be backend validation. Users can simply turn off JS, use something like firebug to alter it or even (sometimes) download the file to their local machine, change it, then use it to submit to your site. A: Have you tried passing this into the JS method, instead of finding it by the ID?: onchange="return LimitAttach(this, this.value);" JavaScript: function LimitAttach(input, file) { allowSubmit = false; if (!file) return; while (file.indexOf("\\") != -1) file = file.slice(file.indexOf("\\") + 1); ext = file.slice(file.indexOf(".")).toLowerCase(); for (var i = 0; i < extArray.length; i++) { if (extArray[i] == ext) { allowSubmit = true; break; } } if (allowSubmit) { return true; } else { alert("Please only upload files that end in types: " + (extArray.join(" ")) + "\nPlease select a new " + "file to upload and submit again."); input.value = ""; return false; } } EDIT This is kind of a hack, but you might want to give it a shot: function checkImg(val){ var dgr = val.value; dgr = dgr.substr(dgr.length-4, dgr.length) dgr = dgr.toLowerCase(); if (dgr =='.jpg' || dgr == 'jpeg' || dgr== '.gif'){ alert('image'); }else{ alert('not image'); var objD = document.forms['form1'].divR; objD.innerHTML = ''; objD.innerHTML = '<input id="uImg" name="uImg" type="file" class="defText" style="font-size: 10pt" onchange="javascript: checkImg(this);" size="30">'; } } <form name="form1" id="form1" method="post"> <div id="divR" name="divR"> <input id="uImg" name="uImg" type="file" class="defText" style="font-size: 10pt" onchange="javascript: checkImg(this);" size="30"> </div> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7600802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mount WebDAV share on Windows programmatically and show login dialog only if required I need to mount WebDAV share programmatically on Windows. I do not know the user credentials, each user has its own login/password. Some servers allow anonymous access. How do I mount WebDAV and present login dialog only if requested by server? I need exactly the same behavior as Add Network Location Wizard. Are there any chance to call the same Windows API Add Network Location is using?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Full Oracle 10g XE Database Can't Be Exported? The simple version of this question is: Is it possible to export all the data from an Oracle 10g XE database that has reached it's 4GB maximum size limit? Now, here's the background: My (Windows) Oracle 10g XE database has reached its maximum allowed database size of 4GB. The solution I intended to implement to this problem was to upgrade to Oracle 11g XE which has a larger maximum size limit, and better reflects our production environment anyway. Of course, in typical Oracle fashion, they do not have an upgrade-in-place option (at least not that I could find for XE). So I decided to follow the instructions in the "Importing and Exporting Data between 10.2 XE and 11.2 XE" section of the Oracle 11g XE Installation Guide. After fighting with SQLPlus for a while, I eventually reached step 3d of the instructions which instructs the user to enter the following (it doesn't specify the command-line rather than SQLPlus, but it means the command-line): expdp system/system_password full=Y EXCLUDE=SCHEMA:\"LIKE \'APEX_%\'\",SCHEMA:\"LIKE \'FLOWS_%\'\" directory=DUMP_DIR dumpfile=DB10G.dmp logfile=expdpDB10G.log That command results in the following output: Export: Release 10.2.0.1.0 - Production on Thursday, 29 September, 2011 10:19:11 Copyright (c) 2003, 2005, Oracle. All rights reserved. Connected to: Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production ORA-31626: job does not exist ORA-31633: unable to create master table "SYSTEM.SYS_EXPORT_FULL_06" ORA-06512: at "SYS.DBMS_SYS_ERROR", line 95 ORA-06512: at "SYS.KUPV$FT", line 863 ORA-12952: The request exceeds the maximum allowed database size of 4 GB I have deleted quite a bit of data from the USERS tablespace, but am unable to resize it because of the physical locations of the data. And no matter what I do, I always get that same output. I have tried running "Compact Storage" from the admin web application with no effect. So my question is, am I missing something? Or is Oracle really so incompetent as to leave people completely out of luck if their XE databases fill up? A: You can get to the point you need to export data, sounds like you just need some help coalescing the data so you can reduce the USERS tablespace size and increase the SYSTEM tablespace size to get past your issue. You mentioned that you removed data from the USERS tablespace but can't resize. Since you can't reduce the tablespace size smaller than the highest block, reorganiza your table data by executing the following command for each table: ALTER TABLE <table_name> MOVE <tablespace_name>; The tablespace name can be the same tablespace that the table currently lives in, it will still reorganize the data and coalesce the data. This statement will give you the text for this command for all the tables that live in USERS tablespace: select 'ALTER TABLE '||OWNER||'.'||TABLE_NAME||' MOVE '||TABLESPACE_NAME||';' From dba_tables where tablespace_name='USERS'; Indexes will also have to be rebuilt (ALTER INDEX REBUILD;) as the MOVE command invalidates them because it changes physical organization of the table data (blocks) instead of relocating row by row. After the data is coalesced you can resize the USERS tablespace to reflect the data size. Is it a pain? Yes. Is Oracle user friendly? They would love you to think so but its really not, especially when you hit some weird corner case that keeps you from doing the types of things you want to do. A: As you can see, you need some free space in the SYSTEM tablespace in order to export, and Oracle XE refuses to allocate it because the sum of SYSTEM+USERS has reached 4 Gb. I would try to install an Oracle 10gR2 Standard Edition instance on a similar architecture, then shutdown Oracle XE and make a copy your existing USERS data file. Using "ALTER TABLESPACE" commands on the standard edition, you should be able to link the USERS tablespace to your existing data file, then export the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql update a table How can I update a table and create column with the id numbers for each entry in that ID column? The table currently looks like: city ------------- New York Los Angeles London Belgrade I need the column in this table that would have the ID number of each city which would be ordered by column city ASC. Something like: id | city ---------------- 1 | Belgrade 2 | London 3 | Los Angeles 4 | New York Can I do this using mysql query or I need to do that using PHP and Mysql? A: ALTER TABLE table_name ADD column_name column-definition; so in your case its ALTER TABLE cities ADD id int auto-increment; A: You'd be wanting to retrospectively add an identity column with auto-increment enabled to this table. The query would look something like this: ALTER TABLE city ADD id INT NOT NULL AUTO_INCREMENT KEY However I'm not sure if that's going to go back and fill in all the Id's for you, you might need to write a proc or another simple query to fill them in, but this will give you the column with the functionality you want going forward. A: In case the table isn't sorted by city name at the moment, the easiest way is to create a new table, then drop the old one and rename. CREATE TABLE new ( id INT NOT NULL AUTO_INCREMENT, city VARCHAR(255) NOT NULL); INSERT INTO new (city) SELECT city FROM old_table ORDER BY city; DROP TABLE old_table; RENAME TABLE new TO old_table;
{ "language": "en", "url": "https://stackoverflow.com/questions/7600810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which method is used to terminate the execution of Java program in between? We used functions like exit() in C++ to abnormally terminate the execution of program, which function can we use in Java. For ex :- In following program I want to terminate the execution as soon the value of i is printed for 1st time. //following is the program : class Lcm { public static void main( String args[] ) { int a = Integer.parseInt( args[0] ); int b = Integer.parseInt( args[1] ); for ( int i=1 ; i<=a*b ; i++ ) { if ( i%a==0 && i%b==0 ) { System.out.println( "lcm is: " + i ); /* i want to terminate the program * when the value of i is printed * for very 1st time */ } } } } } A: You can do it like this: System.exit(0); A: Use break to get out of the loop and let the function end naturally, or a plain return to exit the function altogether. Perhaps it is finally time to learn to control your flow without goto statements and their equivalents (exit, longjmp, try..catch used for flow control etc). A: This is a good way to end the application in Java: System.exit(0); Example: if (num1 == num2) { System.exit(0); } A: System.exit(0) or Runtime.getRuntime().exit(0) A: The System.exit(int status) method has this purpose. A: Please explore System.exit(). http://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html Exit of the control flow from main thread also implies the completion of a program and is normally used. A: In C, C++ and Java the program terminates when the main/Main function/method returns. The difference is that in inJava the return type Main is void. On normal termination it always returns success. To indicate an abnormal termination and return a non-zero exit code, use System.exit. A: In your specific case you could simply escape the loop by using break, which would look like the following: for ( int i = 1 ; i <= a*b ; i++ ) { if ( i%a == 0 && i%b == 0 ) { System.out.println( "lcm is: " + i ); break; } } Because there's no code following, but you can also, as other mentioned before, use the System.exit(0) command for actually terminating your program. Another possible way is to change your code a bit and put the if-statement directly in our loop-termination. This way could look like this: int i = 0; while (++i < a*b && !(i % a == 0 && i % b == 0)); System.out.println(j); which is a bit more difficult to read, but you don't need a additional command to end your program. The semicolon behind the ´while-condition´ simply says that while the loop is running, nothing should be done. In that case your loop simply counts up your variable. For a better readability you could also put the counting of ´i´ in the body of the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to show a error when a modal popup extender is active I have a ModalPopupExtender to create new users. When the user enters the new user details and tries to enter the same email Id which is already registered then I want to show a error. Create user: if (emailcount != 0) { Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"User already exists!\");", true); } I check whether the email is already used, if it is used I want to pop up the error but the page stays still with the ModalPopupExtender on the top. I am not able to do anything after that. How can I display the error? A: I would use a different approach for this. In your modal popup extender, try something like this: <asp:UpdatePanel ID="pnlUserDetails" runat="server"> <ContentTemplate> <asp:TextBox ID="txtEmail" runat="server" OnTextChanged="txtEmail_OnTextChanged" AutoPostBack="true"></asp:TextBox> <asp:Label ID="lblEmailMessage" runat="server" Text="Already exists!" Visible="false" /> </ContentTemplate> </asp:UpdatePanel> In the code-behind: protected void txtEmail_TextChanged(object sender, EventArgs e) { //check for matching email address and show label if match is found lblEmailMessage.Visible = FindMatchingEmailAddress(txtEmail.Text.Trim()); //clear the email input if a match is found?? txtEmail.Text = String.Empty; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does view.startAnimation(animation) not work when called from an event? I have created a custom view which uses an dummy TranslateAnimation to setup some layout properties. I use the Interpolator to calculate height, and apply it to a view inside the applyTransformation() method of the TranslateAnimation. This is working quite well, if i trigger the animation from my Activity. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.i("test", "onCreate()"); view.expand(); // This method starts the animation } When I try to do the same using a touch event, nothing happens. @Override // This method is touch handler of the View itself public boolean onTouch(View v, MotionEvent event) { Log.i("test", "onTouch()"); this.expand(); // onTouch is part of the view itself and calls expand() directly return true; } My expand method looks like this: public void expand() { Log.i("test", "Expand!"); TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 0) { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { Log.i("test", "applyTransformation()"); super.applyTransformation(interpolatedTime, t); // do something } }; anim.setDuration(500); anim.setInterpolator(new AccelerateDecelerateInterpolator()); this.someInternalView.startAnimation(anim); } Once my activity is created Logcat shows "onCreate()" Inside my touch event Logcat shows "onTouch()" Inside the expand() method Logcat shows "Expand!" - either called from the activity or from an event. Inside the method applyTransformation() Logcat shows "applyTransformation()" - BUT! only if expand() is called from the onCreate(). Any attempt in trying to start the animation from an event failed. This looks to me like some sort of threading problem. Could this be? Is there anything I am missing? As far as I see from other posts, starting animations from events should work without any problems... Thanks in advance! A: try this: public void expand() { Log.i("test", "Expand!"); runOnUiThread(new Runnable() { @Override public void run() { TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 0) { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { Log.i("test", "applyTransformation()"); super.applyTransformation(interpolatedTime, t); // do something } }; anim.setDuration(500); anim.setInterpolator(new AccelerateDecelerateInterpolator()); this.someInternalView.startAnimation(anim); } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: php not able to execute system commands For some reason, the following php script when called via apache, is not returning results... is there a system security setting in php.ini somewhere to allow system commands? <div style="background:#000;color:#fff"> <?php $cmd = "/bin/date"; $output = system($cmd); printf("System Output: $output\n"); exec($cmd, $results); printf("Exec Output: {$results[0]}\n"); echo"<pre>"; echo system('/bin/ls'); echo"</pre>"; ?> </div> A: Your host (or configuration) is probably restricting system() or exec() command. Check your configuration or contact your host ; This directive allows you to disable certain functions for security reasons. ; It receives a comma-delimited list of function names. This directive is ; *NOT* affected by whether Safe Mode is turned On or Off. ; http://php.net/disable-functions disable_functions = should be blank, works on my machine http://sandbox.phpcode.eu/g/e47f7 Also, check that SElinux and Suhoshin is configured properly A: plesk safe mode... disabled in httpd.include... sigh... love it when systems land in your lap
{ "language": "en", "url": "https://stackoverflow.com/questions/7600815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to submit unchecked checkbox also If checkbox is not checked, clicking on form submit button does not submit any data. Some checkboxes may be not present in form depending on form fields selected by user. So submit controller has no possibility to determine if the unchecked checkbox was present in form or not. If database contains true for this column, this property is not updated to false. Checkbox name is same as database boolean column name. How to to force form to submit checkboxes which are in unchecked state or any other idea to set value in database to false if checkbox is not checked but not to change value in database if checkbox is not present in form ? jquery, jqueryui, asp.net 2 mvc are used A: This is a very common problem - when checkbox isn't selected it wont send to server value off/ false by itself. Most popular answer that I found was to add hidden field with the same name as checkbox and value = false. But then when someone checked it it sent me two values. And I didn't like it. This is what I did: Somewhere in HTML: <input type="checkbox" name="${name}" onclick="true" > In JQuery: First step is to set hidden values on all checkboxes that aren't checked. $(document).ready(function () { $(".checkbox").each(function () { if ($(this).prop("checked") == undefined) { $(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value="off">") } } ) }); Secondly we have to react on user clicking the check-box: while unselecting add hidden field, when selecting - remove next sibling in DOM - we expected hidden field there. WARNING: when check-boxes have common parent you should check if next sibling's type is hidden and then remove it!: $(".checkbox").click(function () { if ($(this).prop("checked") == undefined) { $(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value=off>") } else { $(this).next().remove(); } } ); And it works for me :) A: My shortest solution: use a checkbox's onchange() event to set a hidden sibling to 0 or 1. As follows: var htm = '<input type="checkbox" '+(isMale>0?"checked":"")+' onchange="this.nextSibling.value=this.checked==true?1:0;" /><input type="hidden" name="Gender" value="'+isMale+'" />'; Submit ONLY sends the hidden sibling, NOT the checkbox because it has no name attribute. So the above is serialized as "...&Gender=1..." or "...&Gender=0..." depending on isMale value. A: I found myself in this issue recently, and this is my solution. I do it without hidden field. Just change the 'value' of the checkbox to 'off', and make sure it is checked so it is sent. Note: I have only tested against a php server, but it should work. // Prepare checkboxes var checkboxes = document.querySelectorAll('input[type="checkbox"]') checkboxes.forEach(function(cbox) { if (!cbox.checked) { // If the checkbox is checked it keeps its value, default value is 'on' cbox.value='off' // Otherwise change the value to off, or something else cbox.checked = true // We need to check it, so it sends the value } }) A: This is a common issue with checkboxes in HTML forms and isn't unique to ASP.NET. The answer is to have a hidden field that accompanies each checkbox. When the checkbox is modified, use a client-side event to update the hidden field. The hidden field will always be submitted. However, since you're using ASP.NET MVC, if you use the HTML.CheckBoxFor helper, it will handle this for you automatically. A: I ran into a similar issue while using jQuery/Java - Instead of using an additional hidden field, I forced a submission each time the form was saved irrespective of whether fields were modified. e.g. If chkBox1 =unchecked (will send null - control value attribute via jQuery onClick or onChange event of checkbox) <input name="chkBox1 " class="editable-value" id="chkBox1 " style="display: inline;" type="checkbox" data-type="A" data-original-value="checked" data-force-save="true" value="N"/> and ChkBox2=checked (Will send Y) <input name="ChkBox2" class="editable-value" id="ChkBox2" type="checkbox" CHECKED="Y" data-type="A" data-original-value="checked" value="Y"> are the on screen values and I try to save the data,in my Java code I perform a null check on the value obtained in the getter and interpret a null as an 'N'. This avoids the overhead of a hidden field although one is free to choose the solution that addresses their particular situation. A: My form is created dynamically, so incorporating additional hidden fields would have been quite complicated. For me it works by temporarily altering the field type in a submit handler of the form. myForm.addEventHandler("submit", ev => { for (let oField of ev.target.elements) { if (oField.nodeName.toUpperCase() === "INPUT" && oField.type === "checkbox" && ! oField.checked) { oField.type = "text"; // input type text will be sent // After submitting, reset type to checkbox oReq.addEventListener("loadstart", () => { oField.type = "checkbox"; }); } } }); This feels a bit dirty, but works for my. A: I know this thread is old and pretty much dead but, I ran into this problem as well (yeah in 2021!). I had to remove the name attribute from the checkbox as my work around. In your razor page code: @model MyViewModel @Html.LabelFor(model => model.MyCheckbox) @Html.CheckBoxFor(model => model.MyCheckbox) ... ... ... @* script tag at bottom of razor page *@ <script> document.getElementById('MyCheckbox').removeAttribute('name'); document.getElementById('MyCheckbox').addEventListener('click', function() { // razor should create a hidden field with the name of the checkbox immediately // after the checkbox. this.nextSibling.value = this.checked; }); </script> The checkbox will no longer get validated or submitted because there is no name attribute but the hidden field (which has the same name the checkbox had) will. A: I know this is an old question, but maybe someone like a solution likes this: <form action="<your url>" method="get" onsubmit="return setupSearch();"> <input id="cache" name="cache" type="checkbox" style="display: none" /> <input id="archive" name="archive" type="checkbox" /> Javascript function: function setupSearch() { document.getElementById("cache").checked = !document.getElementById("archive").checked; return true; } As a result you get the following values in your query string: ?cache=on or just ?archive=on
{ "language": "en", "url": "https://stackoverflow.com/questions/7600817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Android app won't push from eclipse/adb to phone I have a rooted Samsung Galaxy S (Epic) with syndicate Rom Frozen 1.2 ROM. I've developing apps. When the ROM cooks made the ROM, I think that they left out some important things. I first had to fix "am" by added the shell to the top. Now when I try to run apps directly on my device from Eclipse/adb, they won't run. The last version of the ROM (1.1) ran just fine. So I think something else must have been screwed up when the cooks made 1.2. Any ideas on why the ROM doesnt get installed? What can I check for? How can I fix this? [2011-09-29 12:39:55 - Drag Racing Workbench] Automatic Target Mode: using device 'D7005af7xxxx' [2011-09-29 12:39:55 - Drag Racing Workbench] Uploading Drag Racing Workbench.apk onto device 'D7005af7xxxx' [2011-09-29 12:39:56 - Drag Racing Workbench] Installing Drag Racing Workbench.apk... [2011-09-29 12:39:56 - Drag Racing Workbench] Success! [2011-09-29 12:39:56 - Drag Racing Workbench] Starting activity com.motorcitysoftware.dragracingworkbench.startPage on device D7005af7xxxx [2011-09-29 12:39:56 - Drag Racing Workbench] New package not yet registered with the system. Waiting 3 seconds before next attempt. [2011-09-29 12:39:59 - Drag Racing Workbench] Starting activity com.motorcitysoftware.dragracingworkbench.startPage on device D7005af7xxxx [2011-09-29 12:40:00 - Drag Racing Workbench] New package not yet registered with the system. Waiting 3 seconds before next attempt. [2011-09-29 12:40:03 - Drag Racing Workbench] Starting activity com.motorcitysoftware.dragracingworkbench.startPage on device D7005af7xxxx [2011-09-29 12:40:03 - Drag Racing Workbench] New package not yet registered with the system. Waiting 3 seconds before next attempt. [2011-09-29 12:40:06 - Drag Racing Workbench] Starting activity com.motorcitysoftware.dragracingworkbench.startPage on device D7005af7xxxx [2011-09-29 12:40:07 - Drag Racing Workbench] New package not yet registered with the system. Waiting 3 seconds before next attempt. [2011-09-29 12:40:10 - Drag Racing Workbench] Starting activity com.motorcitysoftware.dragracingworkbench.startPage on device D7005af7xxxx [2011-09-29 12:40:10 - Drag Racing Workbench] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.motorcitysoftware.dragracingworkbench/.startPage } [2011-09-29 12:40:10 - Drag Racing Workbench] ActivityManager: Error type 3 [2011-09-29 12:40:10 - Drag Racing Workbench] ActivityManager: Error: Activity class {com.motorcitysoftware.dragracingworkbench/com.motorcitysoftware.dragracingworkbench.startPage} does not exist. A: /system/bin/pm and /system/bin/am are broken. They both need #!/system/bin/sh to add this manually, from a connected PC Run:adb shell Now you are shelled to the device. run busybox vi /system/bin/pm and insert the line. do the same for am.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reload Helper from Rails Console I'm calling helper methods from the Rails console in Rails 3 like this: >> helper.my_method(parameter) >> #=> some result However, if I change the helper method the changes are not reflected when I call the same method again. I have to exit and run rails console in order to see the changes to the helper method take effect. A: You just need to run reload! and most classes will be reloaded, including your helpers. A: Actually, helper is an instantiated object that memoizes the ApplicationController helpers, which will not be reloaded when you call reload!, at least in Rails 4. You can work around this by calling ApplicationController.helpers.my_method(parameter) in the console. You will still need to use reload! when you edit the helper, but it will reload unlike helper. A: After coming across this problem twice now and giving up, I figured out how to reload helpers without exiting the console and not calling them via ApplicationController.helpers.my_method(parameter). After calling reload!, include your helper again (include MyHelper) and it will include your recently changed helper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: WaitforElement timeout error? I am converting my coding to Junit4(webdriver) . When I run my code in Eclipse I get an error in the below code, for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if (isElementPresent(By.cssSelector("button.MB_focusable"))) break; } catch (Exception e) {} Thread.sleep(1000); } Can anyone tell me how to get rid of this? A: Try to call the isElementPresent method after creation of the DefaultSelenium object. While running the testcases in Eclipse and Selenium Rc we need the object on which object should be invoked. Try and let me know if run into any further issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: info in array comes out blank I seem to be having a problem and im a little lost on how I can proceed to fix it. Im trying to echo out some data from an array into another array, but the problem is without me using print_r or echo the info comes back blank, I dont know why it keeps doing that. This is what I have and I know it should work but it just isnt. <?php $number = 0; foreach($picture_info as $path => $picture_location){ ?> <?php $mymap = new Mappress_Map(array("width" => 490, "height" => 290)); $mypoi_1 = new Mappress_Poi(array("title" => "$picture_location->name", "body" => "$picture_location->city, $picture_location->state" ,"point" => array("lat" => "$picture_location->latitude", "lng" => "$picture_location->longitude"))); The problem is here where it says $picture_location->latitude and longitude as you can see this is a array and the infomation is in the array but the result comes out blank however if i use echo $picture_location->latitude or print_r it will shows the results however i cant do that inside of a array because its invalid coding $mymap->pois = array($mypoi_1); echo $mymap->display(array("directions"=>"none")); ?> <?php echo "<div class='search'>reviews for &nbsp;<strong>".urldecode($loc)."</strong> area</div>"; ?> <?php $number++; if($number == 1) break; ?> <?php } ?> I hope I am being descriptive about this and any help on what I can do is appreciated A: Nowhere in all that code do you actually assign anything to $loc, so you're ouputting an empty var. Major syntax problems with your code: 1 - You're jumping in and out of "php mode" frequently, for no good reason. There's no point in doing a ?> if you're just going to have a <?php on the next line. 2 - You're uselessly using " " quoted strings, just to pass in a variable. e.g. array("title" => "$picture_location->name" should just be: array("title" => $picture_location->name in other words: $x = "Hello" $y = "$x"; // useless use of double-quotes $y = $x; // proper usage
{ "language": "en", "url": "https://stackoverflow.com/questions/7600823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the size of longest sublist from a list in scheme I would like to get the size of the longest sublist from a list. for example (getlongest ((a) b (d e m n) (a d (c m g c y u m l d ) a) )) returns 9 since (c m g c y u m l d ) has size 9. I wrote this function (define getlongest (lambda (ls) (cond ((null? ls)0) (else (cond ((atom? (car ls)) (+ 1 (getlongest (cdr ls)))) (else (max (getlongest(car ls)) (getlongest(cdr ls))))))))) However if I write (getlongest ((a) (a (d d d e) m))) i get 5. Can anyone help me to fix this? Thanks A: So the problem with your code is that you're counting 1 length for the part of a list you've already counted, even if you go on to find that a sub-list of that list is actually the longest. For example, your code returns 5 for this case, too: (getlongest '(a (b (c (d (e)))))). Your approach is sort of hard to fix easily. You'll need to pass more data down when you recurse, I think; if each call to getlongest knew the current length, then you should be able to get the right maximum. If this isn't homework, here's how I would instinctively write the same function (not as efficient as possible, but simple:) (define (get-longest x) (cond ((null? x) 0) ((atom? x) 1) ; else take either the length of this list, or of the longest sub-list (else (apply max (length x) (map get-longest x)))))
{ "language": "en", "url": "https://stackoverflow.com/questions/7600826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: slow jquery performance I have about 200 small icons (4kb) on my web page on click on a menu i want the icons to dim out im using this function if (which!="all") { $(function () { // SET OPACITY TO 20% $("."+which).stop().animate({opacity: '0.2'}, 100); }); } for some reason the performance is very slow and it takes a long time for the icons to dim out How can i speed up the performance ? thanks A: You can animate opacity with CSS3. As long as that's an option within your requirements, I would advise looking into CSS3 for this kind of animation instead of JS. A: I would venture a guess and say that the poor performance is changing the DOM properties of 200 items a lot of times per second over and over (mouse over right?) You should consider a more DOM-friendly approach, like <canvas> and drawing your view manually. A: if you want to dim all the icons at once, you could try dimming the parent container instead of each individual icon. A: You should try using CSS sprites -- basically one large image "sliced" into 200 small pieces. Then you can create a second large image, exactly like the first, but dimmed out -- and use JavaScript/jQuery to swap one image for the other at every instance. If nothing else, this should improve your page load times considerably. A: You could try to cache the icon objects in an array and loop over them. Or use css to change opacity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to transfer dlls between projects I wrote a whole bunch of class libraries for silverlight. I want another programming group to use them, but not to see my code. What is the best way to distribute them so it is easy for them to use? I thought at first that it would be as simple as copying over the class library dll. What is confusing me now is how to deal with all the supporting dlls? Both supporting custom dlls made by me and system dlls that need to be included for my class libraries to function A: It is simply a case of supplying your library DLLs and of your own supporting DLLs but you should also supply a list of any 3rd party DLLs & system DLLs that they reference (so that the developers can add them explicitly to their main projects). Anything you miss will be listed as a link error so will be found/noticed quickly. The only extra thing I would suggest is use a commercial naming pattern for your DLL like: companyname.area.subsystem.version.dll
{ "language": "en", "url": "https://stackoverflow.com/questions/7600842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding embedded scripting to a PHP page I have a class like this: class Person { function __construct($name) { $this->name = $name; } function show() { echo $this->name; } } On my PHP page, I'd like to have a textbox that lets me either type in a custom-language script or a PHP script (without security vulnerabilities somehow) like : PHP Example: $me = new Person("Alexander"); $me->show(); And see output on the page with the result of the show() function. Obviously I don't want people writing malicious code. How is this done? I don't have any experience with this type of programming. Examples of problem domain: Interactive "learn php" website. User can type php in and see result without having to set up their own web server. "Program an attack script" game. User programs their fleet AI and watches the result of the battle against the computer AI. A: The simplest option is to run a sandboxed virtual server. You can also try the PHP sandbox, though it doesn't look to be sufficient. Ultimately, the safest approach would be to create your own interpreters that simply don't have capabilities that would let malicious scripts perform any damaging tasks (i.e. they have no affect in the real world), which is a topic that can fill books. The interpreter translates the code into a format that can be executed by a VM, which emulates whatever system features you want to support and provides sandboxed system calls (though the latter can also be provided by interpreter libraries you create). Basing the project on a VM allows you to support multiple languages without having to create an executor for each. Microsoft's CLI and VES provide an example of this. When it comes to books with more information, basically anything on compilers/interpreters and virtual machines is of primary relevance. For more on VMs, see also "Good literature about making a VM", "Simple Interpreted Language Design & Implementation".
{ "language": "en", "url": "https://stackoverflow.com/questions/7600844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: GWT-Platform Gatekeeper and Nested Presenters I would like to know some things about gwtp gatekeeper: * *if canReveal() method returns false, what happens? In my tests, i've been redirected to the defaultplace, i can change it? *having nested presenters, like: MenuPresenter - Only visible for admins. HomePresenter - Visible for admins and normal users. When the logged user is a normal user, i want to only "not display" the menu presenter, is that possible? thanks A: 1 - "if canReveal() method returns false, what happens? In my tests, i've been redirected to the defaultplace, i can change it?" From the GWTP wiki: "The presenter handling errors is the one revealed by your custom PlaceManager's revealErrorPlace method. If you do not override that method, then it's the one revealed by your revealDefaultPlace method." This is the default implementation of revealErrorPlace: public void revealErrorPlace(String invalidHistoryToken) { revealDefaultPlace(); } So you can override it in your custom PlaceManager and add more logic to it to redirect to any place you want. 2 - "When the logged user is a normal user, i want to only "not display" the menu presenter, is that possible?" You can hide the view in the presenter like this: @Override protected void onReset() { super.onReset(); if (!user.getAdmin) { getView().asWidget().setVisible(false); } } (for PopupPresenters you must override the onReveal() method) A: Uhm, I think we should update the documentation. You can also override revealUnauthorizedPlace, this will make sure you have a disctinc process for error handling and for security. By default, revealUnauthorizedPlace calls revealsErrorPlace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can the second and third operand of a ?: expression be statements? I get a syntax error with false ? {var x = 1;} : {var x = 2;} But when just use expressions for the last two operands, I don't run into any problems. Do I have to resort to conditionals? A: That type of thing is done with an IF statement. if (false) { x = 1; } else { x = 2; } To do so with your syntax: var x = false ? 1 : 2; A: To explicitly answer the question, no, the 2nd and 3rd operands must be expressions, and cannot be statements. Here's the MDN docs: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/Conditional_Operator Note the syntax: condition ? expr1 : expr2 Edit: just an interesting side-note is that since function calls are expressions and you can pass contexts around, you can kind of accomplish what you were trying to do. It's horrible. Don't do it. But you can... console.log(typeof x); // undefined false ? (function() { this.x = 1; }).call(this) : (function() { this.x = 2; }).call(this); console.log(typeof x); // number A: [Note: this is chock full of my personal bias] Just stop using the ternary operator, it is terrible and ridiculous. It never makes the code easier to read. Just use an if statement. If your target audience is a maintenance programmer, clarity is generally a desirable trait of code. var x; if (false) { x = 1; } else { x = 2; } [Bias to 11!] If you think the target audience of code is either a compiler or a browser, they you need to get your head in the game and stop programming like a goof-rocket. Humans maintain code not compilers and browsers. A: This is not going to work because var x is always going to be out of scope after this happens. You're not doing anything with it after you declare it, so any reference to it will break. You need to declare var x outside of this first: var x; false ? {x = 1;} : {x = 2;} Think of this in terms of writing out the if's (which is the same thing by the way) if (false) { var x = 1; } else { var x = 2; } // can't do anything with x here, because it doesn't exist A: This isn't valid syntax. Here's how you would do it: var x = false ? 1 : 2; And, you should not define the same variable in two places, which is bad practice. You may want to read up on variable hoisting. A: That's not how object notation works. Your syntax error is not the ternary operator, but your object notation. false ? {x: 1} : {x: 2} This works. A: The second and third parameters need to be wrapped in parenthesis, not curly braces to execute code within a conditional. Math.random() > .5 ? (console.log('1')) : (console.log('2'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7600856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can i use C++ vectors in C code in VS2008 i am running c code in vs2008. I was curious if i can mix this code with c++ code A: The short answer is yes. However, there are some nuances. C++ generally supports a large subset of C. It means that you can almost anything available in C (such as functions, libraries etc) from C++ code. From this point you have two options, an easy one and a bit harder. Option #1 - Use C++ compiler. Just have your code treated as C++. Simply put - use C++ compiler. Option #2 - Mix C and C++. You can write your C code and compile it with C++ compiler. Use C-like C++ where you need to use C++ components. For example, you may have a setup similar to the following: * *head1.h - declarations of your C functions. For example: void foo1(); *header2.h - declarations of your C functions that intend to use C++ code. #ifdef __cplusplus extern "C" { #endif void foo2 (); #ifdef __cplusplus } #endif And two source files, one C and one C++: * *source1.c #include "header1.h" #include "header2.h" void foo1 () { foo2 (); /* Call a C function that uses C++ stuff */ } *source2.cpp #include <vector> #include "header2.h" #ifdef __cplusplus extern "C" { #endif void foo2 () { std::vector<int> data; /// ... etc. } #ifdef __cplusplus } #endif Of course, you will have to compile "cpp" files with C++ compiler (but you can still compile "c" files with C compiler) and link your program with standard C++ runtime. The similar (but slightly more complicated) approach is used by Apple, for example. They mix C++ and Objective-C, calling the hybrid Objective-C++. UPDATE: If you opt for compiling C code as C++, I recommend you spend some time studying the differences between C and C++. There are cases when the code could be both legal C and C++, but produce different results. For example: extern int T; int main() { struct T { int a; int b; }; return sizeof(T) + sizeof('T'); } If it is a C program then the correct answer is 8. In case of C++ the answer is 9. I have explained this in more details in my blog post here. Hope it helps. Good Luck! A: If you are compiling your code using C++ compiler as a C++ program then you can use std::vector. If you are compiling your code using C compiler as a C program then you cannot. This is because std::vector is a type defined by the C++ Standard, C Standard does not define any type as std::vector. In simple words a C compiler does not understand what std::vector is. A: There is a switch to compile .c files as C++ (/TP) . If you enable this, you can use the c as C++. Beware that some c code will not compile as C++ without modification (mainly to do with type casting; c++ has stricter rules for this). A: If you are interfacing with some existing C library, then you of course can use C++. If you are compiling as C though, you won't be able to use any C++ features, such as std::vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android Fragment and getWindow() public class AircraftFragmentTab extends Fragment{ private String ac; public AircraftFragmentTab(String AC){ ac = AC; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View aircraftView = inflater.inflate(R.layout.acdetails, container, false); ??? getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); WebView wv = (WebView) aircraftView.findViewById(R.id.webac); wv.getSettings().setJavaScriptEnabled(true); wv.loadUrl("http://ABCD/ACInfo.aspx?AC=" + ac); return aircraftView; } } I am using a webView and class extends from Fragment. How can I use getWindow() here ? A: Example from Activity getWindow().setStatusBarColor(getResources().getColor(R.color.black)); Example from Fragment requireActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.black)); A: you can use getActivity().getWindow() this getActivity() will Return the Activity this fragment is currently associated with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: Getting Vim to recognize XML I would like Vim to help me indent my XML files like my C code. However, when I use gg=G It just sets everything to the left. Do I need to designate a syntax? Is XML recognized as a language? A: Yep, :set syntax=xml should work. In vim 7.3, this sets :set indentexpr=XmlIndentGet(v:lnum,1). If you've got a one-line file, you may need to :%s/\(<[^>]*>\)/\1\r/g, to insert newlines after every tag (or split it differently). Then, gg=G should work. A: Put filetype plugin indent on in your .vimrc to have Vim automatically identify .xml files as xml. You might need to put set nocompatible before that. If the file extension is not .xml, you can make Vim threat it like xml by using :set filetype=xml After you do that, Vim's autoindention (and syntax highlighting, and omnicomplete (that in xml just closes tags, but that's still something)) will work properly for xml. A: add this line to your .vimrc file: :map <Space>fx :%s/\ </\r</g<cr>:%s/\ android/\randroid/g<cr>:g/^$/d<cr>gg=G` to format click space fx
{ "language": "en", "url": "https://stackoverflow.com/questions/7600860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Manually fire Django 1.3's traceback/exception log I'm using djutils's async decorator, which has the nasty side effect of not sending traceback emails when an exception is raised, since it runs on a separate thread. It does, however, have the following place to put a logger. def worker_thread(): while 1: func, args, kwargs = queue.get() try: func(*args, **kwargs) except: pass # <-- log error here finally: queue.task_done() I've confirmed this will work, but even with the try/except removed, it won't trip Django's traceback logger. While it'd be pretty easy to tell it to write to a db/file on exception, I'd really like it to send a regular traceback as defined in settings. How can I do that? Edit: answer seems to involve django.utils.log.AdminEmailHandler - but I'm having a hard time finding an example. Edit 2: Here's my current (99% likely to be wrong) attempt. from django.utils.log import AdminEmailHandler def worker_thread(): while 1: func, args, kwargs = queue.get() try: func(*args, **kwargs) except: import logging from django.conf import settings print settings.EMAIL_HOST logger = logging.getLogger("async.logger") logger.exception("Async exploded") AdminEmailHandler pass # <-- log error here finally: queue.task_done() A: first, configure your logging settings i settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'myproject': { 'handlers': ['mail_admins'], 'level': 'INFO', 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } from now, all loggers which starts with 'myproject' should use AdminEmailHandler your code should look like this: import logging logger = logging.getLogger('myproject.optional.path') # example # logger = logging.getLogger('myprojects.myapp.views') def worker_thread(): while 1: func, args, kwargs = queue.get() try: func(*args, **kwargs) except: logger.exception("Async exploded") finally: queue.task_done()
{ "language": "en", "url": "https://stackoverflow.com/questions/7600861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Inode of directory on mounted share changes despite no change in modification time I am running Ubuntu 10.4 and am mounting a drive using cifs. The command I'm using is: 'sudo mount -t cifs -o workgroup="workgroup",username="username",noserverino,ro //"drive" "mount_dir"' (Obviously with "" values substituted for actual values) When I then run the command ls -i I get: 394070 Running it a second time I get: 12103522782806018 Is there any reason to expect the inode value to change? Running ls -i --full-time shows no change in modification time. A: noserverino tells your mount not to use server-generated inode numbers, and instead use client-generated temporary inode numbers, to make up for them. Try with serverino, if your server and the exported filesystem support inode numbers, they should be persistent. A: I found that using the option "nounix" before the "noserverino" kept the inodes small and persistent. I'm not really sure why this happened. The server is AIX and I'm running it from Ubuntu. Thank you for your response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to manage two different entities in SOLR? I have several different entities I want to index in SOLR, for example: * *users *products *blogs All are completely different in schema. All are searched for in different places in my app. Is there a way to do it in the same core? Is it the right approach? Is a core the conceptual equivalence of a table in a relational DB (In which case the answer is obvious). A: Really depends on how you will search this data. The main question is: What will you search for? If you will search for products (i.e. the search results are products), then design the schema around products. If you search for products by users or blogs, model users/blogs as dynamic/multivalued fields. If you have an app that searches for products, and another app that searches for blogs, and they're completely unrelated, put them in separate cores. From the Solr wiki: The more heterogeneous (different kinds of data) you have in one field or in one index, the less useful it is. So don't blindly put everything in a single core. Carefully consider what your search scenarios are. A: Here is some guidance from the Solr Wiki on Flattening Data into a Single Index. The key take away from flattening data is: This type of approach can be particularly well suited to situations where you need to "blend" results from conceptually distinct sets of documents. If you want to index your three types and keep them separate and distinct, you can leverage Cores within Solr to keep them fairly isolated, but allow you to manage them under one Solr container.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: For BlackBerry, how can my java program select a specific menu item in another BlackBerry program? How can I simulate a menu item selection for an exact menu item like for example, "New Note" ? A: If you want to create a new memo then simply use the Invoke class and supply it with a MemoArguments object. Note that you can do this for other core BB applications beyond the memo application. Invoke.invokeApplication(Invoke.APP_TYPE_MEMOPAD, new MemoArguments(MemoArguments.ARG_NEW)); If you want to actually click on a menu item in another application then you could try using the EventInjector class, although I don't know how well that will work for you. If it's a third party application that you want to control you probably won't have a lot of success.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework adding / deleting a new object Suppose I add a new object to an EntityCollection: myThingHolder.Things.Add(myThing); ... then later, using the same ObjectContext, before ever saving to the database, I do: myObjectContext.Things.DeleteObject(myThing); I get an exception: "The object cannot be deleted because it was not found in the ObjectStateManager." Other than doing myThingHolder.Things.Remove(myThing); is there another solution? I'd like to be able to independently delete the object--just like I can do if the object has been saved previously. EDIT I should note that this problem only occurs when myThingHolder is also new and has not yet been saved to the database. A: I think you need to attach the object to your context. Take a look at attach on MSDN for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: respond to key press javascript I'm sorry if this is basic, but I've searched and found nothing that works. I want to load a web page. When that page loads, it displays an image. I want to have the page automatically start listening for a right arrow key press. When that happens, a function in my script will change the image (that part I have gotten to work by using a button that reacts when clicked). It's the listening for and reacting to a key press I cannot get to work. Note that I'm using Safari, but I would like if possible for it to work in firefox or IE as well. Please help thanks. UPDATE TO RESPOND TO COMMENT: Here is what I tried, though I simplified the other part to make this shorter -- now it just writes a result to a div: <html> <head> <script language="Javascript"> function reactKey(evt) { if(evt.keyCode==40) { document.getElementById('output').innerHTML='it worked'; } } </script> </head> <body onLoad="document.onkeypress = reactKey();"> <div id="output"></div> </body> </html> A: If you are using jquery, you can do this: $(document).keydown(function(e){ if (e.keyCode == 39) { alert( "right arrow pressed" ); return false; } }); A: document.onkeydown= function(key){ reactKey(key); } function reactKey(evt) { if(evt.keyCode== 40) { alert('worked'); } } http://jsfiddle.net/dY9bT/1/ A: Easiest thing to do is use one of the many many many hotkey libraries, like https://github.com/jeresig/jquery.hotkeys or https://github.com/marquete/kibo. EDIT: try something like this (after you've already loaded Kibo's javascript). In your body statement, add the onload handler: <body onload="setuphandler">. Then add something like this (taken from the Kibo page): <script type="text/javascript"> var k = new Kibo(); function setuphandler() { k.down(['up', 'down'], function() { alert("Keypress"); console.log('up or down arrow key pressed'); }); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7600892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access vSphere 5, ESXi, Virtual Machine environment: processes, file system We have a vSphere 5 Hypervisor that runs few Windows XP/Vista/7 virtual machines with VMWare tools installed on each. Would like to be able to: * *power on a VM by its name *connect an ISO image from a local machine to a powered on VM *copy few files to a VM, to a specific folder (NANT and NUNIT binaries and dlls with tests) *run a just copied executable and wait till it completes *get a file from a TEMP folder, which path has to be determined by reading an Environment variable of a VM *determine whether or not a particular process is running inside VM I would like to use VmWare.Vim.dll which is a part of a VmWare Infrastructure (VI) toolkit. I code in C# and .NET 4. Power on/off operations I could do easily, but what about others? I have no clue how to do these operations. Haven't found anything in documentation. Perhaps there are other tools/API that could help me? Previously we used VixCOM and Vestris.VmWareLib wrapper, but we had a simple VMWare Workstation. Now we moved to a vSphere and these API don't work. Best Regards, Alex A: I am not a developer like yourself, do manage a VM envt. To do what you're looking to do is certainly possible with the API/SDK provided by VMware (http://www.vmware.com/support/developer/vc-sdk/index.html), but there may be an easier way. One way to do this would be with PowerCLi which is a snapin for PowerShell, which as you probably know, is based upon C# and can import its libraries. You could then do something like this and be well on your way: #start VM Start-VM -VM $vmName #mount ISO file Get-VM -Name $vmName | Get-CDDrive | Set-CDDrive -v -IsoPath <ISO-file-name> -Confirm:$false #copy files Copy-Item -Path $somePath -Destination $someDestination #invoke 'script' that will run .exe file (example exe below) $script = '"%programfiles%\Common Files\Microsoft Shared\MSInfo\msinfo32.exe" /report "%tmp%\inforeport"' Invoke-VMScript -ScriptText $script -VM VM -HostCredential $hostCredential -GuestCredential $guestCredential -ScriptType Bat #check for list of processes running $script2 = '"WMIC PROCESS get Caption,Commandline,Processid"' Invoke-VMScript -ScriptText $script2 -VM VM -HostCredential $hostCredential -GuestCredential $guestCredential -ScriptType Bat Hope this is of some help A: Look at vSphere Web Services SDK: GuestFileManager, GuestOperationsManager and GuestProcessManager (http://pubs.vmware.com/vsphere-50/index.jsp?topic=/com.vmware.wssdk.apiref.doc_50/vim.vm.guest.ProcessManager.html) A: We managed to create a NANT task that operates vSphere Virtual Machines. Thanks for tips guys!
{ "language": "en", "url": "https://stackoverflow.com/questions/7600893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: doubts about foursquare API My question is not about FourSquare API and its functions, but about more simpler details that are not well explained on Foursquare API explanations. Thank you very much in advance if someone wants to help me with this doubts: * *Foursquare API is a framework you can use to build applications for mobile devices, above of IOS and Android, so i can imagine that they have API for IOS (Objective-C) and Android (Java), right? *From API Doc: "Be sure to note that although API requests are against api.foursquare.com, OAuth token and authorization requests are against foursquare.com.". Does it mean that if i want to use FourSquare app, the users has to have an account on FourSquare? *From API Doc: "For example, if you write an iPhone application, every user who logs in with their foursquare account will be able to make up to 500 users/* requests and up to 500 venues/* requests, etc." I dont understand this sentence. Does it mean that for example, if you use an API method request like "checkins.add()", this method create two methods? one against api.foursquare.com to monitor the API limit requests, and another to your Web Application Server? *So as a question related to the third one, where do you have to store your database? is it stored on Foursquare cloud database because you are loggin there, or you have to create your own Web Service application with its own SQL database? *From API Doc: "All requests are simple GET or POST requests that return JSON or JSONP respones", so i can imagine that the Web Application Service should understand JSON. Well, my main question is, can i use Ruby on Rails to build the Web Application Service and Web Page frontend? I am seeing that there are some wrapps for RoR designed from third companies, but are not official and doesnt cover all the 2.0 API, just the ones they needed for their services. *If i want to create an app using FourSquare API, what do you advice me to use as a programming language/framework for the Web Service Application? the WSA that has to process the JSON requests and later store them on the database, interaction with users on the WebPage, etc. i am so sorry if my questions are so simple, but i dont have any other place of this level of expertise. thank you very very much in advance. A: * *The API is REST/JSON based, which means that any language that can do an HTTP request and parse a string can be used. There are Java and iOS libraries available. But you could use just about anything - curl with bash would be a bit extreme but if that floats your boat... *For some of the APIs (search a venue, for example) you do not necessarily need a FourSquar OAuth user token. For others (like checkin) a FourSquare token is required. For any API calls that require a userid, your users will have to be FourSquare users and "trust" your application with their FourSquare data. *Only requests to FourSquare is counted. So if you do a single call to checkins.add() it counts as one call for the user that is doing the checkin. I wouldn't worry about the limits. As long as you're usage of the API is sensible they will not be a problem. And if they do become a problem and you're doing something extraordinarily cool, the folks at FourSquare might be sympathetic. *You have to create your own web server with your own database to store some information. The OAuth token is one. You probably want to cache venue information here for short periods as well. *Yes, your webapp will need to be able to understand JSON. Ruby has excellent JSON support - look for the json gem. *It is really difficult to suggest a language or framework without knowing what it is that you're trying to do. I wouldn't choose a framework based on the fact that you want to use FourSquare (anything will do) but rather on your experience and the unique features of your application. You mentioned RoR before - that would definitely work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating File Download Links MVC3 Razor View with Model I am attempting to create links in my view so the end user can download the files in my model. In internet explorer I can right click and download from the link but I cannot left click (it does not open the file). Firefox gives me a message when I click the file that it does'nt know how to open this address, because the protocol (d) isn't associated with any program. Here is how I am creating the link. @{ foreach (var EpubFile in item.files) { if(File.Exists(System.Configuration.ConfigurationManager.AppSettings["UploadFileDirectory"] + EpubFile.FileReference)) { string link = System.Configuration.ConfigurationManager.AppSettings["UploadFileDirectory"] + EpubFile.FileReference; <a href="@link">@EpubFile.OriginalFileName</a> } } } A: Make sure the link is prefixed with http:// and is a full or partial path in URL form, not in filename form. E.g., c:\inetpub\wwwroot\foo\files\myfile.txt should be /files/myfile.txt. You can use Server.MapPath to obtain the relative path of a file under your web application root.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TestNG ERROR Cannot find class in classpath I'm trying to run testng via command line and I have following things in classpath: * *testng jar, jar of compiled test case file, and other required jars. *testng.xml points to appropriate class in the hierarchy. Testng doesn't run instead it throws: [TestNG] [ERROR] Cannot find class in classpath: (name of testcase file) I encountered the same issue before and I just added. In classpath and it solved the problem. But this time it did not seem to solve it. Any workarounds? A: Just do Eclipse> Project > Clean and then run the test cases again. It should work. What it does in background is, that it will call mvn eclipse:clean in your project directory which will delete your .project and .classpath files and you can also do a mvn eclipse:eclipse - this regenerates your .project and .classpath files. Thus adding the desired class in the classpath. A: add to pom: <build> <sourceDirectory>${basedir}/src</sourceDirectory> <testSourceDirectory>${basedir}/test</testSourceDirectory> (...) <plugins> (...) </plugins> </build> A: I just had this problem and I'm pretty confident that it's a bug in the TestNG Plugin for eclipse, since I was able to run my tests from the command line just fine. The fix that seems to be working for me and others is just to clean your project (Project → Clean). One person had to re-install the whole plugin. A: Before running the command for testng.xml file from command prompt, please check the following if you are missing them * *In the command prompt, make sure you are navigating to the folder where you have placed the testng.xml file. *after navigating to that, set CLASSPATH and include the testng jar file location, selenium-server jar file location(if you are working with selenium webdriver), bin folder location of your project which contains all the .class files of your project. e.g., set CLASSPATH=C:\Selenium\testng-5.8-jdk15.jar;C:\Selenium\selenium-server-standalone-2.31.0.jar;C:\SeleniumTests\YourProject\bin *Now run the command java org.testng.TestNG testng.xml. I was into the same situation but the above things worked for me. A: make sure your suite.xml should not have .java extension ex : <test name="Test C1"> <classes> <class name="com.taxi.suiteC.TestCase_C1" ></class> </classes> </test> A: in Intellij, what resolved the issue for me was to open the Maven right side toolbar choose "Clean" , "install" and hit the "Play" button: A: If your package name is FabFurnishPackage and your class name is registration then the code in xml should be <classes> <class name="FabFurnishPackage.registration"> </classes> [TestNG] [ERROR] Cannot find class in classpath: registration issue is fixed... A: I was facing the same issue and what I tried is as below. * *Clean the project (Right click on pom.xml and clean) *And update the maven project (Project > Maven > Update Maven Project) This solved the issue. A: In my case, the package structure was not proper, it was like folders and sub-folders. I deleted that project and imported again with changing the respective jre. After that it worked for me. e.g. Folder structure- TestProject -TestSuite1 Package Structure- TestProject.TestSuite1 A: This issue is coming due to some build error. 1. Clean Project - if issue not resolve 2. update maven project - If still not resolved 3. Go to build path from (right click on project- > properties -> java build path) now check library files. if you see an error then resolve it by adding missing file at given location. I face the same issue, after lots of approaches I found 3rd solution to get that issue fixed A: Please make sure that you have specified your class/package in TestNG.xml file. <test name="test1" preserve-order="false"> <classes> <class name="ABC"/> </classes> </test> A: right click on project -> go to maven -> update project this fixed my problem when nothing else could A: If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Clicking on the highlighted part expands and displays the complete class path. you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION java -cp "path_copied" org.testng.TestNG testng.xml If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12</version> <configuration> <suiteXmlFiles> <suiteXmlFile>config/testrun_config.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> A: I had to make a jar file from my test classes and add it to my class path. Previously I added my test class file to class path and then I got above error. So I created a jar and added to classpath. e.g java -cp "my_jars/*" org.testng.TestNG testing.xml A: Check the class hierarchy. If the package is missing in your class you'll get this error. So, try to create a new testing class by selecting the package. A: After changing the TestNG Output path(Project Properties-->TestNG-->Output Directory), its worked for me. A: I just had this problem and was because the skip test option in the run configuration was checked. made that unchecked and build, then run the testNg, worked. A: I was getting the same error - Cannot find class in classpath: Solution: I had committed following mistakes: * *My class was not under any package. so i created a package and then created my class under that package. *I had not mentioned full path in xml file. ex. . So i also corrected it. *Then i right click on xml file and run as TestNG my program executed successfully. A: i was facing same issue solution is , you need to check testng file,your class created under package in this case class is not found through Test NG. perform below steps just convert your project in to Test NG and over write/rplace with new testNG file. Again run this TestNG in this case it is working my case, A: If you have your project open in Eclipse(Mars) IDE: Right click on the project in eclipse Click on TestNG Click on "Convert to TestNG" This creates a new testng.xml file and prompts you to overwrite the existing one (!!!Warning, this will erase your previous testng.xml!!!). Click Yes. Run as Maven test build. A: I tried all suggestions above, and it did not work for my case. It turns out that my project build path has an error (one of the dependent jar cannot be found). After fixing that error, testng works again in my Eclipse. A: To avoid the error Cannot find class in classpath: (name of testcase file) you need to hold Runner class and Test class in one place. I mean src and test folders. A: I ran into the same issue. Whenever I ran my test, it kept saying classes not found in the classpath. I tried to fix the testng.xml file, clean up the project and pretty much everything the answers say here, but none worked. Finally I checked my referenced libraries in build path and there were 34 invalid libraries, turns out I had renamed one of the folders from the path that I had taken the jar files from. I fixed the path and the test ran successfully. So it might be fruitful to check if there are any errors in the referenced jar files before trying the other methods to fix this issue. A: I have faced the similar issue when I tried to execute my Testng.xml file. To fix you should move your class file from default pkg to some other pkg; ie create a new pkg and place your class file there A: When I converted my project with default pacage and a class named addition, to testng.xml. It got converted as: <classes> <class name=".addition"/> </classes> and was throwing error that class cannot be loaded. If I remove . before addition, the code works fine. So be careful with default package. A: I was also facing the same issue. I have tried to set the class path in different way and it works for me: set classpath="projectpath"\bin;"projectpath"\lib\* press Enter java org.testng.TestNG testng.xml press Enter again I hope this works! A: Eclipse ->Right Click on Project -> Build Path -> Configure -> Java Build Path. Add Library -> JRE lib. Add latest Java lib you are using in the system and remove other old JRE libs and save it. A: I got the same Problem while using maven The solution that worked is, the name of the class in testNG file was different then the actual class Name Since i changed the classname and testng file was not updated. So make sure className in testNG file should match with the actual className RestAssuredTest was mistaken written as RestAssuredest in testNG One of the reason for this problem <?xml version="1.0" encoding="UTF-8"?> <suite name="Suite"> <test name="Test"> <classes> <class name="com.mycompany.app.AppTest"/> <class name="com.mycompany.app.RestAssuredTest"/> <class name="com.mycompany.app.appiumTests"/> </classes> </test> <!-- Test --> </suite> <!-- Suite --> A: Was facing a similar issue using IntelliJ and in case it may be helpful to someone else what fixed it for me was to change the Use classpath of module field, to have it as the one that shows the package name. A: If you have renamed your testNG class and in the test suite xml file, its not renamed, you will get this error. I corrected in xml file also and it worked for me. A: Just problem with the class generating step. You can go to the project folder by explorer and delete classes. After that run "build" your project again. Now, your problem is fixed
{ "language": "en", "url": "https://stackoverflow.com/questions/7600898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Share not showing up in PROFILE_ID/feed, though realtime notification sent I have a realtime handler setup for an app, and it gets a notification of change in a user's feed (changed_fields': ['feed']) due to a Share of someone else's public Wall Photo. However, when I look at the https://graph.facebook.com/USER_ID/feed endpoint with a read_stream-authorized token, the change is not present. Is there another way to access this share?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery distinct array I have array textbox something like below <input type="text" name="txtname[]" value="single" /> <input type="text" name="txtname[]" value="twin" /> <input type="text" name="txtname[]" value="single" /> <input type="text" name="txtname[]" value="dulex" /> <input type="text" name="txtname[]" value="single" /> I wanna show those value to... single -------- 3 twin -------- 1 dulex -------- 1 A: var txtname = $(':input[name="txtname[]"]').map(function(a,b){ return $(b).val(); }).toArray(); var unique = {}; $.each(txtname, function(a,b){ if (!unique[b]) unique[b] = 0; unique[b]++; }); unique ended up with: ({single:3, twin:1, dulex:1}) UPDATE In case you want it as a jQuery add-on: $.fn.extend({ unique_count: function(){ var unique = {}; this.each(function(a,b){ var v = $(b).val(); if (!unique[v]) unique[v] = 0; unique[v]++; }); return unique; }, unique_vals: function(){ var unique = []; $.each($(this).unique_count(), function(a,b){ unique.push(a); }); return unique; } }); And the output being: var $inputs = $(':input[name="txtname[]"]'); $inputs.unique_count() // = Object: {single:3, twin:1, dulex:1} $inputs.unique_vals() // = Array: ["single", "twin", "duplex"] A: Check out the jquery unique function: http://api.jquery.com/jQuery.unique/ A: You can say this: var all = $(":text"); var uniqueNames = jQuery.unique(all.map(function(){return $(this).attr("value"); })); jQuery.each(uniqueNames, function(){ console.log(this + "---" + all.filter("[value=" + this + "]").length); }); The code is self descriptive: * *find unique values *count them in original array See example here: http://jsfiddle.net/BPxTd/
{ "language": "en", "url": "https://stackoverflow.com/questions/7600904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: clipping embedded svg content I have an html site where I've placed an SVG image inline within a table 'td' like this: `<td><svg id="mySVG" preserveAspectRatio="xMinYMin meet" viewBox="0 0 500 500" height="100%"><path d="M140.034,...</svg></td>` I've included zoom-in/zoom-out control buttons like this: <input type=button value="Zoom In" class="svgCtrl" onClick="zoomIn()"><br /> <input type=button value="Reset Zoom" class="svgCtrl" onClick="resetZoom()"><br /> <input type=button value="Zoom Out" class="svgCtrl" onClick="zoomOut()"><br /> And adjusting that zoom level with a js function: function zoomIn() { var mySVG = document.getElementById('mySVG'); var curHt = mySVG.getAttribute("height"); var newHt = parseFloat(curHt) + 10 + "%"; mySVG.setAttribute("height", newHt);} This works, but because I'm zooming the whole SVG, it overlaps everything else on the page when zoomed-in, and I'd like to keep the image within the confines of the 'td'. I tried wrapping the whole thing in a 'clip-path', but I must not have done it properly; the whole image disappeared. I'm sure this probably isn't the best way to achieve my goal. This is my first JS/SVG project, so any advice would be greatly appreciated. A: Have you tried setting a style of overflow:hidden on the containing TD?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between function with parentheses and without Possible Duplicate: Functions vs methods in Scala What is the difference between def foo = {} and def foo() = {} in Scala? In scala we can define def foo():Unit = println ("hello") or def foo:Unit = println ("hello") I know they are not the same but what is the difference, and which should be used when? If this has been answered before please point me to that link. A: A Scala 2.x method of 0-arity can be defined with or without parentheses (). This is used to signal the user that the method has some kind of side-effect (like printing out to std out or destroying data), as opposed to the one without, which can later be implemented as val. See Programming in Scala: Such parameterless methods are quite common in Scala. By contrast, methods defined with empty parentheses, such as def height(): Int, are called empty-paren methods. The recommended convention is to use a parameterless method whenever there are no parameters and the method accesses mutable state only by reading fields of the containing object (in particular, it does not change mutable state). This convention supports the uniform access principle [...] To summarize, it is encouraged style in Scala to define methods that take no parameters and have no side effects as parameterless methods, i.e., leaving off the empty parentheses. On the other hand, you should never define a method that has side-effects without parentheses, because then invocations of that method would look like a field selection. Terminology There are some confusing terminology around 0-arity methods, so I'll create a table here: Programming in Scala scala/scala jargon def foo: Int parameterless methods nullary method def foo(): Int empty-paren methods nilary method It might sound cool to say "nullary method", but often people say it wrong and the readers will also be confused, so I suggest sticking with parameterless vs empty-paren methods, unless you're on a pull request where people are already using the jargons. () is no longer optional in Scala 2.13 or 3.0 In The great () insert, Martin Odersky made change to Scala 3 to require () to call a method defined with (). This is documented in Scala 3 Migration Guide as: Auto-application is the syntax of calling a nullary method without passing an empty argument list. Note: Migration document gets the term wrong. It should read as: Auto-application is the syntax of calling a empty-paren (or "nilary") method without passing an empty argument list. Scala 2.13, followed Scala 3.x and deprecated the auto application of empty-paren methods in Eta-expand 0-arity method if expected type is Function0. A notable exception to this rule is Java-defined methods. We can continue to call Java methods such as toString without ().
{ "language": "en", "url": "https://stackoverflow.com/questions/7600910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }