text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Optional stdin in Python with argparse I found the very useful syntax
parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), default='-')
for specifying an input file or using stdin—both of which I want in my program. However, the input file is not always required. If I'm not using -i or redirecting input with one of
$ someprog | my_python_prog
$ my_python_prog < inputfile
I don't want my Python program to wait for input. I want it to just move along and use default values.
A: Use isatty to detect whether your program is in an interactive session or reading from a file:
if not sys.stdin.isatty(): # Not an interactive device.
# ... read from stdin
However, for the sake of consistency and reproducability, consider following the norm and reading from stdin if the filename is -. You may want to consider to let the fileinput module handle that.
A: Building on top of the answer regarding TTY detection, to answer the question explicitly:
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), default=(None if sys.stdin.isatty() else sys.stdin))
A: The standard library documentation for argparse suggests this solution to allow optional input/output files:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
... default=sys.stdin)
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
... default=sys.stdout)
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
>>> parser.parse_args([])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "79"
}
|
Q: Online Anti-Virus service How would it be possible to design an online-antivirus service. I was thinking about creating an online version of some open-source antivirus. Would it be possible to upload something like a binary image of the selected folders, and then pass that as an argument to the antivirus service installed on the web server?
A: Take a look at http://www.virustotal.com - this is how they do it. BTW - hashing previous results would probably save you a lot of time on scanning duplicate requests.
A: Sure. Be quicker to have them fedex their hard drive, though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android java stop a animation after completed How can i stop a animation after it has completed?
My animation is the image fades in
code:
Java:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView imageView= (ImageView)findViewById(R.id.tCat);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.anim);
imageView.startAnimation(fadeInAnimation );
xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="5000"
android:repeatCount="infinite"/>
</set>
A: Try removing the android:repeatCount="infinite", since you do not want it to repeat.
A: If it is a non repeating animation it will end when it is done otherwise you can just set the repeat counter to 0 to let it end after the current execution.
fadeInAnimation.setRepeatCount( 0 );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Optimal way to fill std::vector buffer This buffer should contain slots (three in this example) of equal length ( 20 in this example)
The buffer has to have contiguous memory so that it can be passed to a C function in non-const fashion.
const int slot_size = 20;
std::vector<char> vbuffer;
This function takes a string, copies to a temporary buffer of the required size then appeds it to vbuffer
void prepBuffer( const std::string& s)
{
std::vector<char> temp(slot_size);
std::copy(s.c_str(), s.c_str() + s.length() + 1, temp.begin());
vbuffer.insert(vbuffer.end(), temp.begin(), temp.end());
}
Testing the function
int main()
{
vbuffer.reserve(60);
prepBuffer( "Argentina");
prepBuffer( "Herzegovina");
prepBuffer( "Zambia");
cout << &vbuffer[0] << endl;
cout << &vbuffer[20] << endl;
cout << &vbuffer[40] << endl;
}
Question. There is a lot of string copying in my prepBuffer function. I am looking for a better way to fill up vbuffer with minimal copying
EDIT
The size of slots is determined elsewhere in the program. But it is not known at compile time.
EDIT
In line with my accepted answer below, I have settled on this version
void prepBuffer(const std::string& s)
{
assert(s.size() < slot_size );
vbuffer.insert(vbuffer.end(), s.begin(), s.end());
vbuffer.insert(vbuffer.end(), slot_size - s.size(), '\0' );
}
Suggestions are still welcome
A: How about this:
vbuffer.reserve(vbuffer.size() + 20);
vbuffer.insert(vbuffer.end(), s.begin(), s.end());
vbuffer.insert(vbuffer.end(), 20 - s.size(), '\0');
An additional check on the string length is recommended, along with a policy for handling over-long strings (e.g. assert(s.size() < 20);).
A: If you don't use std::string at all and avoid the temporary std::vector, you can easily do this without any extra dynamic allocation.
template <unsigned N>
void prepBuffer(char const (&s)[N])
{
std::copy(s, s + N, std::back_inserter(vbuffer));
vbuffer.resize(vbuffer.size() - N + 20);
}
Or, since the number of characters to be written is known ahead of time, you could just as easily use a nontemplate function:
void prepBuffer(char const* s)
{
unsigned n = vbuffer.size();
vbuffer.resize(n + 20);
while (*s && n != vbuffer.size())
{
vbuffer[n] = *s;
++n;
++s;
}
assert(*s == 0 && n != vbuffer.size());
// Alternatively, throw an exception or handle the error some other way
}
A: Another idea:
std::vector<std::array<char, 20> > prepped(3);
strncpy(prepped[0].begin(), "Argentina", 20);
strncpy(prepped[1].begin(), "Herzegovina", 20);
strncpy(prepped[2].begin(), "Zambia", 20);
You could write
typedef std::vector<std::array<char, 20> > prepped_t;
strncpy(..., ..., sizeof(prepped_t::value_type));
in case you wanted to be a bit more flexible when changing the size of the nested array
A: void prepBuffer( const char *s, std::size_t offset)
{
strncpy(&vbuffer[offset], s, 20);
}
Testing the function
int main()
{
vbuffer.resize(60);
prepBuffer( "Argentina", 0);
prepBuffer( "Herzegovina", 20);
prepBuffer( "Zambia", 40);
cout << &vbuffer[0] << endl;
cout << &vbuffer[20] << endl;
cout << &vbuffer[40] << endl;
}
That minimizes copying, at the cost of maintainability.
Here is nearly-optimal code that is still readable and maintainable.
std::string vbuffer;
void prepBuffer( const std::string& s)
{
vbuffer += s;
vbuffer.resize( ( (vbuffer.size() +19) / 20) * 20));
}
Testing the function
int main()
{
vbuffer.reserve(60);
prepBuffer( "Argentina");
prepBuffer( "Herzegovina");
prepBuffer( "Zambia");
cout << &vbuffer[0] << endl;
cout << &vbuffer[20] << endl;
cout << &vbuffer[40] << endl;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Help with c++ logic? Something::methodname()
{
(unsigned char*) ptr = (unsigned char*) m_pptr;
while ((*ptr || *(ptr+1)) && (((unsigned char*)m_pptr+BUFSIZE)<ptr))
ptr++;
if(ptr == m_pptr)
return ptr;
return ptr + 1;
}
m_pptr is a protected member of a class. ptr is local to this function
Could someone help me with the logic of this code? I know it compiles but the answers I'm getting out are not the ones I'm expecting. I am memset-ing a buffer full of A5's and the while loop fails somehow. It skips right past it. Any help would be great.
This will go through a buffer and if the value of the pointer or the value of (ptr+1) is true it will increment the pointer AND the ptr can't exceed the size of the buffer(which is found by m_pptr "pointer to the beginning of the buffer" + buffer size) has to be true also. The if statement says if m_pptr(pointer to beginning of the buffer is the same as ptr then return just the pointer.
this function returns a void* and is passed nothing
A: (((unsigned char*)m_pptr+BUFSIZE)<ptr))
looks backward:
(((unsigned char*)m_pptr+BUFSIZE)>ptr))
would be more likely; Even more sane:
while (ptr < ((unsigned char*) m_pptr + BUFSIZE)) // until end of buffer
{
if (!*ptr) // null char reached
break;
if (!*(ptr+1)) // null char almost reached
break;
// do stuff
ptr++;
}
A: This bit looks suspicious to me:
while ((*ptr || *(ptr+1))
Imagine that ptr is pointing to a valid character byte, followed by a NUL terminator byte.
The first sub-test of the above line will evaluate to true, and so ptr gets incremented. Now ptr is pointing at the NUL terminator byte, and *(ptr+1) is pointing at the byte AFTER the NUL terminator byte... which might be garbage/undefined, and therefore might be non-zero, at which point (ptr) will be incremented again (because the second sub-test evaluated to true this time), so that ptr now points to the byte AFTER the NUL terminator byte. And from there on your pointer heads off into la-la-land, trying to interpret data that was never meant to be part of the string it was parsing.
A: Wouldn't it look cleaner and simpler if you used for-loop instead?
for ( int i =0; i<BUFSIZE && (ptr[i] || ptr[i+1]); i++);
It would be easier to notice wrong comparison, wouldn't it?
And i think it would be also easier to see that in this case it should be
for ( int i =0; i<(BUFSIZE-1) && (ptr[i] || ptr[i+1]); i++);
or even
for ( int i =1; i<BUFSIZE && (ptr[i-1] || ptr[i]); i++);
unless obiviously you accounted for that by having BUFSIZE equal to buffer size minus one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I take a text query, and get a location in Android? I was wondering how I can channel or simulate Google Maps just in the sense of a user types in a location in text, such as a restaurant name and a city name. Then Google suggests 5 or so places they have indexed, and presumably they know the GPS coordinates because Google then puts them on a map. I want to be able to use that feature- not the map, just getting the location.
My goal is for a user to type in a query, 5 options or so to be shown, and if they user chooses one of them, then the GPS coordinates, or a location object, is saved representing that place.
Ideally I could just send the query to Google and steal the results back to my app. Obviously building my own database of locations and an algorithm to suggest them is out of the question.
Thanks for the help and advice in advanced!
Note 1: To clarify, this does NOT involve the current position of the user/device.
Note 2: I looked at the Google Maps add-on API, but it looks like that is for a visual map, not the querying a location part. You are already supposed to know your location, and it will map it.
A: Use geocoder.getFromLocationName, you get back a list of Address objects, in those objects you will find all the information you need about the location.
To test this on the simulator you need an image with the Google APIs included. In a device should be fine if you have the market installed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Display in iOS Browser using without the use of the Tag Is it possible to display <svg> content inside an <html> in an iOS browser without the use of the <embed> or <img> tags which require me to store the <svg> content in a separate file?
The embedding of <svg> content inside <html> seems to work on all other modern browsers (IE9, Chrome, even Safari on Window!).
I have found some references that suggest changing the content-type to 'text/xml' might work, but I am not able to change it as my code is running as part of a mobile server control in SharePoint 2010.
My page contains several <svg> areas, each of which displays a simple graph. The data for these graphs is stored in a serialized object which needs to be deserialized before the svg polylines can be drawn. Since the deserialization process is time-consuming I prefer to do it once and generate all graphs in a single pass, rather than generating resource references to individual svg files which can be referenced by an <embed> tag.
Edit: There are indications that inline <svg> is supported in iOS5.
A: If you need to embed the SVG directly in the document
Use XHTML (not just HTML), serve it with the correct mime type, and your SVG will work correctly in all major browsers, including on the iPhone and iPad.
This example file uses inline SVG in XHTML, and even uses JavaScript and CSS in the host document to manipulate the SVG:
http://phrogz.net/SVG/svg_in_xhtml5.xhtml
It works fine in iPhone/iPad.
If you need to reference an external file
Use the <img> tag to reference your SVG directly. This works on iOS.
For example, open this on your iPhone/iPad:
http://phrogz.net/SVG/svg-via-img.html
which references
http://phrogz.net/SVG/heart.svg
Note that there is a bug with WebKit related to rendering variable-sized SVGs inside fixed-size <img> tags. (It appears to draw the aspect ratio for the SVG from the aspect ratio of the containing window instead of the dimensions of the <img> element.) You can see the weirdness in Chrome or Safari if you resize your browser window with that test file.
A: You may need to use inline SVG inside an XHTML compound document. In this case, XML namespaces are used for both the HTML root element and the inline SVG element. See here for a relevant example:
http://www.croczilla.com/bits_and_pieces/svg/samples/dom1/dom1.xml
Other useful examples may be found here:
http://www.croczilla.com/bits_and_pieces/svg/samples
A: Have you tried using <object>? I haven't done this in a while but you can Google for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does calling 'delete' in a specific way on a dynamic array not work? I'm wondering why this code doesn't work:
void KeyValueList::Release()
{
//(m_ppKeyValueList is a dynamic array of pointers to objects on the heap)
if (m_ppKeyValueList) {
for (int i = 0; i < m_iCapacity; ++i) {
if (m_ppKeyValueList[i]) {
delete m_ppKeyValueList[i];
}
}
/*delete[] m_ppKeyValueList;*/
for (int i = 0; i < m_iCapacity; ++i) {
delete (m_ppKeyValueList + i);
}
}
}
Why can't we iterate the dynamic array and delete it in this way?
A: A dynamic array is more than just a sequence of elements. It contains information about the array size as well. Moreover, there is just one chunk of memory known to the allocator. So just like with any dynamic memory, you can only free what you allocated, not smaller subsets of it.
That's why the language requires that you only invoke delete[] on a pointer obtained from a new[] expression, and that that is the only way to deallocate that memory.
A: Simple answer: because the language specifications say that you do that with a delete[].
Better answer: because after all for the heap manager the array pointed by m_ppKeyValueList is a single large allocation, not m_iCapacity consecutive small allocations, so you just have to tell it where the allocated block begins and it will deallocate it as a whole (after calling the single destructors if needed); if it kept each element as a single separated allocation into the allocated block lists it would be a stupid waste of resources (and if it used a bitmap for this it probably wouldn't have enough granularity to support this silly allocation scheme).
A: Because new int[5] allocates one contiguous block big enough to hold 5 ints. new int 5 times allocates 5 small blocks, each big enough to hold a single int. The number of deallocations must equal the number of allocations.
A: Case 1: m_ppKeyValueList is "a dynamic array of pointers to objects on the heap"
In this case you do need to delete m_ppKeyValueList piece by piece. If this is what you meant, your declaration will be of the form SomeType ** m_ppKeyValueList; Your allocation and deallocation should like
Allocation:
m_ppKeyValueList = new SomeType*[m_iCapacity];
for (int i = 0; i < m_iCapacity; ++i) {
m_ppKeyValueList[ii] = new SomeType;
}
Deallocation:
for (int i = 0; i < m_iCapacity; ++i) {
delete m_ppKeyValueList[ii];
}
delete[] m_ppKeyValueList;
However, that your code fails suggests that you do not have "a dynamic array of pointers to objects on the heap."
Case 2: m_ppKeyValueList is a dynamic array of objects on the heap
Here your declaration will be of the form SomeType * m_ppKeyValueList; Instead of allocating this piece by piece your allocation and deallocation take on a much simpler form:
Allocation:
m_ppKeyValueList = new SomeType[m_iCapacity];
Deallocation:
delete[] m_ppKeyValueList;
Bottom line:
Your allocations and deallocations need to match one another in number and in form. If you allocate something with new you need to destroy it with delete. If you allocate it with new[] you need to destroy it with delete[].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get scala-library.jar location How can I get the full path of scala-library.jar from file system with Scala code?
I've tried ways like scala.Console.getClass.getProtectionDomain.getCodeSource.getLocation.getPath but it seemed don't work (returned a null pointer).
A: We use this to adjust the classpath for caliper:
val so = classOf[ScalaObject].getResource("ScalaObject.class").toString
val scalaJar = so.substring(so.lastIndexOf(":") + 1, so.lastIndexOf("!"))
This works in eclipse and a fat-jar from command line under Mac OS and Linux.
A: One way is to get it through the classpath like this:
System.getProperty("java.class.path").split(java.io.File.pathSeparator)
.filter{_.contains("scala-library")}.head
A: A bit similar to the answer by thoredge, but also searches the boot classpath (this should work in Eclipse + ScalaPlugin):
List("java.class.path", "java.boot.class.path", "sun.boot.class.path")
.flatMap(s => System.getProperty(s, "")
.split(java.io.File.pathSeparator))
.find(new java.io.File(_).getName == "scala-library.jar")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trying to learn about the new async features in c# I copied this example from here
I have seen many similar examples. Most of them say they're using the Async CTP. I'm using Visual Studio 11 on Windows 8 though so that does not apply. As shown, the error says TaskEx doesn't exist. I assume I'm missing a reference but don't know which one.
This page is http://users.zoominternet.net/~charleswatson/pic.png.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static Random rnd = new Random();
static void Main(string[] args)
{
//Do some other heavy duty background task in this thread
StartHotel();
Console.WriteLine("StartHotel called..");
Console.ReadLine();
}
static void StartHotel()
{
Console.WriteLine("Starting Hotel..");
for (int i = 0; i < 10; i++)
{
string name = "Chef" + i;
CookDish(name, "Dish" + i);
Console.WriteLine("Asked {0} to start cooking at {1}", name, DateTime.Now.ToString());
}
}
static async void CookDish(string chefName, string dish)
{
//Induce a random delay
int delay = rnd.Next(1000, 4000);
//Cook is cooking - Task
await TaskEx.Delay(delay);
//Write the result - StuffAfterAwait
Console.WriteLine("Chef {0} Finished at {1}", chefName, DateTime.Now.ToString());
}
}
}
A: Replace TaskEx with Task. At the top of the .cs file, you'll need:
using System.Threading.Tasks;
Much of the sample code I've seen refers to TaskEx, and the estimable Mr. Lippert seems to be indicating that's an artifact of their development process. If you're using the Developer Preview, calls like Run, WhenAll, and Delay are already methods of the class Task rather than of TaskEx. The release tools should be the same.
A: In the CTP we were unable to add new features to the Task type so we did the pragmatic thing and just made a new TaskEx type. In the final release there will be no such type; those methods will just be on Task like you'd expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Share data between users in metro application I would like to create a Metro application that allows a group of people to interact. One person would create data and serve as the owner, and multiple others would be invited in and be allow to modify that data. I heard from Build talks that each Metro application will get per-user Azure storage, but will it be possible to share that data between multiple users? Does anyone have a link they could share where I could research this?
A: I think that you are confusing SkyDrive with Azure Blob Storage.
SkyDrive
*
*Personal to a Live ID
*Not really meant as a base for collaborative work
Azure Blob Storage
*
*You can have public files that anyone can view and update
*You can have a lease on file that only allows certain people to edit it
*Since you own the Azure account you also control the content
*You can learn the basics here
A: If you want to share private app data between users, the best way to do so would be via a shared server of some sort. You should have a server (running on Azure, Amazon EC2, or anything really) that exposes a REST-ful web service which each application connects to. The shared state then lives on that server.
This is better than trying to use skydrive or some file-based system for storing shared data. With a file on skydrive and multiple users trying to access it, you would run into concurrency issues when more than 1 person tries to write to it.
A: You don't get Azure with Metro.
With Live you get a free SkyDrive that is a personal cloud storage. Like 10 GB. Can share files but it is via sending an email link. It is not file storage that would readily support a server type application to manage that sharing.
Azure is a cloud platform for file and data sharing. Azure is not free but storage cost is only $0.125 / GB per month. 10 GB = $1.25 / month. Using SkyDrive as shared storage you are giving up a lot of developer and hosting tools that come with Azure to save $1.25 / month.
A: It looks like there is a more formal definition of this with the updated help now available. They were referring to roaming application data. I found the following links that provide guidance:
http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
http://msdn.microsoft.com/en-us/library/windows/apps/hh465094.aspx
The general is that a small amount of temporary application data is provided on a per-app, per-user basis. The actual size you get is not detailed, but the guidance is pretty clear - app settings only, no large data sets, and don't use it for instant synchronization. Given this guidance, my plan is not a good one and will change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to mount WebDAV share programmatically on Windows 7/Vista without assigning drive letter? I need to mount WebDAV share programmatically on Windows 7/Vista without assigning drive letter. I know
net use
and
WScript.CreateObject('WScript.Network').MapNetworkDrive('E:', 'http://server/');
can mount WebDAV but they require drive letter. Any chance to mount WebDAV without assigning drive letter? For example Add Network Location Wizard can do this.
A: Use this to provide the credentials:
net use \\www.foobar.baz\folder /USER:Foo /PASS:Bar
Then, you can use the WebDAV drive by its UNC name (myCoolCommand.exe \\www.foobar.baz\folder)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convert a raster image into a polygon using QGis (or another method) I want to convert several images into polygon shp files using QGis (Quantum GIS 1.6).
I need to do edge detection AND differentiate between several different colors of lines (red, green, yellow and black). I need good edge detection as my images are scanned in at 200 DPI.
I'm open to other suggestions that don't involve QGis. Could I use Photoshop or would Arcgis do a better job of this?
A: Inkscape has a rather functional vectorizer (Trace Bitmap, IIRC)
http://inkscape.org/doc/tracing/tutorial-tracing.html
Inskscape's native format is SVG (fully vector based). It allows simplifcation of the resulting paths as well. Also, you might use the resulting XML to process automatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Comparing two arrays and showing the difference according to each one So I know there's an easy way to see the difference between two arrays using array_diff.
Take a look at why I need something a bit more specific though:
Let's say we have these 2 arrays
$array1 $array2
1 1
2 -
- 3
4 4
- 5
6 -
The - indicates it is missing from the opposing array.
If $array1 contains a missing element from $array2, it must be dropped from $array1.
If $array2 contains a missing element from $array1, it must be added to $array1.
If I simply perform array_diff($array1, $array2), it will only return me [2, 6]. This isn't helpful in my scenario because I don't know which of the two arrays these items are missing from.
I did a bit of looking around and didn't seem to find out if there is a native php function that will distinguish the arrays the items are missing from.
What would be the best way to go about this? I was thinking of looping $array1 and checking it against $array2 and storing the results missing in a third array, and visa-versa for a fourth array.
Is that the best way? or is there an even easier, native function i can use?
A: $comparison1 = array_diff($array1, $array2);
$comparison2 = array_diff($array2, $array1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best practices for a stationary frame at the top of an ASP.NET page? What is the best practice for creating a hovering "frame" in ASP.NET which will remain stationary at the top of a web page regardless of how the user scrolls vertically?
For example, if I create a textbox to contain search criteria, I might want the area of that textbox to remain stationary at the top of the browser window, allowing the user to scroll among the results freely and if they wish update their search criteria.
A: Here is a working example: http://jsfiddle.net/srPPu/2/ (edit: better link)
Using css create an element thats position is fixed on the top of the page (meaning it will not scroll
#search{
position:fixed;
width:100%;
height:25px;
background:#eeeeee;
clear:both;
}
#content{
padding-top:20px;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Filter output of adb logcat based on thread id I am using adb logcat -v threadtime to get the output in a format that includes time and thread id. I was wondering if there is a way to filter output based on the thread id (tid).
I want to get output from certain threads only, now i can get the thread id but not the filtered output.
Thanks
A: adb logcat -v threadtime | grep 123yourthreadid456
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: session variable set by checkbox not being stored/shared from page to page I have a listview that's showing a long list. Each item has the ability to be 'hidden' or not. I want a checkbox to either show all the list, or not to show the hidden ones. The idea is that users will hide the older items they don't want to see any more, but may want to see at some point. I want to store the value of this decision in a session variable so if the user navigates to another page, then comes back, the ShowAllCheckbox will pre-populate to what the user has previously decided. Everything is working good, except i can't get the session variable to keep. It keeps going back to False. This is what I have:
aspx page:
Show Hidden: <asp:Checkbox ID="ShowHiddenCheckbox" runat="server" AutoPostBack="True" OnCheckedChanged="ShowHiddenCheckboxChange" />
...
<asp:ListView ...>
<!-- this list works fine, and pulls the correct records -->
aspx.vb page:
Protected Sub ShowHiddenCheckBoxChange(ByVal sender As Object, ByVal e As EventArgs)
' toggle the values
Dim CheckBoxField As CheckBox = TryCast(sender, CheckBox)
If CheckBoxField.Checked Then
Session("ShowHiddenRotations") = False
Else
Session("ShowHiddenRotations") = True
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'if i navigate to another page, and come back to this one, this comes back as "False". I don't understand how it could be reset to False.
Response.Write( "Session: " & Session("ShowHiddenRotations") )
'when page loads check if session variable has been set to show/hide the hidden rotations
If Session("ShowHiddenRotations") Then
If Session("ShowHiddenRotations") = True Then
'update sql query on select statement to show the hidden rotations
'update checkbox to show it as checked
ShowHiddenCheckBox.Checked = True
Else
ShowHiddenCheckBox.Checked = False
End If
Else
'not checked by default (ie don't show hidden)
ShowHiddenCheckBox.Checked = False
End If
End Sub
The Session variable always reverts back to False when i navigate to another page and come back to this one. My understanding of session variables was that they would pass their values from one page to another until the user closes the browser. Maybe there's another way of doing this, or something simple I'm missing. Any help is much appreciated! Thanks!
A: Is session-state enabled on your site? It can be disabled in a couple of different way, on a page level or even in web.config.
You should also be aware the Page_Load event fires for every request, before the check-box auto-postback happens.
I'm also a little confused as to what you're trying to store: I assume every row has a check-box, but it seems you're trying to store the set/not-set value in a single session variable. How do you differentiate which have been selected, and which ones hasn't? :)
Update:
Okay, let's try a clean the code up a little bit. First create a property to access the session value:
Private Property ShowHiddenRotations As Boolean
Get
If Not Session("ShowHiddenRotations") Is Nothing Then
Return CType(Session("ShowHiddenRotations"), Boolean)
Else
Return False
End If
End Get
Set(value As Boolean)
Session("ShowHiddenRotations") = value
End Set
End Property
If you're using that value on other pages, I would recommend moving it to a seperate class.
Then we can reduce your other code to something closer to this:
Protected Sub ShowHiddenCheckBoxChange(ByVal sender As Object, ByVal e As EventArgs)
ShowHiddenRotations = ShowHiddenCheckbox.Checked
End Sub
And ...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If not Page.IsPostBack
' Load your data, better stick it in a seperate sub...
ShowHiddenCheckBox.Checked = ShowHiddenRotations
else
' This section is executed BEFORE any control methods are run, i.e. ShowHiddenCheckBoxChange
end if
End Sub
I'm guessing your problem is really just the order of how things are called in your page. What happens when you debug through it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone is there a way to set the type of animation when going from one view to another? I'm using presentModalViewController to go from view controller to view controller. Right now the animations are up and down when it goes from one view to another. Can I change it to right and left? I did not see any settings for this in the method presentModalViewController
Ted
A: Try this before presenting the modal vc:
[sampleViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
// or..
// [sampleViewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
// or..
// [sampleViewController setModalTransitionStyle:UIModalTransitionStylePartialCurl];
See the modalTransitionStyle Property of a UIViewController - Here are the Reference docs
You can make convenience methods for all styles like so (from Modal View Controller Example):
- (IBAction)showDefault:(id)sender {
SampleViewController *sampleView = [[[SampleViewController alloc] init] autorelease];
[self presentModalViewController:sampleView animated:YES];
}
- (IBAction)showFlip:(id)sender {
SampleViewController *sampleView = [[[SampleViewController alloc] init] autorelease];
[sampleView setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:sampleView animated:YES];
}
- (IBAction)showDissolve:(id)sender {
SampleViewController *sampleView = [[[SampleViewController alloc] init] autorelease];
[sampleView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:sampleView animated:YES];
}
- (IBAction)showCurl:(id)sender {
SampleViewController *sampleView = [[[SampleViewController alloc] init] autorelease];
[sampleView setModalTransitionStyle:UIModalTransitionStylePartialCurl];
[self presentModalViewController:sampleView animated:YES];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Balancing performance heavy procedures with real-time mouse input To put this question succinctly, is there any way to offer a real-time web application that requires processing to be done at every coordinate that a user moves their mouse to without dropping any mouse events?
With JS, if we want to keep track of the user's mouse location, we're essentially limited to attaching a mousemove handler to some element. Unfortunately, if we're using the mouse location to perform some expensive procedures such as drawing dynamic graphics to the screen via WebGL or a 2D canvas, we can (and typically do) lose a lot of accuracy.
For instance, if we link the user's mouse to a camera in a first-person WebGL game and the user is moving around erratically, some of the immersion will be lost as the camera fails to accurately mimic where the mouse is pointed. Or, even more simply, if we want to stamp multiple images onto a 2D canvas wherever the user drags the cursor, chances are we won't be able to produce a nice smooth curve if the user happens to draw one.
Ultimately, since JS is single-threaded we can't just have a separate thread running with the sole purpose of collecting mouse coordinates and let the application process the input as fast as it can (maybe a web worker would help here?). Similarly, we can't very easily prioritize collecting mouse events over the processing that needs to happen, because we can quickly start starving the processing side of things.
Is there some sort of approach that I'm overlooking here? If all an app does is record mouse coordinates, you typically get a very accurate record of where the mouse has been. The problem arises when we have to do some significant, but not unreasonable, processing based on that input in real-time.
A: Depending on what you're doing, you may be able to interleave your processing with event handling by working a little at a time in a timeout handler. This gives the event handlers a chance to fire in between.
var workInterval = 0; // or try other small values
function doABitOfWork() {
// ... Do stuff, but don't take too long ...
if (!finished) {
setTimeout(doABitOfWork, workInterval);
}
}
setTimeout(doABitOfWork, workInterval);
I've used this trick successfully to make the page responsive while constructing a heavy HTML table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: problem with finishing/exiting an activity in android app I am trying to exit an activity using the code
myClass.this.finish();
However, the code keeps on executing the lines after this.
Any idea why ?
A: This code just informs runtime that activity is finished so appropriate actions could be taken and activity is not preserved. But it does not mean immediate abort. Just put return where necessary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simple and concise desktop Cocoa NSXMLParser example? I would like to look through the elements of a file and when one specific element comes out, output the contents in between the tag.
I tried to follow the example in the Mac Dev entitled Event Driven XML Programming, but it just doesn't finish very clearly. It says to make sure I code the delegates, but it never shows an example. I just want to see a simple example where:
*
*The file is assumed to be a good xml file.
*Its path is a URL (or string).
*The way the delegate interacts with the parser is explained.
Many tutorials for Cocoa seem to almost teach you to circumvent the delegate classes and make your own IBAction functions so I'm missing the training I think on how to use the delegates properly. Its not clear in the example if I'm supposed to build the delegates in the delegate class or keep them in the class with the parser.
A: This is based on something I originally wrote for Cut out a part of a long NSString. I copied the NSXMLParserDelegate code from that iOS project into an OS X project. It gets the text from a specific object in a web page.
.h file:
@interface so7576593AppDelegate : NSObject <NSApplicationDelegate, NSXMLParserDelegate> {
NSWindow *window;
IBOutlet NSTextField *textField;
NSMutableString *divCharacters;
BOOL captureCharacters;
}
@property (assign) IBOutlet NSWindow *window;
@end
.m file:
#import "so7576593AppDelegate.h"
@implementation so7576593AppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
captureCharacters = NO;
NSURL *theURL = [NSURL URLWithString:@"http://maxnerios.yolasite.com/"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
[parser setDelegate:self];
[parser parse];
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqual:@"div"] && [[attributeDict objectForKey:@"id"] isEqual:@"I3_sys_txt"]) {
captureCharacters = YES;
divCharacters = [[NSMutableString alloc] initWithCapacity:500];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (captureCharacters) {
//from parser:foundCharacters: docs:
//The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element.
//Because string may be only part of the total character content for the current element, you should append it to the current
//accumulation of characters until the element changes.
[divCharacters appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if (captureCharacters) {
captureCharacters = NO;
[textField setStringValue:divCharacters];
[divCharacters release];
}
}
@end
A: If you click the "Next" link on that page and go onto "Handling XML Elements and Attributes" it will give you an example of how to code the delegates.
Apple provides a Mac example in ImageMap.
There's no difference between NSXMLParser on Mac and iPhone, so reading an iPhone example shouldn't be a problem.
A: Here is an example of using an NSXMLParser in a custom class that takes in a string of the tag to look for and the xml NSData:
JHXMLParser.h:
@protocol JHXMLParserDelegate <NSObject>
@optional
- (void)acceptParsedData:(NSMutableArray *)parsedData withIdent:(NSString *)ident;
- (void)acceptParsedDebugData:(NSMutableArray *)parsedData withIdent:(NSString *)ident;
@end
@class JHKeyValuePair;
@interface JHXMLParser : NSObject <NSXMLParserDelegate> {
NSString *ident;
@private
id _delegate;
NSMutableArray *_parsedData;
NSString *_key;
NSData *_rawData;
NSXMLParser *_dataParser;
NSString *_previousTag;
NSString *_currentTag;
}
@property (retain, nonatomic) NSString *ident;
- (id)initWithKeyValuePair:(JHKeyValuePair *)kvPair;
- (id)initWithKey:(NSString *)Key andData:(NSData *)data;
// delegate management. The delegate is not retained.
- (id <JHXMLParserDelegate>)delegate;
- (void)setDelegate:(id <JHXMLParserDelegate>)delegate;
- (BOOL)start;
@end
And the JHXMLParser.m:
#import "JHKeyValuePair.h"
#import "JHXMLParser.h"
@implementation JHXMLParser
@synthesize ident;
- (id)init {
if ((self = [super init])) {
ident = [[NSString alloc] init];
}
return self;
}
- (id)initWithKeyValuePair:(JHKeyValuePair *)kvPair {
if ((self = [self init])) {
_key = [kvPair key];
_rawData = [kvPair value];
_dataParser = [[NSXMLParser alloc] initWithData:_rawData];
_dataParser.delegate = self;
}
return self;
}
- (id)initWithKey:(NSString *)key andData:(NSData *)data {
if ((self = [self init])) {
_key = key;
_rawData = data;
_dataParser = [[NSXMLParser alloc] initWithData:_rawData];
_dataParser.delegate = self;
}
return self;
}
- (id <JHXMLParserDelegate>)delegate {
id <JHXMLParserDelegate> d = nil;
if (_delegate) {
d = _delegate;
}
return d;
}
- (void)setDelegate:(id <JHXMLParserDelegate>)delegate {
_delegate = delegate;
}
- (BOOL)start {
return [_dataParser parse];
}
- (void)dealloc {
[_parsedData release];
[_rawData release];
[super dealloc];
}
#pragma mark - NSXMLParser Delegate
- (void)parserDidStartDocument:(NSXMLParser *)parser {
_parsedData = [[NSMutableArray alloc] init];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
_currentTag = elementName;
if ([elementName isEqualToString:_key]) {
NSMutableDictionary *tmpDict = [[NSMutableDictionary alloc] init];
[_parsedData addObject:tmpDict];
[tmpDict release];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (![_previousTag isEqualToString:_currentTag]) {
[[_parsedData lastObject] setObject:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
forKey:_currentTag];
} else {
[[_parsedData lastObject] setObject:[NSString stringWithFormat:@"%@%@",[[_parsedData lastObject] objectForKey:_currentTag], [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]
forKey:_currentTag];
}
if (_previousTag) {
[_previousTag release];
_previousTag = nil;
}
_previousTag = [[NSString alloc] initWithFormat:@"%@", _currentTag];
[pool drain];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (![_previousTag isEqualToString:elementName]) {
[[_parsedData lastObject] setObject:@"" forKey:elementName];
} else {
if (_previousTag) {
[_previousTag release];
_previousTag = nil;
}
_previousTag = [[NSString alloc] initWithFormat:@""];
}
[pool drain];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
if ([_delegate respondsToSelector:@selector(acceptParsedData:withIdent:)]) {
[_delegate acceptParsedData:_parsedData withIdent:ident];
} else if ([_delegate respondsToSelector:@selector(acceptParsedDebugData:withIdent:)]) {
[_delegate acceptParsedDebugData:_parsedData withIdent:ident];
}
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
#ifdef DEBUG
DEBUGLOG(@"Parser ERROR Occurred: %@", self.ident);
DEBUGLOG(@"ERROR: %@", parseError);
#endif
if ([_delegate respondsToSelector:@selector(acceptParsedData:withIdent:)]) {
[_delegate acceptParsedData:_parsedData withIdent:ident];
} else if ([_delegate respondsToSelector:@selector(acceptParsedDebugData:withIdent:)]) {
[_delegate acceptParsedDebugData:_parsedData withIdent:ident];
}
}
@end
Used like so:
parser = [[[JHXMLParser alloc] initWithKey:@"INFO" andData:connectData] autorelease];
parser.ident = @"INFO";
parser.delegate = self;
[parser start];
Then implement the delegate method:
- (void)acceptParsedData:(NSMutableArray *)parsedData withIdent:(NSString *)ident {
// do stuff here with the parsed data
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you run multiple instance of gud in emacs I want to debug C++ and and php in the same emacs instance (using gdb and a php debugging mode that uses gud-common-init). When I fire both up everything just gets messed up. My guess is that gud.el doesn't support this.
Does anybody know if a way to do this exists?
A: From gdb help:
To run GDB in text command mode, use `gud-gdb'. You need to use
text command mode to debug multiple programs within one Emacs
session.
So as you say Emacs don't allow simultaneously full featured debugging, but allow simultaneously many text mode debuggers (like M-x shell).
A: There is a rewrite of gud called realgud and that support multiple debuggers. It doesn't support php, see this for a list of supported debuggers, but then I am not aware that gud does either. But there are instructions for how to add a new debugger.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drawing gets slow I am develop my writing application on my phone.
I need to draw the stroke on the canvas. I need to save all the points in order to redraw.
I found that as the number of points grow. It gets slow.
How ever i need all the points to redraw. Is there a way to save the previous drawing and restore the background for canvas?
A: Your canvas you are drawing in should be part of a view. Then you should be able to use getDrawingCache.
You need to enable caching too... check this.
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parsing a comma seperated string of paired numbers with CRLF between data pairs I am using C#.
I have scoured the examples, and tried for hours. This situation is different. I can't find a solution.
I have a long string captured from a device on a serial port.
The string's format is:
integer,integerCRLFinteger,integerCRLF
(repeats...). Ends with CRLF.
If you show this string in a RichTextBox it looks like:
2442,6266
7727,2727
6320,272
etc...
So, again, the string's format is
TextWhichIsAnInteger,TextWhichIsAIntegerCRLF
(repeats).
I would like to get it into two arrays (or lists) of type int.
And, as a bonus, into a 2 column array or list of paired ints.
This is driving me nuts. If you can help provide the code, I will be completely grateful and will worship you forever.
A: Something like this? From the top of my head. Untested. But it should give you the idea.
using System.Collections.Generic;
List<int> aTypes = new List<int>();
List<int> aValues = new List<int>();
string sInput = "1234,5678\n9876,4321\n";
// Split by linebreak.
string[] aLinebreaks = sInput.Split('\n');
foreach(string sNumericString in aLineBreaks)
{
// Split by comma.
string[] aNumbers = sNumericString.Split(',');
aTypes.Add(Convert.ToInt32(aNumbers[0]);
aValues.Add(Convert.ToInt32(aNumbers[1]);
}
...
aTypes.ToArray();
aValues.ToArray();
A: Why .Replace then .Split ?
Also, Tuples are great tools to make pairs.
string myNumbers = "123,456,789\r\n";
myNumbers += "123,456,789\r\n";
var delimiters = new[] {"\r\n"};
string[] lines = myNumbers.Split(delimiters, StringSplitOptions.None);
var result = new List<Tuple<int, int>>();
foreach (var line in lines)
{
var integers = line.Split(',');
result.Add(Tuple.Create(Int32.Parse(integers[0]), Int32.Parse(integers[1])));
}
A: Does something like this work for you?
string input = "2442,6266\r\n7727,2727\r\n1234,1234";
string[] numberGroup = input.Replace("\r\n", ":").Split(':');
IDictionary<int,int> numberPairs = new Dictionary<int, int>();
foreach(string str in numberGroup)
{
string[] pair = str.Split(',');
numberPairs.Add(Convert.ToInt32(pair[0]), Convert.ToInt32(pair[1]));
}
foreach(int key in numberPairs.Keys)
{
Console.WriteLine("Number Pair: [{0}]:[{1}]", key, numberPairs[key]);
}
//Output:
//Number Pair: [2442]:[6266]
//Number Pair: [7727]:[2727]
//Number Pair: [1234]:[1234]
EDIT
If you don't want duplicates there is this way, like Pano pointed out, but I would tell the splitter to remove empty results so it doesn't blow up on one of the index calls in the convert area.
string input = "2442,6266\r\n7727,2727\r\n1234,1234";
string[] numberGroup = input.Split(new[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
IList<Tuple<int, int>> numberPairs = new List<Tuple<int, int>>();
foreach(string str in numberGroup)
{
string[] pair = str.Split(',');
numberPairs.Add(Tuple.Create(Convert.ToInt32(pair[0]), Convert.ToInt32(pair[1])));
}
foreach(Tuple<int,int> item in numberPairs)
{
Console.WriteLine("Number Pair: [{0}]:[{1}]",item.Item1, item.Item2);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JAXB Annotations and SuperClass I'm trying to use JAXB annotations in a parent class so that all the sub classes can inherit them but I'm running into a marshaling error. I don't get the below error when I include @XmlRootElement and @XmlAccessorType(XmlAccessType.FIELD) in the sub class
error:
HTTP Status 500 - Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: application/xml
@MappedSuperclass
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
//class contents here
}
public class Child extends Parent{
//class contents here
}
A: You have to list all of your subclasses in @XmlSeeAlso annotation of your parent class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Running a .bat in the background So I have this in my coding:
vb Code:
file = My.Computer.FileSystem.OpenTextFileWriter("c:\command.bat", False)
file.WriteLine("@echo off")
file.WriteLine("cd " & TextBox2.Text)
file.WriteLine("adb shell dumpsys meminfo " & TextBox1.Text & " > C:\Sample.txt")
file.Close()
Shell("C:\command.bat")
what I want it to do is to run the batch file without it opening if that makes sense. Right now this runs on a loop for 10 minutes and on every 2 second tick it opens and then closes the .bat. Which is really annoying to see a .bat open and close every two seconds. Is there anyway to get this process to run silently in the background so the user doesnt even know that it is running?
A: Shell("C:\command.bat", AppWinStyle.Hide)
That will run the batch file but the window is hidden.
or use Process.Start as suggested by David. with WindowStyle = ProcessWindowStyle.Hidden
A: Here is an example on how to use Process.Start with a hidden window
Dim params As String = "C:\command.bat"
Dim myProcess As New ProcessStartInfo
myProcess.FileName = "cmd.exe"
myProcess.Arguments = params
myProcess.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(myProcess)
if you run into the issue of file not found errors with the path you can try to add the following Windows API call and run your file path through this function as well.
'This would be declared at the top of your Form Code/Class Code
Private Declare Auto Function GetShortPathName Lib "kernel32" ( _
ByVal lpszLongPath As String, _
ByVal lpszShortPath As StringBuilder, _
ByVal cchBuffer As Integer) As Integer
And here is the function to return back a ShortPath (win98 style path (ie. c:/progra~1/myfolder/myfile.bat)
Public Function GetShortPath(ByVal longPath As String) As String
Dim requiredSize As Integer = GetShortPathName(longPath, Nothing, 0)
Dim buffer As New StringBuilder(requiredSize)
GetShortPathName(longPath, buffer, buffer.Capacity)
Return buffer.ToString()
End Function
then simply call your path like this in your process.start function
Dim params As String = GetShortPathName("C:\command.bat")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can specify multiple paths on LinkerBaseInputPaths Wix Property? The PropertyGroup MSBUILD Task on WIX lets you set the LinkerBaseInputPaths property, its essentially the -b parameter for light.exe.
The property is named plural for multiple paths (which light.exe supports by multiple -b arguments), however how do we specify multiple paths on the property?
I have tried separating the paths with ";" and ",", both do not work.
Any suggestions?
A: How does it not work? MSBuild turns a semi-colon-separated string into an array for the task. For example, the WiX setup project uses this:
<BaseInputPaths>$(OutputPath_x86);$(OutputPath_x64);$(OutputPath_ia64);$(MSBuildProjectDirectory);$(WIX_ROOT)src;$(WIX_ROOT)bin;$(WIX_ROOT)src\dutil\inc;$(BaseInputPaths)</BaseInputPaths>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to "genericize" an XML-to-XML XSL transform to work with files having different tags but same basic structure I have a set of XML files similar to this:
Example Input File:
<a-list>
<a-item key_field="unique1" other="foo"/>
<a-item key_field="unique2" other="foo"/>
...
</a-list>
and I have a transform that will merge these files into a single file of the same structure. It generates the same outer level element (<a-list>) containing all of the <a-item> elements from the files, and discards duplicate entities (entities having the same key_field). I am now faced with several other sets of files, each very similar in its top level structure, that I need to perform almost the same exact kind of merge.
For example, these files might look like this:
<b-list>
<b-item different_key_field="unique93" other="foo"/>
<b-item different_key_field="unique94" other="foo"/>
...
</b-list>
These other files have different data in them, but the transform is generically the same: I need to take multiple input files that have the same structure (a root level containing a list of items, where the items are uniquely identified by a key attribute), and produce an output file that has the top level element containing all of the (unique) items from each of the input files.
Unfortunately, my "merge" transform operates specifically on the named elements in the input files (e.g. it has templates for <a-item> nodes, and it specifically looks for duplicated key_field attributes). It is fairly trivial to copy the transform, search/replace the element names and the key attribute name, but it seems horribly inefficient to duplicate the same code once for each type of input file. The only things that are different are the name of the root element, the name of the item element, and the name of the key attribute. What I want to do (merge) remains the same.
How can I write a transformation that can perform this kind of merge operation without specifying the exact names of the elements/attribute, so that I can invoke the same transform for each type of file? Is there any way to accept the root element name, item element name, and key attribute name as parameters?
As additional constraints, I'm limited to using Xalan, so I believe that means XSL 1.0 only, and it would be best to avoid any extensions.
I thought about transforming an XSL with another XSL, but that seems rather convoluted for such a simple thing.
I've tried searching here and around the internet via Google, but I'm somewhat new to XSL, and all of the words I can think to search in association with XSL or XSLT seem to have specific meanings in the XSL context that make them less useful as search terms (e.g. XSL template, generic XSL, etc.). Some vocab and some good links would be great, an example would be amazing.
Many Thanks,
Russ
A: Here is a complete solution:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pDoc1File" select="'b-list-file1.xml'"/>
<xsl:param name="pDoc2File" select="'b-list-file2.xml'"/>
<xsl:param name="pElemName" select="'b-item'"/>
<xsl:param name="pKeyAttrName" select="'different_key_field'"/>
<xsl:variable name="vDoc1" select="document($pDoc1File)"/>
<xsl:variable name="vDoc2" select="document($pDoc2File)"/>
<xsl:template match="/">
<xsl:apply-templates select="$vDoc1/node()"/>
</xsl:template>
<xsl:template match="/*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:copy-of select=
"*[name()=$pElemName]
[not(@*[name()=$pKeyAttrName]
=
$vDoc2/*/*[name()=$pElemName]
/@*[name()=$pKeyAttrName])
]"/>
<xsl:copy-of select=
"$vDoc2/*/*[name()=$pElemName]
[not(@*[name()=$pKeyAttrName]
=
$vDoc1/*/*[name()=$pElemName]
/@*[name()=$pKeyAttrName])
]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
File: b-list-file1.xml
<b-list>
<b-item different_key_field="unique93" other="foo"/>
<b-item different_key_field="unique94" other="foo"/> ...
</b-list>
File: b-list-file2.xml
<b-list>
<b-item different_key_field="unique92" other="foo"/>
<b-item different_key_field="unique93" other="foo"/> ...
</b-list>
When this transformation is applied on any XML document (not used / ignored), the wanted, correct result is produced:
<b-list>
<b-item different_key_field="unique94" other="foo"/>
<b-item different_key_field="unique92" other="foo"/>
</b-list>
Explanation:
*
*The filepaths (URLs) to the documents to be processed are provided as global (external to the transformation) parameters.
*The name of the elements is provided in a global parameter.
*The name of the "key" attribute is provided as a global/external parameter.
*Finally, the XPath expressions in the select attributes of the two <xsl:copy-of> instructions, use the values of the parameters for selecting the appropriately-named elements and attributes.
Do note: Every XSLT processor has its own implementation of setting and passing parameters to the transformation. Read this in the Xalan documentation.
A: Well you can solve your problem with parameters. There is no notion of templated xsl like C++ templates for example, but with parameters you can achieve this effect. For example one of my xslt files looks like this :
<xsl:stylesheet xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xml:space="preserve" version="2.0">
<!--Output type to be used with the xsl:result-document-->
<xsl:output name="html" encoding="utf-8" method="html" indent="yes" doctype- system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"/>
<!--Global output type-->
<xsl:output encoding="utf-8" method="html" indent="yes" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"/>
<!--xml output-->
<xsl:output name="xml" encoding="utf-8" method="xml" indent="yes"/>
<xsl:param name="sapFile" as="xs:string" required="yes"/>
<xsl:param name="automaticDate" as="xs:string" required="yes"/>
<xsl:param name="generatePDF" as="xs:string" required="yes"/>
<xsl:param name="fileName" as="xs:string" required="yes"/>
.
.
.
The important element here is xsl:param. You can pass these parameter when you "call" your xsl transform. These parameters in your case would be for example : in one case a-list and in the other case b-list etc. Then you can use these parameters like $param wherever you want in your xslt code so that you can achieve genericity.
I hope that give you some pointers :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: var bounds not working on my google maps I am having an issue getting bounds to work with my google map. All markers are pointing to the correct coordinates, but when they appear on the map, the auto zoom does not adjust properly. Can someone please help me with my var bounds please.
var companyLocale = new google.maps.LatLng(33.206060, -117.111951);
var noGeo = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
<!-------------------------------USER MARKERS------------------->
var usericon = new google.maps.MarkerImage(
'images/userimage.png',
new google.maps.Size(48,48),
new google.maps.Point(0,0),
new google.maps.Point(24,48)
);
var usershadow = new google.maps.MarkerImage(
'images/usershadow.png',
new google.maps.Size(76,48),
new google.maps.Point(0,0),
new google.maps.Point(24,48)
);
<!-------------------------------COMP MARKERS------------------->
var icon = new google.maps.MarkerImage(
'images/image.png',
new google.maps.Size(48,48),
new google.maps.Point(0,0),
new google.maps.Point(24,48)
);
var shadow = new google.maps.MarkerImage(
'images/shadow.png',
new google.maps.Size(76,48),
new google.maps.Point(0,0),
new google.maps.Point(24,48)
);
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Safari supports the W3C Geolocation method
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var bounds = new google.maps.LatLngBounds();
var placeMarker = new google.maps.Marker({
position: initialLocation,
icon: usericon,
shadow: usershadow,
animation: google.maps.Animation.DROP,
map: map
});
map.setCenter(initialLocation);
var bounds = new google.maps.LatLngBounds();
var Marker = new google.maps.Marker({
position: companyLocale,
icon: icon,
shadow: shadow,
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(Marker, 'click', function() {
window.location = "main-export/main.html";
});
google.maps.event.addListener(placeMarker, 'click', function() {
window.location = "main-export/loyalty.html";
});
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation();
}
function handleNoGeolocation() {
initialLocation = noGeo;
map.setCenter(initialLocation);
}
bounds.extend(myLatLng);
map.fitBounds(bounds);
}
A: You have bounds.extend(myLatLng); but nowhere does myLatLng get created. You seem to only have two markers, so you should just need to call bounds twice, once for each latlng.
Replace bounds.extend(myLatLng); with
bounds.extend(companyLocale);
bounds.extend(initialLocation);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is CSS lone * selector good for? There is one CSS selector I cannot figure good use for.
* {
/* Some styles */
}
I know it is used to set styles on every element on a page. Some people use it to reset every padding and margin to 0. Other ideas?
I don't ask about hacks. I don't ask about combination like something * or something * something_else. I ask only about lone *.
This questions is similar, but little different.
in what conditions we can use css * selector?
I only ask about lone *.
It was my mistake to ask this question on Stack Overflow. There is probably no good answer. It could only be something like open poll about weird ideas. There was too much of my personal opinion in the first version of this entry too.
A: It is important and useful if you want to SPECIFICALLY override inheritance. Applying a font and color to body for example will be overridden by child elements. The * will not unless an element is specifically overridden.
Ex:
* { color: #FFF }
#Wrapper
{
color: #000
}
A p element within #Wrapper will still be #FFF unless it is specifically set in the CSS above as.
#Wrapper p
{
color: #000;
}
A good writeup on it has been done by Eric Meyer.
A: The universal selector is often used in reset.css (which standardize the default browser style sheet) to avoid browser quirks. There is a lot of content on why to reset and actual reset sheets, so I'll let you pick your fav.
Another important used I've seen is to provide child-selector '>' for IE.
So for example.
.article > p { padding: 5px; }
There is a good write up here if you're interesting in supporting IE and use the child selector.
http://www.sitepoint.com/erics-universal-child-selector/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom ADO.Net Data Provider - How To? Is there any good How-To document on developing Custom ADO.Net data provider?
I looked at the MSDN and all I could find is an article published on this subject in 2003 and could not find any update for later versions.
Thanks in Advance
A: That's still all there is to it if you are using basic ADO.Net. The API is pretty stable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ruby gem extend class with methods defined in a block I am creating a gem and wanted to be able to modify an ActiveRecord object by creating attribute getters and setters dynamically to a serialized attribute. For example:
class User
has_serialized :setting do |config|
config.define :notify_by_email, default: true
config.define :notify_by_phone, default: true
end
end
user = User.new
user.notify_by_email? # true
user.notify.by_phone? # true
user.notify_by_email = false
user.notify_by_phone = false
user.notify_by_email? # false
user.notify.by_phone? # false
I realize that I will need to extend ActiveRecord with a module containing the method has_serialized and that I will need to use define_method to add the custom getters and setters, however I can't figure out how to combine the two using the block syntax I want for definition. Any ideas?
A: You can create a class that extends hash used to capture your parameters then execute the block using the class. Once finished, you can iterate over your capture performing define method. Here is an example:
class Initializer < Hash
def define(settings, options = {})
self[setting] = options
end
end
module ClassMethods
def has_serialized(name, &block)
initializer = Initializer.new
block.call(initializer)
initializer.each do |method, options|
define_method "#{method}?" do
...
end
define_method "#{method}=" do |value|
...
end
end
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Git repo for framework inside local git project in Xcode 4 I have an iOS project in Xcode 4, that is using Git. Now I want to add the MKStoreKit framework to my project. It is already under version control using Git and a public repo. I'd like to include it in my project, and allow my project's git version control to do version control of the currently pulled version of MKStoreKit, while maintaining the ability to clone any updated MKStoreKit code with standard git ease. I see that a git submodule or subtree is probably what I need, but it seems like a real PITA. Is there not a simpler way?
So far any external code I add to my project I clone to a temp directory, then copy the individual files into my project. This feels like a kludgy way to do things.
A: Check out the submodules section of the Git book. They're not really all that bad.
If you have a git repository, and you want to add another repository as a subdirectory, you can do this:
git submodule add git://github.com/MugunthKumar/MKStoreKit.git mstorekit
Now you have a directory "mstorekit" inside your project that is actually the MStoreKit repository. If someone clones your repository, they'll start with an empty "mstorekit" directory. Running:
git submodule init
git submodule update
Will clone the MStoreKit repository. They'll end up with the HEAD of the MStoreKit repository at the same commit as the one checked in to your repository.
Updating MStoreKit would look like this:
cd mstorekit
git pull origin master
cd ..
git ci -m 'updated mstorekit to latest version'
There are some alternatives out there, including git-subtree, which I saw mentioned recently around here. I have no experience with it (whereas I've been reasonably happy working with submodules).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mobile detection between 2 different platforms I am in the process of wrapping up a mobile site and I need to give the user the option to switch from the mobile(jQuery mobile) site to the desktop version of the site. I am planning on using the code below for detection on both sides and then setting a cookie if the user makes the preference of one or the other site (mobile / desktop). I am curious to know best practice for this type of thing as I feel this will work well but not sure if there is a better way.
var isMobile = navigator.appVersion.toLowerCase().indexOf('mobile') > -1
Thanks in advance,
JN
A: There are many ways to do it but because there are so many variations of user agents it can definitely be tricky. However, there is a nice script out there that solves this problem fairly elegantly. It also handles the cookie'ing that you touched on as well.
https://github.com/sebarmeli/JS-Redirection-Mobile-Site
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best way to store (and retrieve!) dom-element-specific data using javascript I've got a matrix of drop down lists, and I'd like to be able to show the user when they have edited a setting visually (for example by setting the background of the table cell to red). If they switch it back to the original value, it will go back to the default background color. This way it will be unambiguously clear what the state of the system is.
To do this I have come up with setting an onchange handler on the <select> element like this: select.setAttribute('onchange','chSel(this,'+select.selectedIndex+');'); where select is a <select> element.
It will call the function chSel with a reference to itself and the current setting, so it will be able to set classes which will determine display properties via CSS:
function chSel(node, origSelIndex) {
if (node.selectedIndex == origSelIndex) // switching back to the set state
node.parentNode.removeAttribute('class');
else node.parentNode.setAttribute('class','cell_changed');
}
That doesn't require the retrieval of dynamic data, though the saved selectedIndex value in the onchange handler serves as element-specific static data.
I wanted to extend this functionality I have described by making a border around my table, which I intend to color red when ANY of its contents are modified, so that if a table is huge it is still possible to tell at a glance if any of its entries are modified.
There is a bad way and a better way to implement this. The bad way, which I do know how to implement in compliant HTML/XHTML, is to have chSel (which is executed any time the user interacts with a drop down menu) run a full search through the entire table to count edits, and mark the table border accordingly. This may not actually be a performance problem but I anticipate that it will be. I don't think it would scale that well.
The better way is to keep a count of the number of edited elements. When that number drops back to zero (user changes all his edits back to original values) I can re-mark the table as unedited.
However this requires that I have some method of determining if a select menu has been changed from a new value to a different new value, as opposed to changing from the original value to a new value, i.e. it is now relevant what the value being changed from is. There does not appear to be a way to do this. This discussion seems to indicate that I cannot create and retrieve custom attributes while keeping my document valid. When I have tried to assign arbitrary attributes I've had difficulty retrieving their values.
What's left? Can I build an object which I will use as a hash from elements to integers? Will javascript even let me do that?
A: I'm not sure I totally follow what you're trying to do, but you can keep track of state either in javascript variables or in custom DOM attributes. Javascript variables are slightly easier, but you have to give them an appropriate scope so they survive the duration of your operation. Custom DOM attributes are sometimes easier to make object oriented and to avoid any global javascript variables. jQuery's .data() capability is actually in between the two. It uses one custom data attribute to tag the DOM object with a unique tag and then stores all the actual data in a javascript map.
Once you store the state appropriately, anytime you get a change event, you can compare to the previous value and see what actually changed from the previous state, update your new state and save the new value as the previous value or do whatever else you need to do.
For example, in this way, you could keep a count of how many edited items there were and anytime that value goes from 0 to non-zero or non-zero to 0, you would change the overall table look as desired. Likewise, anytime an individual cell changes, you could update it's look.
If your DOM elements are your only data structure, then it's probably easiest to just create a custom attribute and keep additional data there. The HTML5 way of doing this is to preprend "data-" to your attribute names as in obj.setAttribute("data-origSelectIndex", x) or obj["data-origSelectIndex"] = x to keep them clear of any name conflicts with standard attributes.
If there's any reason you don't want to use custom attributes, then you would need to make a parallel javascript data structure (probably an array where each item in the array corresponds to one DOM element in some way that you can map between the two) that held the data.
A: Most form controls have a defaultValue property. To determine if any have changed from their default, cycle through them and compare the current value with the defaultValue. For select elements, always set one to selected, and check if the currently selected option has its defaultSelected property set to true. Similarly for radio buttons and checkboxes.
That way you don't have to store any values, it's done by the DOM elements themselves.
A: Working off of @jfriend00 's suggestion using dom attributes as a sort of global variable:
Jsfiddle demo.
CSS
.selected { border: 1px solid red;}
HTML
<div id="table1">
<select id="sel1">
<option>1</option>
<option>2</option>
<option selected>3</option>
</select>
<select id="sel2">
<option selected>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div id="table2">
<select id="sel3">
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>
<select id="sel4">
<option selected>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
Javascript:
(function(){
var selects = document.getElementsByTagName('select'),
i = 0,
selectLength = selects.length;
var applyParentChange = function(node, val){
var currentEdits = node.getAttribute('data-edits') || 0;
currentEdits = parseFloat(currentEdits, 10) + val;
if(currentEdits <= 0) {
currentEdits = 0;
node.className = '';
} else {
node.className = 'selected';
}
node.setAttribute('data-edits',currentEdits);
};
var onSelectChange = function(){
var defaultIndex = parseFloat(this.getAttribute('data-default'),10);
if(defaultIndex === this.selectedIndex){
applyParentChange(this.parentNode, -1);
this.className = '';
} else {
applyParentChange(this.parentNode, 1);
this.className = 'selected';
}
};
for(i=0; i<selectLength; i+=1){
selects[i].setAttribute('data-default',selects[i].selectedIndex);
selects[i].onchange = onSelectChange;
}
})();
To walk through the code a bit...
You get a collection of all your select elements and give them a custom property with their default selected index and you give it a onchange event directly.
On change it checks the new index, versus the original (default) index and applies the CSS to the element if needed. Then it passes it off to the parent node (div in this case, but can be whatever).
In the parent we keep a similar custom attribute for the number of edits. The min of 0 is to keep it set if someone keeps re-selecting the default over and over. It applies the CSS if it has 1 or more edits, removing if it is 0.
Note that this is only one approach, you can keep a collection inside a variable that you keep references/counts in, some use hidden (offscreen) input elements that store values...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Sizing panels in an ItemsControl I have a parent view model, that contains a collection of other view models (of same type) (children). On Initialization the number of children will be decided (varying).
The child View consists of a button and a list box. Initially the listbox is hidden. On click of button the list box appears and on clicking outside (outside of the control or any other child button).
On init only buttons will be shown. I want these buttons to be spaced across the available width. The requirement is that once the button is clicked (when listbox is shown) the width of the whole child will increase (lets say 350) and when it is hidden it reverts back to the original size.
In the parent i am using a ItemsControl to show the children views. I have tried all controls but not able to figure ou a appropriate solution for this. I have two issues:
*
*On Button click i am able to show current listbox. If i click another button teh first one goes off. Till here it works fine. But i also need that the currentopen listbox closes on click anywhere outside of the control (child control)
*How to automatically size and resize based on what is clicked . First all should be propotionately sized and then when one is clicked it's size increases (here other childs resize with the rest available space). When the one (open control) is collapsed, all of them come back to normal proptionate sizes.
Any ideas ?
BTW, i am using MVVM pattern for this.
A: how about using a flag to direct the view to perform calc and refresh/readjust the sizing as when needed.
like on-click routine, set the flag on
whenever the view (pre-)painting/drawing event is kicked in, check if the flag is on, do the calc and sizing, then off the flag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Building a Silverlight application upload utility? This post is really more of a discussion if this is even possible.
There are numerous examples all over the web, but all of those are using asp.net applications and unfortunately I can't go that route. So my goal is to build an upload utility in Silverlight that can be deployed as a CRM 2011 web resource, without using anything Asp.Net related.
I have looked at the Telerik SL upload control, but it appears to require a ServiceURL handler and I'm not sure I can embed something like that within Silverlight and make it work?
I guess I'm looking for some direction here on what my options would be. I don't want to start down one path and run into a brick wall.
Thanks for reading!
A: Your SL control can upload the bytes of the file as an attachment (in the Notes area) to the entity record. Here is a project on CodePlex that uses SL to upload an image as an attachment:
http://crmattachmentimage.codeplex.com/
Hopefully that will get you pointed in the right direction!
A: I haven't really looked into the creation of web-resources from silverlight, but considering the web-resource utility would be using the CRM SOAP end-point, I imagine you could do the same from Silverlight.
From Silverlight, you would either need to make a reference to SOAP End-Point url which can be found in the CRM client in Settings -> Customization -> Developer Resources.
Otherwise, you could use the open-source project CrmSilverSoap library which already has all the generated proxy classes as well as a few helper methods for connecting to the various CRM services.
In trying to work with and create the web resources, I'd have a look at the this SDK article which shows to how to use some messages for Creating Web Resources. You will need to make the required modifications to code to enable these messages to be sent via the reference soap end-point in silverlight.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML+CSS : how to move not close divs to create a right column? I have a problem that I thought was pretty simple but that is taking me a lot of time to solve it. If there is a simple solution (and I don't know CSS enough), please point me there and I'll close this question immediately.
My problem is the following.
I have 6 divs one on top of another, something like:
<div id="header">header content</div>
<div id="sidebar1">sidebar1 content</div>
<div id="maincontent">maincontent content</div>
<div id="maincontent2">maincontent2 content</div>
<div id="sidebar2">sidebar2 content</div>
<div id="footer">footer content</div>
What I want to have is something like:
-----------------------------------------------------------
| header content |
-----------------------------------------------------------
-------------------------------------- -------------------
| maincontent content | | sidebar1 content|
| | -------------------
| | -------------------
| | | sidebar2 content|
| | -------------------
--------------------------------------
--------------------------------------
| maincontent2content |
| |
| |
| |
| |
--------------------------------------
-----------------------------------------------------------
| footer content |
-----------------------------------------------------------
In other words, is there a way to create a right column even if the divs are not one after another using only CSS and without moving the divs in the code?
I tried to use for sidebar1 the following css
position:absolute;
top:3em;
right:0;
and for sidebar2 the following css
position:absolute;
top:9.5em;
right:0;
but I have the impression that this is not the right way to do it.
A simple way could be to define the top attribute size as a function of the height of heather, but I couldn't find any way to do it only with CSS.
Thanks!
A: Well... as a direct answer to your question, you can use a combination of floats and % widths to accomplish this. You can also use fixed widths, but you'll have to determine what those sizes are. Here's a simple implementation:
Demo
CSS
#maincontent
{
float:left;
width:70%;
background:#ee5;
}
#sidebar2,#sidebar1
{
float:right;
width:30%;
background:#5e5;
}
#footer
{
clear:both;
background:#5ee;
}
#header
{
background:#55e;
}
HTML
<div id="header">header content</div>
<div id="sidebar1" class="side">sidebar1 content</div>
<div id="maincontent">maincontent content</div>
<div id="sidebar2" class="side">sidebar2 content</div>
<div id="footer">footer content</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Service running AsyncTask over and over in onCreate() method I have a Service that i run when a alarm is sent.
The problem is the service runs ever couple of hours automatically.
I only want it to run once when the alarm is executed.
Here is the code i am using:
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
loadList service_release = new loadList();
service_release.execute();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return startId;
}
@Override
public void onCreate(){
super.onCreate();
loadList service_release = new loadList();
service_release.execute();
}
Someone told me i should move the AsyncTask to execute in onStartCommand(). But i didnt see anything in the docs that will fix my problem by doing this.
What do i need to do for it to run once and dont kepp running over and over throughout a time period after the alarm is set off?
EDIT:
My Alarm is being set up like this..
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager)getSystemService(alarm);
Intent Aintent = new Intent("REFRESH_THIS");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.FRIDAY, );
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 4 * AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pi);
A: You have a repeating alarm, that means it will be triggered repeatedly, and launch the service each time it is. If you don't need it to repeat, set a non-repeating alarm, using AlarmManager.set().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Downsample image below size limit before upload There's a 2MB limit on the server where I need to upload an image.
I'm using this method to downsample a Bitmap Strange out of memory issue while loading an image to a Bitmap object
within this method
public InputStream getPhotoStream(int imageSizeBytes) throws IOException {
int targetLength = 1500;
ByteArrayOutputStream photoStream;
byte[] photo;
Bitmap pic;
final int MAX_QUALITY = 100;
int actualSize = -1;
do {
photo = null;
pic = null;
photoStream = null;
//this calls the downsampling method
pic = getPhoto(targetLength);
photoStream = new ByteArrayOutputStream();
pic.compress(CompressFormat.JPEG, MAX_QUALITY, photoStream);
photo = photoStream.toByteArray();
actualSize = photo.length;
targetLength /= 2;
} while (actualSize > imageSizeBytes);
return new ByteArrayInputStream(photo);
}
This throws OutOfMemoryError on the second iteration. How could I downsample the image below a certain size limit?
A: I think the problem is happening because you are compressing the image to a in memory representation, you need to free up that memory before you try to compress again.
You need call close() in the photoStream before trying again in order to free up resources.
Also toByteArray() makes a copy of the stream in memory that you have to free up later, why don't you just use the photoStream.size() to check for the file size?
I can post some code if you need.
A: Instead of this:
pic = null;
Do this:
if (pic!=null)
pic.recycle();
pic = null
If you simply set the bitmap object to null the memory it occupied isn't released immediately. In the second case you are explicitly telling the OS you are done with the bitmap and its okay to release its memory.
Also consider using a compression quality of 90 instead of 100, I believe that will reduce the resulting file size quite a bit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: android non unique view id I have a LinearLayout that contains a ViewStub which points to a ViewFlipper. The ViewStub is *statically assigned its layout reference values on startup (currently, next version will be dynamic). Located within the ViewFlipper are 10 RelativeLayouts each with its own assortment of buttons, edittexts, textviews, etc.
On about half of those pages is a TogggleButton
<ToggleButton
android:id="@+id/dontNeed"
android:textOn="DON'T NEED"
android:textOff="DON'T NEED"
android:layout_width="200dp"
android:layout_alignParentBottom="true"
android:layout_height="100dp"
android:textSize="36sp"
android:layout_centerHorizontal="true"
android:background="#AA0000"
android:layout_marginBottom="25dp"
/>
Specific views, when used, will assign recommendation values to others based on some calculations. This button well let the system know the user does not require any information from the current page.
If I have this same button on many pages, does it require a unique ID for each page? This is based in terms of attaching listeners to each of the buttons. Does each button "dontNeed" require a separate ID or will attaching the non unique id to a listener use all of them?
A:
If I have this same button on many pages, does it require a unique ID for each page?
That depends on where and how you are calling findViewById() to retrieve the widget. The widget ID must be unique enough that, when you call findViewById() on something (the activity, the ViewFlipper, a child container within the ViewFlipper, etc.), that you are guaranteed to get your desired widget back.
will attaching the non unique id to a listener use all of them?
You do not attach an "id to a listener", "non unique" or otherwise. You attach a listener to a widget.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: FetchXML Greater Than I am using FetxhXML and I want the condition to be greater than a certain number of hours.
This is what I have:
string groupby1 = "<fetch distinct='false' mapping='logical' aggregate='true'>" +
"<entity name='opportunity'>" +
"<attribute name='opportunityid' alias='opportunity_count' aggregate='countcolumn' />" +
"<filter type='and'>" +
"<condition attribute='new_leadstatus' operator='eq' value='100000000' />" +
"<condition attribute='new_emailedtorsm' operator='eq' value='false' />" +
"<condition attribute='ownerid' operator='not-null' />" +
"<condition attribute='createdon' operator='last-x-hours' value='1' />" +
"</filter>" +
"<attribute name='ownerid' alias='ownerid' groupby='true' />" +
"<link-entity name='systemuser' from='systemuserid' to='ownerid'>" +
"<attribute name='internalemailaddress' alias='internalemailaddress' groupby='true' />" +
"</link-entity>" +
"</entity>" +
"</fetch>";
So basically on the createdon condition I would want it to be greater than 1 hour or greater than the last x hours. Is this possible?
A: You'll need to use the on-or-before condition and insert your own DateTime that is one hour before the current time, like so:
string groupby1 = string.Format(@"
//snip...
<condition attribute='createdon' operator='on-or-before' value='{0}' />
//snip...
", DateTime.Now.AddHours(-1).ToUniversalTime().ToString("u"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best practices for drawing dynamic UITableView row height Possibly a duplicate but I couldn't find a specific question on SO, so here it is.
I'm curious about dynamically changing heights for all rows, typically, because you don't know the length of an NSString that's used for a label.
I know you must use this delegate method to change the row heights:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
The problem is this delegate method is called BEFORE the cell is created (i.e. called before cellForRowAtIndexPath).
So, what I've thought of is to create a mock cell in viewWillAppear and a method that adds cell heights to an array that maps to the table view's data source (which in my case is also an array).
viewWillAppear implements this one important method to get the height:
[NSString sizeWithFont: constrainedToSize: lineBreakMode:]
Then in heightForRowAtIndexPath I can return the cell height like so:
//cellHeights is an ivar populated in viewWillAppear
return [[cellHeights objectAtIndex:indexPath.row] floatValue];
I was wondering if there was a better way to dynamically change the row height?
I realize this will degrade performance for a large number of rows (greater than 1000, I believe). But in my case, my rows won't ever come close to that number. So the performance hit is negligible.
Thanks in advance!
A: Great question! In fact, I did something similar in some of my applications.
I can think of a couple of alternatives, but all of these are along the same theme. You could also just to use sizeWithFont: inside of heightForRowAtIndexPath: and do away with the array. In that case, you might take a performance hit for recalculating the size each time, if that operation is expensive.
You could do "lazy loading" of the cellHeights array inside of heightForRowAtIndexPAth: so it might look something like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([cellHeights objectAtIndex:indexPath.row] == nil) {
... calculate height and store it in the array at the correct index...
}
return [[cellHeights objectAtIndex:indexPath.row] floatValue];
}
The advantage I am thinking of here is that you will only calculate the heights for cells that are definitely going to be loaded. If you do the calculation in viewWillAppear, I guess you end up doing it for every cell, regardless of whether it is displayed?
Finally, you could put the size in your data model itself. If it is, for example, an array of strings, you could make a class that has two properties: a string and a "representationSize" property. Then you can recalculate the size of the string each time the value of the string is changed. Then, there would just be one array, not two, that maps onto your data source, filled with a data class containing both the string and display size of the string, and the value would be calculated when the string changes, not at all once when the view appears.
Anyway, I would love to hear some comments about these various approaches.
A: Matthew's idea of putting the height in the data model sounds interesting. Here's another answer that proposes a very similar solution: How can I do variable height table cells on the iPhone properly?
A: I have too problem in my UITableView,when I scroll tableview (on 3gs iPhone). I saw a lot of lags. So i open time profiler (very good tool for optimization) and problem was when I call function sizeWithFont. The best solution for resolve this problem is call sizeWithFont in constructor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: onfocus, type, outfocus, count, deactive after time period I would like to have such a jQuery when a user can click in a text input box, where they type it appears in 'real-time' in a div [this part, I have no problem with] - however, I would like to offer the user to outfocus from the text input box for upto, say, 5 seconds. If the user re-onfocus they can continue writing and it appears 'real-time', otherwise if more than 5 seconds later, the 'realtime' function disappears (but can continue writing).
When the realtime function disappears - I would like an edit button to appear next to the div where they can edit it in the div. I guess a hidden input would be required.
I guess what I'm looking for is similar to how Wordpress allows you to write in a page title, where the title forms part of the URL.
For the realtime part, I know I could do the following (not sure though on the logic and time counting once the focus has been lost):
$('#entry').keyup(function(){
// if < 5 sec
var entry = $('#entry').val();
$('#display').html(entry+'<input type="button" id="edit" value="Edit">');
$('#hidden-display').val(entry); // hidden input
// if > 5 sec
// do nothing realtime; add edit button
$('#display').html($('#hidden-display').val()+'<input type="button" id="edit" value="Edit">');
});
Then for editing:
$("#edit").click(function(){
$('#display').html('<input type="text" id="update" name="update" value="'+$('#hidden-display').val()+'"><input type="button" id="save" value="Save"><input type="button" id="cancel" value="Cancel">')
});
$("#cancel").click(function(){
$('#display').text($('#hidden-display').val());
});
$("#save").click(function(){
var entry = $('#update').val();
$('#display').html(entry+'<input type="button" id="edit" value="Edit">');
$('#hidden-display').text(entry);
});
I know the above isn't quite right, as should be adding in some live parts, the part i'm struggling with is the outfocus count, then checking that when back in focus.
Any help would be appreciated, any solution would be highly welcomed - especially if far more efficient than my current working draft :)
A: You could go and save the current timestamp on the blur event and check back on the focus event:
$("#entry").blur(function(){
$(this).data("blurtime", (new Date()).getTime());
}).focus(function(){
var timediff = (new Date()).getTime() - $(this).data("blurtime");
if(timediff > 5000)
//do something
});
Alternatively you could go the native JS way using setTimeout() and clearTimeout().
Also, instead of adding a button as plain html, I highly recommend having the edit button outside of the #display div.
<div id="display"></div>
<input type="button" id="edit" value="Edit" style="display:none">
$("#edit").show();
Of course you can add a wrapper div around them, if you need to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding a Time/Date stamp to photos I have a bunch of photos at home that I'd like to add a time and date stamp to based on the file properties.
I'll be writing this as a WPF application but does anyone have sample c# code on how to add text to a .jpg file in the bottom right hand corner of the photo?
I know there are a couple of libraries out there but would like to actually have the c# code itself as I can see a few applications of that here at Muppet Labs plus it'd be nice to learn this also.
EDIT
Thanks to Andy for the link. I have posted my code here for others to see the solution.
System.Drawing.Image img = System.Drawing.Image.FromFile("Brush Tail Possum.jpg");
System.Drawing.Image imgOverlay = System.Drawing.Image.FromFile("overlay.png");
Graphics gr = Graphics.FromImage(img);
Font font = new Font("Times New Roman", (float)12, System.Drawing.FontStyle.Regular);
System.Drawing.Color color = System.Drawing.Color.FromArgb(255, 255, 255, 255);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.DrawImage(imgOverlay, new System.Drawing.Point(img.Width - 78, img.Height - 25));
gr.DrawString(DateTime.Now.ToShortDateString(), font, new System.Drawing.SolidBrush(color), new System.Drawing.Point(img.Width - 40, img.Height - 15), stringFormat);
MemoryStream outputStream = new MemoryStream();
img.Save("Brush Tail Possum2.jpg");
Overlay.png is a small image that sits under the text and aids in readability.
A: Found this question that has example code for adding a watermark to jpgs any use?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How does a program know how much memory to release? I suspect the answer to my question is language specific, so I'd like to know about C and C++. When I call free() on a buffer or use delete[], how does the program know how much memory to free?
Where is the size of the buffer or of the dynamically allocated array stored and why isn't it available to the programmer as well?
A: Each implementation will be different, but typically the runtime allocates a bit more than asked for, and uses some hidden fields at the start of the block to remember the allocated size. The address returned to the caller is therefore offset a bit from the start of the memory claimed from the heap.
It isn't available to the caller because the true amount of memory claimed from the heap is an implementation detail, and will vary between compilers and platforms. As for knowing how much the caller asked for, rather than how much was allocated from the heap... well, the language designers assume that the programmer is capable of remembering this if needed.
A: The memory allocator that gave you that chunk of memory is responsible for all that maintenance data. Typically it's stored in the beginning of the chunk (right before the actual address you use) so it's easy to access on freeing.
Regarding to your other question: why should your app know about it? It's not your concern. It decouples memory allocation management from the app so you can use different allocators (for performance or debugging reasons).
A: The heap keeps track of all memory blocks, both allocated and free, specifically for that purpose. Typical (if naive) implemenation allocates memory, uses several bytes in the beginning for bookkeeping, and returns the address past those bytes. On subsequent operations (free/realloc), it would subtract a few bytes to get to the bookkeeping area.
Some heap implementations (say, Windows' GlobalAlloc()) let you know the block size given the starting address. But in the C/C++ RTL heap, no such service.
Note that the malloc() sometimes overallocates memory, so the information about mallocated block size would be of limited utility. C++ new[]'ed arrays, that's a whole another matter - for those, knowing exact array size is essential for array destruction to work properly. Still, there's no such thing in C++ as a dynamic_sizeof operator.
A: It's stored internally in a location dependent on the language/compiler/OS.
Sometimes it is available (.Length in C# for example), though that may only refer to how much memory you're allowed to use, and not the object's total size.
A: Usually because the size to free is stored somewhere within the allocated buffer. A common technique is to have the size stored in memory just previous to the returned pointer.
Why isn't such information available to the programmer? I don't really know. I guess its because an implementation may be able to provide memory allocation without actually needing to store its size, and such implementation -if it exists- shouldn't be penalized by the others.
A: It's not so much language specific. It's all done by the memory manager.
How it knows depends on how the memory manager manages memory. The general idea is that the memory manager allocates more memory than you ask for. It stores extra data about the allocated blocks of memory in those locations. Thus, when you release the memory, it uses the information stored in those locations (reconstructed based on the given pointer) and figures out how much actual memory to stop managing.
A: Don't confound deallocation and destruction.
free() knows the size of the memory because of some internal magic ("implementation-defined"), e.g. the allocator could keep a list of all the allocated memory regions indexed by their corresponding pointers and just look up the pointer to know what to deallocate; or that information could be stored next to the allocated memory itself in some hidden block of data.
The array-delete expression delete[] arr; does not only deallocate memory, but it also invokes all destructors. For that purpose, it is not sufficient to just know the memory size, but we also need to know the number of elements. For that purpose, new T[N] actually allocates more than sizeof(T) * N bytes of memory, so the array-deleter knows how many destructors to call. All that memory is properly deallocated by the corresponding delete-operator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JavaScript works in WordPress preview, not in the published post I have a JavaScript, which draws some stuff based on user input. I've put the link to the .js file in WordPress header, and I should put <div id="drawstuff"></div> where I want it to show up. So if I put it into a post, it works fine in the preview, but when I publish that post, there's only a note that my browser requires JavaScript :( Please help!
A: I had the same problem and the solutions was that I didn't have a / at the beginning of the links in the header.
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fadein on hover then fade out to orginal state but stay on hover state when onclicked What I have to create is a fade in/out of an image to show the image behind it which has text on it, the user can stay on that button by clicking it. Then it will go back to its orginal state when an other button is clicked on. But while an image has been clicked on the other buttons can be hovered over.
There are 8 images/buttons.
A: Add the following classes to your CSS stylesheet:
*
*A CSS class for the inactive button state:
.buttonInactive { /* your inactive styles here */ }
*A CSS class that makes use of the :hover pseudo-class that will automatically handle the hovering for you without JavaScript:
.buttonInactive:hover { /* your hover styles here */ }
*A CSS class that is for the currently-selected (i.e., most recently clicked button), which will be set via JavaScript:
.buttonActive { /* your active styles here */ }
In your HTML each button should be set as class="buttonInactive". If you test it at this point you should see the hovering working.
Then, in JavaScript, add a handler for clicking on the buttons:
$(document).ready(function() {
$(".buttonInactive").click(function() {
// your code here
});
});
You've tagged your question with jQuery, which makes adding and removing styles very simple. Your JavaScript in the click handler will need to remove the buttonActive class from any other element that might have been active previously (can be done in one line of jQuery) and then add the buttonActive class to the clicked element (only takes one more line of jQuery). Optionally, you may want to remove buttonInactive from the currently active element (and, obviously, put it back when it becomes inactive).
The jQuery you need for this is very basic, so I'll leave it to you to do some googling and figure the rest out yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: UIPickerView as inputView gets messed up on orientation change I'm using a standard UIPicker view as an inputView for a textField in an iPhone application. When the view is loaded in either landscape or portrait, the picker is sized the same as the appropriate keyboard. However, when you rotate the device once inside the view the picker doesn't resize it's height properly, like it does with it's width. I have UIViewAutoresizingFlexibleWidth set. When I tried setting UIViewAutoresizingFlexibleHeight as well the picker gets messed up (choppy graphics, component cuts off) on rotation, though the height is correct! Has anyone figured this out?
A: I found that if you are working with iOS 7 simply add:
pickerView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
This solved the problem for me. The transition isn't very choppy, looks like it "should" look.
A: I found a band-aid:
In didRotateFromInterfaceOrientation: in your hosting viewController, call setNeedsLayout on that picker view. The weird layout glitches are visible during the rotate but clean up at the end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Summing with a column but potentially use another column I have this table
campaignArchive
id campaignID bannerID poolID limitImpressions actualImpressions
-----------------------------------------------------------------------------
1 496 10367 7 12500 205
2 497 10367 7 12500 22860
3 498 10367 7 12500 1525
I need to sum actual impressions to date, which would ordinarily just be:
select sum(actualImpressions) as actuals from campaignArchive
However, if the actualImpressions column value exceeds the limitImpressions column value (as in row 2), I want the limitImpressions column value to be used instead.
Hope that makes sense. Any help appreciated.
A: You'll need to include a case statement.
select
sum(case when actualImpressions > limitImpressions
then limitImpressions
else actualImpressions end) as actuals
from campaignArchive
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is a change required only in the code of a web application to support HSTS? If I want a client to always use a HTTPs connection, do I only need to include the headers in the code of the application or do I also need to make a change on the server? Also how is this different to simply redirecting a user to a HTTPs page make every single time they attempt to use HTTP?
A: If you just have HTTP -> HTTPS redirects a client might still try to post sensitive data to you (or GET a URL that has sensitive data in it) - this would leave it exposed publicly. If it knew your site was HSTS then it would not even try to hit it via HTTP and so that exposure is eliminated. It's a pretty small win IMO - the bigger risks are the vast # of root CAs that everyone trusts blindly thanks to policies at Microsoft, Mozilla, Opera, and Google.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails: adding additional methods to a model for cache retrieval When adding caching to a model in Rails, there is the repetitive nature that looks like the following:
class Team < ActiveRecord::Base
attr_accessible :name
end
Before caching, to retrieve a name, everything was trivial,
team = Team.new(:name => "The Awesome Team")
team.save
team.name # "The Awesome Team"
With caching introduced using memcached or redis I find myself adding methods to my models and it's super repetitive:
def get_name
if name_is_in_cache
return cached_name
else
name
end
end
def set_name(name)
# set name in cache
self.name = name
end
Is there some obvious way that I'm missing to clean this up? I'm caching a lot of fields in different ways and it seems attr_accessible is virtually redundant at this point. How can this be cleaned up?
A: Create a mixin that just provides wrappers around instance_eval. Untested:
module AttributeCaching
def cache(name)
instance_eval(<<-RUBY)
def get_#{name}
if #{name}_is_in_cache
return cached_#{name}
else
#{name}
end
end
RUBY
instance_eval(<<-RUBY)
def set_#{name}(name)
self.#{name} = name
end
RUBY
end
end
Then in your model:
class Team < ActiveRecord::Base
extend AttributeCaching
cache :name
cache :something_else
end
You could probably make your life a lot easier, however, by not naming each of your caching methods differently. Couldn't you do something like get_cached(name) and set_cached(name, value), then your problem suddenly becomes a lot less repetitive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: java.lang.NoClassDefFoundError: com/jogamp/common/type/WriteCloneable jogl 2 in eclipse I am on windows 7 64 bit and using eclipse indigo. I downloaded the latest version of jogl 2 and i have created an eclipse project following this link
https://sites.google.com/site/justinscsstuff/jogl-tutorial-2
this tutorial is old as the jars in the jogl download dont match and i have included all the jars and for each jar set the native libraries directory. I have written a small jogl test program that creates a GLProfile, GlCapabilities and an awt frame. I get this exception:
java.lang.NoClassDefFoundError: com/jogamp/common/type/WriteCloneable
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Caused by: java.lang.ClassNotFoundException: com.jogamp.common.type.WriteCloneable
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 24 more
Exception in thread "main"
seems like im missing a jar..could any let me know what im doing wrong here?
A: Try to add gluegen as well.
For example
<dependency>
<groupId>org.jogamp.jogl</groupId>
<artifactId>jogl-all</artifactId>
<version>2.0-rc11</version>
</dependency>
AND
<dependency>
<groupId>org.jogamp.gluegen</groupId>
<artifactId>gluegen-rt-main</artifactId>
<version>2.0-rc11</version>
</dependency>
A: I am using the jogl-all.jar from Matlab 2014a. The error above disappeared and everything run smoothly when I added the library glugen-rt.jar.
(remember also to -Djava.library.path=/path/to/native/files when you execute your application, in my case this was -Djava.library.path=/Applications/MATLAB_R2014a.app/bin/maci64)
A: I had a similar problem with the JOGL jar files. See here. Also, check out the tutorials on the jogamp wiki (by the looks of it Wade is pretty active on the wiki).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What exactly is a content level merge? What is exactly is a content level merge?
I've heard this term used a couple times in git discussions.
A: A merge between two branches where a different set of files has been changed in each branch is a simple (or "trivial") merge. Git doesn't need to look inside the files to see what to do - it just takes the latest of each.
However, if both merge parents change the same file, then Git must look inside the file to see how to apply both changes. This is a "content level merge". The results may be applied automatically if there is no conflict, or may require manual resolution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Respond y(es) to psftp host key prompt I am creating a script file programmatically and call psftp.exe as follows:
psftp user@hostname.com -pw password -b psftpscript.txt
but it prompts for user input
The server's host key is not cached in the registry. You have no
guarantee that the server is the computer you think it is. The
server's rsa2 key fingerprint is: [ssh-rsa 1024 somekey]
If you trust this
host, enter "y" to add the key to PuTTY's cache and carry on
connecting. If you want to carry on connecting just once, without
adding the key to the cache, enter "n". If you do not trust this host,
press Return to abandon the connection. Store key in cache? (y/n)
I need it to be completely prompt free, automatic.
I tried -batch parameter but it just abandons the connection
A: I had the same problem with running a unattended script in Windows Server 2008's 'sandbox' like environment. I ended up running the following which enters the y at the prompt for you:
echo y | psftp user@hostname.com -l username -pw password -b psftpscript.txt
Hope this helps!
Note: I only had to run the echo y once and removing it for the 2nd run didn't ask for the key to be cached anymore.
A: You can create a file as input containing just a y and carriage return then run
psftp user@hostname.com -pw password -b psftpscript.txt < filename.txt
Thanks to James from http://www.sqlservercentral.com/Forums/Topic281954-9-1.aspx for such a simple solution
A: This doesn't answer your question directly, but provides a possible workaround:
Launch a command prompt as the user who will be running your script and manually accept the certificate. Then upon future connections, you won't have the issue.
Given your need, beyond what has been stated, this may or may not work. I came to this question with the same problem and ended up resolving it using the approach I've just described.
A: When you run it the first time, it will show you your key for the server.
Copy the key and then on your command line, specify your host key like this:
psftp example.com -hostkey 06:15:d4:3b:e4:e8:23:c0:d6:6d:45:47:7e:bd:8d:74 -l yourusername -pw yourpassword -batch
A: In .Net, I found that the above method didn't work quite as expected. The trick was to use .Net's built-in input redirection - and not the < operator. Here's what the code looks like now:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "c:\\psftp.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.Arguments = strIP + " -v -l " + strUsername + " -pw " + strPassword + " -b " + strBatchFilename;
proc.Start();
StreamWriter myStreamWriter = proc.StandardInput;
myStreamWriter.WriteLine("Y\n"); //override the public key question <---
myStreamWriter.Close();
proc.WaitForExit();
proc.Close();
A: I had the problem where I didn't have the permission to delete \ rename file over the remote server and the files contains time stamp.
So I needed to download files by name.
The psftp can't accept params (or any way I was aware of) and I couldn't dynamically change the file names according to the current date.
So, from the batch file which I'm calling the psftp commands I created the commands dynamically and with the file with the relevant time stamp.
I could copy only the today files which is better the then copy everything each time.
cd "C:\Files"
echo cd outbound > C:\SFTP\temp.txt
echo mget file_%date:~10,4%%date:~4,2%%date:~7,2%*.csv >> C:\SFTP\temp.txt
echo quit >> C:\SFTP\temp.txt
echo close >> C:\SFTP\temp.txt
C:\SFTP\psftp user@ftp.address.com -b C:\SFTP\temp.txt
close
exit
The "echo cd outbound > C:\SFTP\temp.txt" cleaned the old file and start writing the content of the new file.
The "echo mget file_%date:~10,4%%date:~4,2%%date:~7,2%.csv >> C:\SFTP\temp.txt" resulted in creating the the command: "mget file_20151008.csv " which downloads all files which starts with "file_20151008..." the next 2 rows just ended the action and the line "C:\SFTP\psftp user@ftp.address.com -b C:\SFTP\temp.txt" execute it.
as results temp.txt looks like this:
cd outbound
mget file_20151008*.csv
quit
close
A: I ended up adding the key to cache by entering 'y' to the prompt. I had to do it only once, and after that no more prompts, it works good.
A: I think it should also be noted that if you are intending to use psftp in an unattended manner that you MUST include the -batch option. This will ensure that psftp does not provide any interactive prompts.
In the event user input would be required, psftp would abort. (e.g. ask user to cache host key, ask for password, etc.)
This will ensure that your process doesn't 'hang' and allow your automation to alert someone that there is an issue.
A: I think there is a problem with your command line.
Usage: psftp [options] [user@]host
Try:
psftp -pw password -b psftpscript.txt user@hostname.com
A: None of the above suggestions worked for me, but I did figure out something that DID work for me.
I made 2 entries in my batch file for it to work.
The first entry causes a connection to cache in the registry.
The second entry will connect automatically because now the hostkey is cached in the registry.
echo y | psftp.exe username@hostname.com -pw password
psftp.exe username@hostname.com -pw password -v -be -batch -b psftp_upload_command.bat
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: style attribute ignored on deployed page The following markup (cleaned up to keep it brief) is generated the same in my VS2010 dev environment and from IIS on my test server (identical text when I right-click and view source from the browser). The IE browser in VS2010 looks as expected with a yellow border. IE running against the test server seems to be ignoring the STYLE completely. IE 8 and 9.0.2 both have the same behavior. Ideas? I don't understand why the same browser and the same markup would render on the screen differently.
<select name="blah" onchange="blah" id="blah" disabled="disabled" class="aspNetDisabled" style="border-color:Yellow;border-style:Double;">
<option selected="selected" value="blah">blah</option>
</select>
Sorry I can't include the pics but I just created my new login and have no points so the site will not allow me to post pics of how these render. Take it from me, VS2010 shows it with a yellow border (as expected) and when I run it from the test server it's got the same default bevel you normally see on the select element.
A: If you hit F12, what mode does IE say it's in?
For your IIS test server, your browser is probably setting its mode to the dreaded Compatibility Mode because you are accessing your page on an intranet. IE assumes that if you are working on an intranet you don't want the latest rendering styles and JavaScript enhancements because they might break your internal tools which you coded for IE 7 (you didn't, but they need to account for those that did). See this flow chart for all of the available modes IE 8 can be put into.
If IE is in compatibility mode you will need to either:
*
*Have IIS send the X-UA-Compatible header on every request (set the value to "edge").
*Add a <meta http-equiv="X-UA-Compatible" content="edge"> near the top of the <head> section of your HTML file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Type inference from right to left I created following code snippet:
class PimpToRight[A](f: A => Boolean) {
def <| (a: A) = f(a)
}
implicit def f2pimp[A](f: A => Boolean) = new PimpToRight(f)
class PimpToLeft[A](a: A) {
def <|: (f: A => Boolean) = f(a)
def |> (f: A => Boolean) = f(a)
}
implicit def a2pimp[A](a: A) = new PimpToLeft(a)
There are right- and left-associative methods available.
Following code works:
((_: Int) > 3) <| 7
((_: Int) > 3) <|: 7
7 |> (_ > 3)
But this does not:
(_ > 3) <| 7
(_ > 3) <|: 7
Is it possible to infer type parameters from right to left?
A: These two issues are related: SI-4773 and SI-1980. Based on these issues, the answer to your question seems to be no. While not directly related to your question, there is a very nice post by Paul Chiusano on making the most of type inference in Scala, which addresses the current state of type inference in Scala and provides some useful advice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What's wrong with this enum lookup map? I have an enum where the reverse-lookup table I created for it returns null for all values. I added an assert after the lookup table is created, and sure enough, it's empty. I feel like this is something simple and obvious that I'm overlooking because I use this exact same structure for all my enums and they work fine.
public enum TerrainType {
ROAD(1),
PLAINS(2),
FOREST(3),
MOUNTAINS(4);
private static final Map<Byte,TerrainType> lookup = new HashMap<Byte,TerrainType>();
private final byte terrainId;
static {
for(TerrainType type : EnumSet.allOf(TerrainType.class)) {
lookup.put(type.getByte(),type);
}
assert lookup.get(1) != null; // <--- THIS ASSERT FIRES, WHY?
}
TerrainType(int id) {
assert id > 0 && id < 128: "ID must be from 1 to 127";
this.terrainId = (byte) id;
}
public static TerrainType get(int id) {
return lookup.get(id);
}
public byte getByte() {
return this.terrainId;
}
}
A: The literal 1 is an integer.
This works.
assert lookup.get(Integer.valueOf(1).byteValue()) != null
Alternatively, you could change your terrainId to be of type int
A: This works fine for me. Note the changes.
I'd recommend not using assert to enforce your contract. Throw an IllegalArgumentException if you get unexpected input.
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum TerrainType
{
ROAD(1),
PLAINS(2),
FOREST(3),
MOUNTAINS(4);
private static final Map<Integer, TerrainType> lookup = new HashMap<Integer, TerrainType>();
private final int terrainId;
static
{
for (TerrainType type : EnumSet.allOf(TerrainType.class))
{
lookup.put(type.getTerrainId(), type);
}
assert lookup.get(1) != null; // <--- THIS ASSERT FIRES, WHY?
}
TerrainType(int id)
{
assert id > 0 && id < 128 : "ID must be from 1 to 127";
this.terrainId = id;
}
public static TerrainType lookupById(int id)
{
return lookup.get(id);
}
public int getTerrainId()
{
return this.terrainId;
}
}
class TerrainTypeDriver {
public static void main(String[] args)
{
for (int i = 0; i < 6; ++i) {
System.out.println(TerrainType.lookupById(i));
}
}
}
A: Basically it's equals(Object) problem.
Quoting Java API:
"if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null"
Try this piece of code:
int a = 1;
byte b = (byte) a;
Byte c = b;
boolean d = c.equals(1);
System.out.println(d);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: problem using django's User authentication model. Uncomprehensible error I want to register users.
So I made a:
class RegisterForm(ModelForm):
class Meta:
model=User #(from django.auth.contrib.User)
now i display that form in a template for the users to fill it and to submit it.
When i do form.is_valid(), i get this validation error: Your username and password didn't match. Please try again.
Does anyone know what can cause this?
i've included the ModelForm, the view that processes the registration form and the template that displays the registration form.
Thank you for your time and kind concern.
MY MODEL FORM
class RegisterForm(ModelForm):
class Meta:
model=User
THE VIEW THAT HANDLES THE REGISTRATION
def register(request):
if request.method=='POST':
form=RegisterForm(request.POST)
if form.is_valid(): # HERE I GET A VALIDATION ERROR
new_user=User.objects.create_user(username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email'],
)
new_user.is_active=True
new_user.first_name=form.cleaned_data['first_name']
new_user.last_name=form.cleaned_data['lastname']
return HttpResponseRedirect(reverse('confirm_registered'),args=[form.cleaned_data['username']])
else:
return render(request,'login/register.html',{'form':form})
else:
raise ValueError()
THE REGISTRATION TEMPLATE
{% extends "store/index2.html" %}
{% block canvas %}
<h3>Registration</h3>
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="/retailstore/login/register.html">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
<tr>
<td>{{ form.first_name.label_tag }}</td>
<td>{{ form.first_name }}</td>
</tr>
<tr>
<td>{{ form.last_name.label_tag }}</td>
<td>{{ form.last_name }}</td>
</tr>
<tr>
<td>{{ form.email.label_tag }}</td>
<td>{{ form.email }}</td>
</tr>
</table>
<input type="submit" value="register" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
A: The form is not validating, but your template is set to always show the same error message about username and password not matching:
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
The reason it is not validating is probably because you are only using some of the fields from the User object, and a ModelForm expects all of the non-editable fields. In the Form's Meta, set
fields = 'username', 'password', 'first_name', 'last_name', 'email'
to tell it to only require those fields.
Also note that passwords are not stored in the database as plain text, so creating a user with a password like that will not work. You need to use user.set_password(form_password).
A: As Dave points out, you always show the same message no matter what the validation error. You should do this:
{% if form.errors %}
{{ form.errors }}
{% endif %}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I include an XML Schema Declaration inside of the same file as the XML data? How do you do it?
Here's my attempt for reference, but I don't think I'm doing it correctly:
<?xml version="1.0" encoding="UTF-8" ?>
<X:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://x.iaesr.com">
<X:element name="track">
<X:complexType>
<X:sequence>
<X:element name="title" type="X:string" />
<X:element name="length" type="X:time" use="optional" />
<X:element name="featuring" type="X:string" use="optional" />
</X:sequence>
<X:attribute name="track_number" type="X:int" use="optional" />
</X:complexType>
</X:element>
<X:element name="cd_collection">
<X:complexType>
<X:sequence>
<X:element name="album" minOccurs="1">
<X:complexType>
<X:sequence>
<X:element name="id" type="X:int" />
<X:element name="title" type="X:string" />
<X:element name="artist" type="X:string" />
</X:sequence>
<!--
The following use of of the schema:choice element makes having a Disk item in the
Album element optional. In either case, it ensures that an album contains either
Disk elements with Track elements in them, or just Track elements alone, but never
both at the same level.
-->
<X:choice>
<X:element name="disk" minOccurs="1">
<X:complexType>
<X:sequence>
<X:element ref="track" minOccurs="1" />
</X:sequence>
<X:attribute name="id" type="X:int" />
</X:complexType>
</X:element>
<X:element ref="track" minOccurs="1" />
</X:choice>
<X:attribute name="label" type="X:string" />
</X:complexType>
</X:element>
</X:sequence>
</X:complexType>
</X:element>
</X:schema>
<cd_collection xmlns="http://x.iaesr.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="joePeaCDCollection.xsd">
<album label="Raisin Records">
<disk id="1">
<id>1</id>
<title>Barenaked Ladies Are Men</title>
<artist>Barenaked Ladies</artist>
<track track_number="1">
<title>Serendipity</title>
<length>00:04:11</length>
</track>
<track track_number="2">
<title>Something You'll Never Find</title>
<length>00:04:57</length>
</track>
<track track_number="3">
<title>One and Only</title>
<length>00:03:47</length>
</track>
<track track_number="4">
<title>Angry People</title>
<length>00:04:01</length>
</track>
<track track_number="5">
<title>Down To Earth</title>
<length>00:03:46</length>
</track>
<track track_number="6">
<title>Beautiful</title>
<length>00:02:35</length>
</track>
<track track_number="7">
<title>Running Out Of Ink</title>
<length>00:03:58</length>
</track>
<track track_number="8">
<title>Half a Heart</title>
<length>00:04:27</length>
</track>
<track track_number="9">
<title>Maybe Not</title>
<length>00:03:00</length>
</track>
<track track_number="10">
<title>I Can I Will I Do</title>
<length>00:03:08</length>
</track>
<track track_number="11">
<title>Fun & Games</title>
<length>00:03:45</length>
</track>
<track track_number="12">
<title>The New Sad</title>
<length>00:02:34</length>
</track>
<track track_number="13">
<title>Quality</title>
<length>00:04:15</length>
</track>
<track track_number="14">
<title>Another Spin</title>
<length>00:04:05</length>
</track>
<track track_number="15">
<title>What A Letdown</title>
<length>00:03:49</length>
</track>
<track track_number="16">
<title>Why Say Anything Nice?</title>
<length>00:03:42</length>
</track>
</disk>
</album>
<album label="Virgin Records">
<id>2</id>
<title>Live From Mars</title>
<artist>Ben Harper</artist>
<disk id="1">
<track track_number="1">
<title>Glory & Consequence</title>
</track>
<track track_number="2">
<title>Excuse Me Mr.</title>
</track>
<track track_number="3">
<title>Alone</title>
</track>
<track track_number="4">
<title>Sexual Healing</title>
</track>
<track track_number="5">
<title>Woman in You</title>
</track>
<track track_number="6">
<title>Ground on Down</title>
</track>
<track track_number="7">
<title>Steal My Kisses</title>
</track>
<track track_number="8">
<title>Burn One Down</title>
</track>
<track track_number="9">
<title>Mama's Got a Girlfriend</title>
</track>
<track track_number="10">
<title>Welcome to the Cruel World</title>
</track>
<track track_number="11">
<title>Forgiven</title>
</track>
<track track_number="12">
<title>Faded/Whole Lotta Love</title>
</track>
</disk>
<disk id="2">
<track track_number="1">
<title>Waiting on an Angel</title>
</track>
<track track_number="2">
<title>Roses from My Friends</title>
</track>
<track track_number="3">
<title>Power of the Gospel</title>
</track>
<track track_number="4">
<title>Pleasure and Pain</title>
</track>
<track track_number="5">
<title>Please Bleed</title>
</track>
<track track_number="6">
<title>The Drugs Don't Work</title>
<featuring>Richard Ashcroft</featuring>
</track>
<track track_number="7">
<title>In the Lord's Arms</title>
</track>
<track track_number="8">
<title>Not Fire, Not Ice</title>
</track>
<track track_number="9">
<title>Beloved One</title>
</track>
<track track_number="10">
<title>Number Three</title>
</track>
<track track_number="11">
<title>Walk Away</title>
</track>
<track track_number="12">
<title>Another Lonely Day</title>
</track>
<track track_number="13">
<title>Like a King/I'll Rise</title>
</track>
</disk>
</album>
</cd_collection>
A: John Saunders is right, there is no predefined way of doing this. But, if you really need this, you can define schema for documents which include schema and instance in one file. Similar approach is used in Web Services Description Language. Here is a condensed idea:
schema.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="instance">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="types" type="Types"/>
<xsd:element name="document" type="Document"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="Types">
<xsd:sequence>
<xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Document">
<xsd:sequence>
<xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
instance.xml
<?xml version="1.0" encoding="UTF-8"?>
<instance xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='schema.xsd'>
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetnamespace="library">
<element name="book">
<complexType>
<sequence>
<element name="title" type="string"/>
<element name="author" type="string"/>
</sequence>
</complexType>
</element>
</schema>
</types>
<document>
<book xmlns="library">
<title>Memoirs</title>
<author>John Smith</author>
</book>
</document>
</instance>
Later you will read schema from <types> and use it to validate content of the <document>.
A: There is no general way to do this, as it is generally a bad idea. Even though you may have seen this with a DataSet, "don't try this at home".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: HTML Textbox Input Tooltip?
Possible Duplicate:
How do I make an HTML text box show a hint when empty?
A very simple question. I would like to place a tooltip within a Textbox similar to the StackOverflow log in. I want the word discount on the textbox value and when the user enters a new value, the word "discount" disappears from the Textbox.
Can I do this by myself using events like OnBlur, OnChange, etc (I don't know which)? Or there is something around that is already done?
Thanks
A: As said by rudeovski, you can use placeholder in modern browsers.
But for the older one, you'll need a javascript/jQuery fallback.
Here is a good example:
http://uniquemethod.com/html5-placeholder-text-with-modernizr-and-jquery-fallback
This will generate placeholder fallback for you automaticly. You simply have to write:
<input type="text" id="discount" placeholder="discount" />
Modernizr combined with jQuery will do the rest for you.
Hope this help :)
A: You can use placeholder text for this.
<input type="text" id="discount" placeholder="discount" />
To make it work on all browsers, you need to use jquery/javascript for it. As far as i know, it doesn't work in IE.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: rmysql match numbers in a list I'm trying to do a query in rmysql to get data from a db. I have a list of idNumbers in a column that I want to match and pull records for from a database.
R data frame: df1
idNumColumnInR saleAmt
345 22.34
456 44.53
678 77.87
... ...
I think it would be something like to go from db -> R:
select * from dataBase where idNum in (df1$idNumColumnInR).
I could just use a for loop and go thru each row of the column but was curious if there's a better way.
A: You don't need to use a loop to use paste().
For example:
df1 <- data.frame(idNumColumnInR=c(345,456,678),
saleAmt=c(22.34,44.53,77.87))
qry <- paste("SELECT * from dataBase where idNum in (",
paste(df1$idNumColumnInR, collapse=","),")" )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Storing Undo and Redo information to the database? I've been wondering about this for a while and I haven't yet come up with a solution for it. On MySQL, I'd create a TRIGGER to automate saving revisions when changes happen and persist change values to the database to track revisions.
The question I have now is: how I can implement this in a more generic sense across most of my models in Django? Right now, I have just over 20 models and it's quickly growing. Generating objects to store all of these items will multiply my models by at least 2 and doesn't seem to be too optimal.
Is there a way I can automate this and make it a bit smarter and less cumbersome?
A: Check out django-reversion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: sql script to drop old versions of stored procedures and functions I am looking to write a sql server script to achieve the following in a sql server 2008 database.
I have a number of functions and stored procedures with the following names:
*
*prSP_GetItem.1.0.0
*prSP_GetItem.1.1.0
*prSp_GetItem.1.2.0
As you can see a version number is appended to them.
Each time a new version of the application is released, new functions/stored procedures are created with the new version number.
What I would like to do is write a generic script to remove all old version of a function or stored procedures. So lets say current version is 1.2.0, all functions and stored procedures ending in a version number before this eg. 1.0.0, 1.1.1 etc should be dropped.
Any tips or ideas how I might write a script to achieve this?
A: You can use this as starting point and see how far it can take you. Run it against your DB and post your observations. The last select only lists the SQL statement in the last column. Nothing gets executed actually. Verify the output very carefully.
;With RawData As
(
SELECT
name
, SUBSTRING(name, 1, CHARINDEX('.', name) - 1) AS BaseName
, CAST(REPLACE(SUBSTRING(name, CHARINDEX('.', name), LEN(name) - CHARINDEX('.', name) + 1), '.', '') AS INT) AS IntVersion
FROM
sys.objects
WHERE
type = 'P'
AND
CHARINDEX('.', name) > 0
AND
ISNUMERIC(REPLACE(SUBSTRING(name, CHARINDEX('.', name), LEN(name) - CHARINDEX('.', name) + 1), '.', '')) = 1
)
,GroupedData As
(
SELECT
BaseName
, MAX(CAST(REPLACE(SUBSTRING(name, CHARINDEX('.', name), LEN(name) - CHARINDEX('.', name) + 1), '.', '') AS INT)) AS IntVersion
FROM
RawData
GROUP BY
BaseName
)
SELECT
*
, NULLIF(ISNULL(GD.BaseName, ''), ISNULL(GD.BaseName, '-')) + 'DROP PROCEDURE [' + Name + ']' as SQLs
FROM
RawData RD
LEFT JOIN
GroupedData GD
ON
RD.BaseName = GD.BaseName
AND
RD.IntVersion = GD.IntVersion
--WHERE
-- GD.BaseName IS NULL
ORDER BY
RD.BaseName
, RD.IntVersion
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get string from url example: domain.com/THESTRING Please some one explain to me how it works and how to do it.
A: PHP has a function just for this: parse_url().
$parts = parse_url('domain.com/THESTRING');
$path = $parts['path'];
That wil get the part that you want
A: Yet another way:
echo strstr(str_replace('://', '', 'domain.com/THESTRING'), '/'); // THESTRING
EDIT: This should get you started.
A: Could also use below if you want the current URI:
$_SERVER["REQUEST_URI"]
A: Make sure your server support Mod_Rewrite
I opened a .htaccess in the public_html directory.
Then turned on the Mod_Rewrite by this command:
RewriteEngine on
Then I write a new law:
RewriteRule (.*)\.html$ index.php?link=$1
Thats bicycly mean that every url that ends with .html will redirect to index.php
Then in index.php I get the URL link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Paypal orders not going through to Magento We have noticed that some customer orders never made it through to magento, but they did go through Paypal. This used to happen when an order would go through a payment review, the payment would be cleared by Paypal after the review was completed, but Magento would never clear it. Is there a reason why some orders are completed on Paypal?s end, but never make it through to Magento?
A: Sounds like your missing the Callback IPN Url within Paypal itself.
http://www.magentocommerce.com/wiki/3_-_store_setup_and_management/payment/paypal_standard_payments_setup_with_ipn
http://www.magentocommerce.com/knowledge-base/entry/setting-up-paypal-for-your-magento-store
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exception handling continue on error and then rethrow //Assume list1 and list2 are populated with states as 2
foo (List<Class1> list1, List <Class1> list2) {
boolean error = false;
try {
operate on list1
} catch (Exception e) {
error = true;
//Modify list1 objects to state 1
}
try {
operate on list2
} catch (Exception e) {
error = true;
//Modify list2 objects to state 1
}
//What are the problems and what is the best practice for this
if (error)
throw new Exception(…); //How should i really rethrow the exception
}
A: The main improvement I'd make is to store all exceptions that occur and make them available somehow, somewhere. Otherwise, it seems fine.
To the skeptical, it's not really abnormal to want to complete some work even when an exception happens. Batch processing is a pretty typical case.
A: Nothing technically wrong with it, other than getting the throws clause correct, etc. You could even save one of the caught exceptions and re-throw it.
Not clear why you'd want to do this, but I've done weirder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Number of words preceding a particular word While indexOf(the) in java gives me number of characters preceding "the" in the sentence One day I saw the beautiful bird, I would like to know the way of getting the number of words preceding it. For example, the output for the given sentence would be 4!
Thank you.
A: The simplest way to do this is to count the space characters preceding "the".
One day I saw the
^ ^ ^ ^
There are 4 spaces, so there are 4 words.
Of course, you might have to add some special handling for multiple spaces between words or punctuation marks.
A: Have a look at java.util.Scanner
Scan and count the words until you hit the
EDIT: very simple example (and not tested ;-)
public static void main(String args[]) {
System.out.println(indexOfWord("One day I saw the beautiful bird", "the"));
}
private static int indexOfWord(String input, String word) {
Scanner s = new Scanner(input);
Pattern p = Pattern.compile("\\S*");
int count = 0;
while (s.hasNext(p)) {
if (word.equals(s.next(p)))
return count;
count++;
}
return -1;
}
A: You must fist split the string into words, then you can find the index of the word.
public int indexOfWord(String sentence, String word) {
return Arrays.asList(sentence.split("\\s+")).indexOf(word);
}
If you need a more efficient approach, see the Scanner pointed by Sascha.
A: Use String.split() using a space as the delimiter. Then count the number of elements in the returned array before you get to the word.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Installing mapnik on Windows XP fails with the message "ImportError: DLL load failed: The specified procedure could not be found." I'm trying to install mapnik on Windows XP.
After diligently following the instructions on their website (http://trac.mapnik.org/wiki/WindowsInstallation), it fails with the message:
File "<stdin>", line 1, in <module>
File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line 43, in <module> from _mapnik import *
ImportError: DLL load failed: The specified procedure could not be found.
I tried the OSGEO4W installer as well, which is no more successful but before displaying the same error message also produces a pop-up saying:
"The procedure entry point xmlCtxtReadMemory could not be located in the dynamic link library libxml2.dll."
The Trouble Shooting suggestions highlighted a couple of possible missing dlls. I installed both of those but failed to resolve the problem.
Dependency Walker identified a further three missing dlls, which I also installed, and yet still without solving the problem.
Any suggestions hugely appreciated!
A: This is quite an old thread. However I just ran into the same problem and was able to solve it with different hints which I found across the web.
*
*I had to make sure that I have the 32bit version of Python. I used Windows x86 MSI Installer (2.7.2)
*I set the PATH variable for Python: C:\Program Files (x86)\Python27
*I downloaded and installed Mapnik v2.2.0 Windows 32 bit Package (so no SDK version)
*I set the PATH variables for the lib and the bin folder in this order: C:\Program Files\mapnik-v2.2.0\lib;C:\Program Files\mapnik-v2.2.0\bin (here comes the important part: make sure you put these two entries at the very beginning of the path variable as stated by zvolsky at https://github.com/mapnik/mapnik-packaging/issues/109)
*Make sure you have the libxml2.dll in your c:\windows folder as mentioned by Joan Natalie at Installing Mapnik 2.2.0 in windows 7 with Python 2.7 I just copied the dll file from my mapnik install folder C:\Program Files\mapnik-v2.2.0\lib
After that I was able to execute the command "import mapnik" without any issues. I was also able to execute the python demo as stated here at number 5: https://gist.github.com/springmeyer/5651701
So I guess I had two problems. First the fact that I was somehow missing the libxml2.dll file and second that because I put the mapnik entries in the PATH variable at the end, python somehow took a wrong one since there are many of the same dll's on my system.
Hope I could provide the missing solution here.
A: Try installing libxml / libxml2 for windows. Seems you might be missing that as a dependancy or yourl libxml2.dll may be out of date. zlatkovic.com is the place for windows binaries of libxml:
libxml(2)
Downloads here: ftp://ftp.zlatkovic.com/libxml/
A: I had the same problem (on windows server 2012 R2).
i searched a lot on google and i tried all of the above answers.
btw today mapnik is fixed the libxml2.dll by linking with static address.
And Finally my problem was using double quotation in first and last of the mapnik lib path("C:\mapnik-v2.2.0\lib") in PATH variable!!!!
you should NOT use double quotation in system environment variables.
i changed "C:\mapnik-v2.2.0\lib" to C:\mapnik-v2.2.0\lib and every thing works fine. ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Simple Vimeo Regex: How to identify valid video urls but ignore user urls? This link is good:
http://vimeo.com/22669590
This link is bad:
http://vimeo.com/gopro or http://vimeo.com/user1234
Here's my current Regex: /vimeo\.com\/([^&]*)/i
How can I catch the good (which this regex does) but avoid the bad (which this regex does not)?
A: It appears videos only have numeric value. Why not just match where entire string is numeric after the vimeo.com/
/vimeo\.com\/\d+$
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to undraw, hide, remove, or delete an image from an html canvas? this.context.drawImage(myimage, 0, 0);
Putting the image on the canvas is pretty well covered all over the web.
But how do I remove it after it's there?
A: Option 1:
Draw a rectangle over it of the same color as the background.
Option 2 (works for non-trivial background, but slower):
Get the pixel data from the canvas before drawing the image, then redraw that pixel data to remove the image.
A: So I came up with a quick and easy way to clear my canvas. I just put my <canvas> tags in between <p> tags with an Id, then each time i needed my canvas cleared I just rerendered my <p> tags by changing the innerHTML, works like a charm.
A: Canvas is an immediate drawing surface. This means that you execute a command on it (drawImage or fillRect) and it does that command, and it doesn't give a damn what has just done. There is no undoing of something.
You had a hard time searching for it because there's no such thing as "removing" for a Canvas. All it knows is that it has some pixels of some color from somewhere. It has no idea where.
To simplify a bit, there are generally two ways:
*
*Clear the entire canvas, and draw everything all over again EXCEPT the one image you do not want drawn
*Use two canvases, one that only has the image and one with all the other stuff. Clear this canvas with clearRect(0,0,width,height) and you're done.
You'll notice in 1. that you will probably have to start keeping track of the things that you draw on canvas if you want some of them selectively removed or repositioned. Instilling object persistence, or rather turning canvas from an immediate drawing surface to a retained drawing surface, is something that a lot of canvas libraries do. If you want to do it yourself, I've written a few tutorails to help people get started.
If you want to look into libraries, take a peek at easel.js. It's pretty learnable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to trace what is causing WordPress error 500? Internal error 500 is such a general error and nothing shows up in the logs under /wordpress/error_log. Is there a way to get a stack trace of where the crash is occurring? In ASP.NET it is so easy because a stack trace, code snippet, and line number all show up in the error page. Any help would be greatly appreciated.
A: Turn on php errors in your php.ini or add this line to your .htacess file in your webroot:
php_flag display_errors on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Error using ChromeDriver when kicked off from teamcity I was having trouble with firefox for my watir-webdriver tests and decided to move over to CHROME. This runs fine local dev box, however when kicked off from team city on our qa server I get the following error:
This is using the same chromedriver as on dev box.
Windows 2003 Server 32 bit
Chrome 14.0.835.186
chromedriver_win32_14.0.836.0.zip ChromeDriver server for win32
Ruby 1.8.7
watir-webdriver 0.3.4
selenium-webdriver 2.7.0
watir-page-helper 0.3.0
Error
[15:57:06]: Started ChromeDriver
[15:57:06]: port=1203
[15:57:31]: .\test\automation\proxy_launcher.cc(89): error: Value of: app_launched
[15:57:31]: Actual: 1
[15:57:31]: Expected: AUTOMATION_SUCCESS
[15:57:31]: Which is: 0
[15:57:31]: Error while awaiting automation ping from browser process
[15:57:56]: .\test\automation\proxy_launcher.cc(223): error: Value of: automation()->GetBrowserWindowCount(&window_count)
[15:57:56]: Actual: false
[15:57:56]: Expected: true
A: I believe your problem is you're running the TeamCity agent as a service, try manually running the agent using the instructions on: http://confluence.jetbrains.net/display/TCD5/Setting+up+and+Running+Additional+Build+Agents#SettingupandRunningAdditionalBuildAgents-StartingtheBuildAgent
A: I'm not using TeamCity or Watir, but I had the same error message from webdriver (using selenium server) running under a windows service.
The solution that worked for me was to run the service under another account and not the system account. Might be worth a try?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create objects using a static factory method? I know Unity can be configured to use a class' constructor to create an instance of a class (like below) but that's not what I want.
container.RegisterType<IAuthoringRepository, AuthoringRepository>();
I would like to configure Unity to use a factory method with the windows identity passed as a parameter (ie: RepositoryFactory.CreateAuthoringRepository(WindowsIdentity.GetCurrent())) when resolving a type of IAuthoringRepository. How do i do this?
A: One way is to have RepositoryFactory implement IRepositoryFactory, then register that. Resolved types can get a factory, then call its CreateAuthoringRepository method. You could create an overload called CreateAuthoringRepositoryForCurrentIdentity if desired, or register an IIdentity dependency of the factory with Unity.
I'd probably just inject a factory and leave the CreateAuthoringRepository method as you have it, then have the clients pass WindowsIdentity.GetCurrent(). That way the identity is always fresh, and you can mock the factory for testing.
Alternately, you can specify a delegate with InjectionFactory:
void Main()
{
using (var container = new UnityContainer())
{
container.RegisterType<IAuthoringRepository>(
new InjectionFactory(c => CreateAuthoringRepository()));
Console.WriteLine("debug - resolving model");
var model = container.Resolve<Model>();
}
}
public IAuthoringRepository CreateAuthoringRepository()
{
Console.WriteLine("debug - calling factory");
return new AuthoringRepository
{ Identity = WindowsIdentity.GetCurrent() };
}
public class Model
{
public Model(IAuthoringRepository repository)
{
Console.WriteLine(
"Constructing model with repository identity of "
+ repository.Identity);
}
}
public interface IAuthoringRepository
{
IIdentity Identity { get; }
}
public class AuthoringRepository : IAuthoringRepository
{
public IIdentity Identity { get; set; }
}
This prints:
debug - resolving model
debug - calling factory
Constructing model with repository identity of System.Security.Principal.WindowsIdentity
That's for Unity 2.0. With earlier versions, see StaticFactoryExtension.
A: Now method InjectionFactory is obsolete. That's why it'd be better to use method RegisterFactory. Below I am showing how the previous code changed. How you see I changed the method CreateAuthoringRepository. Now it is the static method with one param IUnityContainer container
void Main()
{
using (var container = new UnityContainer())
{
container.RegisterFactory<IAuthoringRepository>(CreateAuthoringRepository);
Console.WriteLine("debug - resolving model");
var model = container.Resolve<Model>();
}
}
public static IAuthoringRepository CreateAuthoringRepository(IUnityContainer container)
{
Console.WriteLine("debug - calling factory");
return new AuthoringRepository
{ Identity = WindowsIdentity.GetCurrent() };
}
public class Model
{
public Model(IAuthoringRepository repository)
{
Console.WriteLine(
"Constructing model with repository identity of "
+ repository.Identity);
}
}
public interface IAuthoringRepository
{
IIdentity Identity { get; }
}
public class AuthoringRepository : IAuthoringRepository
{
public IIdentity Identity { get; set; }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: Accessing property of returned object causes EXC_BAD_ACCESS I have a class defined where the top two properties are accessible without issue. Only the UIColor* is a problem. I imagine something isn't being alloc'd, init'd, retained, or released properly and have been changing various things without success. Any help would be grand.
// PieceScore.h
@interface PieceScore : NSObject {
int pieceCount;
BOOL greatMatch;
UIColor *colorMatched;
}
@property (nonatomic) int pieceCount;
@property (nonatomic) BOOL greatMatch;
@property (nonatomic, retain) UIColor *colorMatched;
-(id) initWithPieceCount:(int)pC withGreatMatch:(BOOL)gM withColorMatched:(UIColor*)cM;
@end
// PieceScore.m
@implementation PieceScore
@synthesize pieceCount, greatMatch, colorMatched;
-(id) init {
return [self initWithPieceCount:0 withGreatMatch:NO withColorMatched:[UIColor clearColor]];
}
-(id) initWithPieceCount:(int)pC withGreatMatch:(BOOL)gM withColorMatched:(UIColor*)cM {
self = [super init];
if (self) {
pieceCount = pC;
greatMatch = gM;
colorMatched = cM;
}
return self;
}
@end
It is initialized and returned by another class as follows:
PieceScore* pieceScore = [[[PieceScore alloc] initWithPieceCount:piecesRemoved withGreatMatch:greatMatch withColorMatched:pieceColor] autorelease];
return pieceScore;
NOTE: (pieceColor is a UIColor*)
Then, the UIColor* is used in a method of yet another class:
- (void) labelRender:(UILabel*)label withColor:(UIColor *)color {
// ...
label.textColor = color; // Thread 1: Program received signal: "EXC_BAD_ACCESS".
// ...
}
In the debug view, I can see that color is actually being passed as a UIColor*, but is error-ing out when being assigned to the label's textColor property.
A: You are setting the ivar to an autoreleased variable. Make sure you use the property so that it is properly retained.
Change colorMatched = cM; to self.colorMatched = cM;
A: The ivars in your initWithPieceCount:piecesRemoved:withGreatMatch:withColorMatched need to make sure they retain any values which may be provided as autoreleased. You shouldn't use properties within your init methods,
See here for some discussion
so do a retain on the passed object.
i.e. colormatched = [cM retain];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the difference between stream.end and stream.destroySoon for files in Node.js? I'm writing to a file (a writable steam) and I need to close the file once I'm done. I'm not sure of the difference between these two functions or if I need to call them both. Here's what the documentation says:
stream.end()
Terminates the stream with EOF or FIN. This call will allow queued write data to be sent before closing the stream.
stream.destroySoon()
After the write queue is drained, close the file descriptor. destroySoon() can still destroy straight away, as long as there is no data left in the queue for writes.
A: There is no difference.
From fs.js in the node source:
// There is no shutdown() for files.
WriteStream.prototype.destroySoon = WriteStream.prototype.end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: prevent updates, deletes and truncates on database table I am in the process of creating a sql server 2008 database table for auditing users actions.
Is it possible to create a database table which can only inserted in to - no truncates, deletes or updates allowed on the data in the table. One option I know of is to use a different user with limited rights, but this isnt option for me. So looking at other options?
A: You need to create a TRIGGER that fires on UPDATE and DELETE and throws an error:
CREATE TRIGGER user_action_update on UserActions FOR UPDATE, DELETE AS
BEGIN
RAISERROR ('Cannot modify or delete user actions', 16, 1)
ROLLBACK TRAN
RETURN
END
GO
Source: http://msdn.microsoft.com/en-us/magazine/cc164047.aspx
A: Another way to do that is to Write a trigger creation script for the table and set the action to " INSTEAD OF " which will override the triggering action (unwanted action in your case ) for some other code, or null code.
INSTEAD OF Property
Specifies that the DML trigger is executed instead of the triggering SQL statement, therefore, overriding the actions of the triggering statements.
Here is a link in how to Write the SQL statement for the trigger creation:
http://technet.microsoft.com/en-us/library/ms189799.aspx
Good luck
*
*Adrian
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: what is the benefit in using a wrapper for CURL in php vs using it directly? I can use straight forward
`curl $url -H $headers -d $data`
Or I can use the cURL wrapper functionality and some more wrappers like the ones Zend Framework gives.
I find it easy to use the straight forward approach, am I missing a benefit here? I use cURL for getting JSON responses, so no complex parsing is needed.
A: *
*The API lets you set various options that might not have command-line equivalents.
*Error handling is cleaner since you get an error code and can ask for an error string. Getting the errors from the command's return code and stderr is messier.
Btw your backtick version should probably use escapeshellarg on the $url, $headers and $data especially if any of them depend on user input.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Simplify PHP Script for SQL Query I'm a self-taught, beginner programmer. Recently I've been working on a PHP script to query a database with user-entered keywords. What I've come up with seems much more complicated than it needs to be, so I was wondering if there was a way I could simplify what I wrote. Please let me know if you have any other questions or need any more code. Thank you!
$types = array();
if(!empty($_GET['location_id']) && isset($_GET['location_id'])) $types[] = "groups.location_id = " . str_replace(' ', '%', $_GET['location_id']) . " ";
if(!empty($_GET['season_id']) && isset($_GET['season_id'])) $types[] = "seasons.season_id = " . str_replace(' ', '%', $_GET['season_id']) . " ";
if(!empty($_GET['event']) && isset($_GET['event'])) $types[] = "(`event` LIKE '%" . str_replace(' ', '%', $_GET['event']) . "%' OR `note` LIKE '%" . str_replace(' ', '%', $_GET['event']) . "%') ";
if(!empty($_GET['place']) && isset($_GET['place'])) $types[] = "`place` LIKE '%" . str_replace(' ', '%', $_GET['place']) . "%' ";
if(!empty($_GET['city']) && isset($_GET['city'])) $types[] = "`city` LIKE '%" . str_replace(' ', '%', $_GET['city']) . "%' ";
if(!empty($_GET['state_abbr']) && isset($_GET['state_abbr'])) $types[] = "`state_abbr` LIKE '%" . str_replace(' ', '%', $_GET['state_abbr']) . "%' ";
if(!empty($_GET['weekday']) && isset($_GET['weekday'])) $types[] = "(`weekday` LIKE '%" . str_replace(' ', '%', $_GET['weekday']) . "%' OR `through_weekday` LIKE '%" . str_replace(' ', '%', $_GET['weekday']) . "%') ";
if(!empty($_GET['month']) && isset($_GET['month'])) $types[] = "`month` LIKE '%" . str_replace(' ', '%', $_GET['month']) . "%' ";
if(!empty($_GET['day']) && isset($_GET['day'])) $types[] = "(`day` LIKE '%" . str_replace(' ', '%', $_GET['day']) . "%' OR `through_day` LIKE '%" . str_replace(' ', '%', $_GET['day']) . "%') ";
if(!empty($_GET['year']) && isset($_GET['year'])) $types[] = "`year` LIKE '%" . str_replace(' ', '%', $_GET['year']) . "%' ";
A: Because your WHERE conditions are so different there wouldn't be any way of reducing the number of lines in the code but each line could be slightly shorter. Also you want to pass the submitted variables through mysql_real_escape_string() to prevent SQL injection attacks.
You can prepare all of your variables in a loop so you don't have to run through mysql_real_escape and str_replace on each line:
foreach ($_GET as $key => $val) {
$_GET[$key] = mysql_real_escape_string(str_replace(' ', '%', $val));
}
and I think the call to isset() is slightly redundant so after you've run the loop above each line could look something like this:
if (!empty($_GET['year']))
$types[] = "`year` LIKE '%" . $_GET['year'] . "%' ";
A: Just an idea.. It might make the code more clear and the sql writing a very easy job.
Put this code for testing purposes:
$_GET['event']='jut for test';
$_GET['place']='jut for test';
$_GET['city']='jut for test';
$_GET['state_abbr']='jut for test';
$_GET['weekday']='jut for test';
$_GET['month']='jut for test';
$_GET['day']='jut for test';
$_GET['year']='jut for test';
Then below that, put the actual code:
$queryTmplArr=Array("(`@field` LIKE '%@value%' OR `note` LIKE '%@value%') ",
"`@field` LIKE '%@value%' ","`@field` LIKE '%@value%' ","`@field` LIKE '%@value%' ",
"(`@field` LIKE '%@value%' OR `through_weekday` LIKE '%@value%') ",
"`@field` LIKE '%@value%' ","(`@field` LIKE '%@value%' OR `through_day` LIKE '%@value%') ",
"`@field` LIKE '%@value%' ");
$i=0;
foreach($_GET as $key =>$rawData)
{
$cleanData= mysql_real_escape_string( str_replace(' ', '%', $rawData) ) ;
$queryTmplArr[$i]=str_replace('@value', $cleanData, $queryTmplArr[$i]);
$queryTmplArr[$i]=str_replace('@field', $key, $queryTmplArr[$i]);
$i++;
}
And for testing purpose again:
echo '<pre>';
print_r($queryTmplArr );
This will output this:
Array
(
[0] => (`event` LIKE '%jut%for%test%' OR `note` LIKE '%jut%for%test%')
[1] => `place` LIKE '%jut%for%test%'
[2] => `city` LIKE '%jut%for%test%'
[3] => `state_abbr` LIKE '%jut%for%test%'
[4] => (`weekday` LIKE '%jut%for%test%' OR `through_weekday` LIKE '%jut%for%test%')
[5] => `month` LIKE '%jut%for%test%'
[6] => (`day` LIKE '%jut%for%test%' OR `through_day` LIKE '%jut%for%test%')
[7] => `year` LIKE '%jut%for%test%'
)
Is this okay?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to detect Alt + left key in ToolStripTextBox In C# - WinForms, how to detect Alt + left key when it is pressed in ToolStripTextBox?
A: protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (this.ActiveControl == toolStripTextBox1.Control && keyData == (Keys.Alt | Keys.Left)) {
MessageBox.Show("it's special");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Multidimentional Array Foreach - Display in different tables I currently have the following array:
Array
(
[group] => Array
{
[5] => group1-title
[6] => group2-title
}
[treatment] => Array
(
[5] => Array
(
[16] => Array
(
[title] => title1
[description] => description1
[price] => price1
)
[17] => Array
(
[title] => title2
[description] => description2
[price] => price2
)
[6] => Array
(
[21] => Array
(
[title] => title3
[description] => description3
[price] => price3
)
}
}
}
(In reality the array data is large so it has been cropped to give an example above)
What I am attempting to do is run a foreach loop over the array to enable to me group the data in a pricing table separate by their groups (the array keys [5] and [6])
The end result I am aiming for is the following:
Group1-Title
Title 1 | Desc | Price
Title 2 | Desc | Price
Group2-Title
Title 3 | Desc | Price
I have attempted so far with a foreach loop with an inner foreach loop. That pulls the details and echos out fine - however I can't figure out how to successfully group the data during the foreach loop.
A: Here's one way to go about it. Grab the first array item and use that for the titles. Then loop through the rest of your array using the keys from the first item to display the results. Obviously my display code is quick and dirty, but this should get you started.
foreach($your_array['group'] as $iGroupId => $sTitle) {
echo 'Group: ' . $sTitle . "\n";
foreach($your_array['treatment'][$iGroupId] as $aGroup) {
echo implode('|', $aGroup); . "\n"
}
}
A: $data = array(); //your data array above
//loop through the groups
foreach($data['group'] as $key=>$group){
//echo group header and table start
echo "<h1>$group</h1>";
echo "<table border=1>";
//loop through the data with the corresponding group key
foreach($data['treatment'][$key] as $row){
//echo row data
echo "<tr>";
echo "<td>{$row['title']}</td>";
echo "<td>{$row['description']}</td>";
echo "<td>{$row['price']}</td>";
echo "</tr>";
}
//close table.
echo "</table>";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to develop for the browser, android, and iphone with the core logic written in C++? With some Googling it appears this is possible in iOS, Android using the NDK, and in a browser using Java Web Start or a Java Applet. I understand the GUI for iOS and Android will have to be done using Objective-C and Java. If this is even possible how practical is it when you start to consider debugging support?
A: The Objective-C runtime can be accessed through a C api, so it is possible to write code for iOS and Cocoa using pure C++.
For web development, there is nothing that I know of that is currently available that allows you to deploy code written in C++. This is because C++ is usually compiled into native code, which is very difficult to sandbox and which would imply a security hole. In the future, it may be possible to run such code with Native Client. At the moment it is still in development, but it is already partially functional as an experimental extension to Chromium.
For Android, your code must always run in the Dalvik JVM, but you can incorporate C++ that has been compiled into native code by using the Android NDK.
A: I can't speak for the browser, but I've been doing C++ on iOS for almost a couple years now. Both Fieldrunners and Autodesk Tinkerbox (both of which I work on) are C++. The GUI is also custom C++. There is only a tiny amount of Objective-C so that the C++ code can interface with iOS. The Android version of Fieldrunners also uses the C++ codebase with just a tiny amount of Java, again as glue code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to curve fit data in Excel to a multi variable polynomial? I have a simple set of data, 10 values that increase.
I want to fit them to a polynomial of the form:
Z = A1 + A2*X + A3*Y + A4*X^2 + A5*X*Y+ A6*Y^2
Where Z the output is the set of data above, A1 - A6 are the coefficients I am looking for,
X is the range of inputs (10 of course), and Y for the moment is a constant value.
How can I curve fit to this polynomial and not the standard 2nd order one that is created using 'trendline'?
A: Construct a Vandermonde matrix on your data points, find it's inverse with MINVERSE, then apply this to the vector of Z values with MMULT. This would work for polynomial degree n with n data points.
Otherwise you could try polynomial regression, which will again use the Vandermonde matrix.
More math than Excel really.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it OK to close JDBC connection from another thread on timeout? Because none of the JDBC operations have a concept of timeout, is it advisable to try to close JDBC connection of the overdue operation from the other thread if timeout is exceeded?
I am aware of Statement.cancel method, however it does not seem to work in all cases. Also, the driver that I am using does not respond to interrupts.
I think Connection.close is, unfortunately, the lowest common denominator that can be used to prevent resource leakage in case the database operation had ran amok.
I am aware that when using connection pooling I have to close the real connection object.
A: The best answer is, it depends on what driver you are using. But from the jdbc stack point of view, it should be ok.
A: For derby it should be ok:
http://db.apache.org/derby/docs/10.8/devguide/cdevconcepts23499.html
According to the JDBC spec you can share Connections and Statements with multiple threads
A: I'd wrap that operation in a ThreadPoolExecutor with a timeout. It'll give you more control over what's happening.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it possible to get gateway/router ip in java
Possible Duplicate:
How can I determine the IP of my router/gateway in Java?
I would like to get router/gateway ip in java. I need some thing which is more standard like any libraries i can use. I do not want to curl any site and get the ip.
Thank you
Balaji
A: This looks like it will do what you want. What you really want to do is do a traceroute, which discovers each networking device in turn between you and a destination machine. Since you really only want the next hop, any outside destination will do in your case.
Note that if you know what OS this will be running on, you may be able to do this much easier and faster. For instance, you may be able to get the information you want out of the files in /etc under Linux, or by executing ifconfig.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook Comment not picking right URL I am using facebook comments and providing the url of the page to distinguish. here is the code I am using
<?php $commenturl="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];?>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<fb:comments href="<?php echo $commenturl?>" num_posts="8" width="670"></fb:comments>
My url is www.domain.com/foldername/index.php?etc.
so it shows up the comment feed ok, but once someone posts a comment the url on his wall omits the foldername and directly goes to mangoestv.com/index.php?etc.
what am I supposed to do?
A: I had the same problem was solution was to use htaccess to rewrite url , because it seems that facebook considers domain.com/index.php?var=abc and domain.com/index.php?var=xyz the same
so you should have url like that domain.com/abc and domain.com/xyz
Edit :
info about rewriting url's
http://www.workingwith.me.uk/articles/scripting/mod_rewrite
http://corz.org/serv/tricks/htaccess2.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Extend IOS SimpleURLConnections HTTP POST to Send Description Decodable by CGI Perl I would like to extend the sample ios code called SimpleURLConnections. This sample code can upload a file using HTTP POST. I have enabled my apache web server with a cgi script written in Perl to receive the HTTP POST that addresses the cgi script and successfully uploads the file. The extension I would like to make is to add a title or description of the uploaded file. I have tried to update the multipart form data in the sample code and a corresponding change to my cgi script to transfer this description, but it is failing. The cgi script cannot read in the description using the cgi.pm method called param(). I'm hoping someone can help. Here are the details:
The multipart form data BEFORE my modification looks like the following (NOTE: the SimpleURLConnections routine inserts the image file between the Content-Type and the 2nd boundary on the fly):
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="fileContents"; filename="1234567/TestImage1.png"
Content-Type: image/png
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="uploadButton"
Upload File
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97--
The multipart form data AFTER my modification looks like the following:
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="Title"; title="Hello World"
Content-Type: text/plain
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="fileContents"; filename="1234567/TestImage1.png"
Content-Type: image/png
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="titleButton"
my Title
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="uploadButton"
Upload File
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97--
My cgi script looks like the following:
#!/usr/bin/perl -wT
use strict;use CGI;
use CGI::Carp qw ( fatalsToBrowser );
use File::Basename;
my $upload_dir = "/Library/WebServer/Documents/upload";
my $query = new CGI;
my $title = $query->param("Title");
#if (!$title) {
# die "the title is $title. $!";
#}
if ( !$filename ) {
print $query->header ( );
die "There was a problem uploading your photo (try a smaller file). : $!";
exit;
}
...
open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!";
while ( <$upload_filehandle> ) {
print UPLOADFILE;
}
close UPLOADFILE;
This code works fine and the uploaded file gets written to the upload_dir.
But, if I uncomment that little block of code:
if (!$title) {
die "the title is $title. $!";
}
the script dies with an error that indicates that $title has no value:
[Tue Sep 27 17:09:17 2011] [error] [client 10.0.1.2] [Tue Sep 27 17:09:17 2011] upload.cgi: Use of uninitialized value $title in print at /Library/WebServer/CGI-Executables/upload.cgi line 79.
So, is the problem with my multipart form data, the cgi script, or is it not possible to pass this data in the multipart form data? Is there an alternate way?
Thanks
Ok, after getting help from @AFresh1, I found the problem. The problem was in the details of how the multipart form data was created. First I will show the wrong way.
NSString *title = @"Hello World";
bodySuffixStr = [NSString stringWithFormat: // create the footer for the POST message
@
"\r\n"
"--%@\r\n"
"Content-Disposition: form-data; name=\"titleButton\"\r\n"
"%@\r\n\r\n"
"--%@\r\n"
"Content-Disposition: form-data; name=\"uploadButton\"\r\n"
"\r\n"
"Upload File\r\n"
"--%@--\r\n"
"\r\n",
boundaryStr,
title,
boundaryStr,
boundaryStr
];
Now the correct way (a very subtle change in the 7th line - moved the CR/LF):
NSString *title = @"Hello World";
bodySuffixStr = [NSString stringWithFormat: // create the footer for the POST message
@
"\r\n"
"--%@\r\n"
"Content-Disposition: form-data; name=\"titleButton\"\r\n"
"\r\n%@\r\n"
"--%@\r\n"
"Content-Disposition: form-data; name=\"uploadButton\"\r\n"
"\r\n"
"Upload File\r\n"
"--%@--\r\n"
"\r\n",
boundaryStr,
title,
boundaryStr,
boundaryStr
];
A: I believe the content goes in the space after the header
and before the next boundary not in a title attribute. The part header being everything after the boundary and before the blank line.
If you are want to get "Hello World" into $title using $query->param('Title') I think you will need something more like this (note that Content-type defaults to text/plain):
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
Content-Disposition: form-data; name="Title"
Hello World
--Boundary-D4AFFBA9-AD92-4697-9184-7BDA128C3B97
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: initializing static array problem I am making a server-client and the client repeatedly calls the server files. I am supposed to save the message the client sent in a char array. In the server files, each time the client sends something the char array (static variable) gets overwritten with what it is assigned to in the function of that file. How do I initialize the static variable char array to all '\0' before going into the function in the file? Is that the right thing to do in the first place? I feel silly going char array[100] = 'dddddddddd... Plus, the length value is unknown.
Any help would be appreciated.
A: What language are you using? I'm not too familiar with server programming, but a lot of languages adopt syntax from C, and in C it would be static char array[100] = {0};.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you allow a webapp to add users to the system? In my app, i have something called "groups" which any user can create. The user can then add members to this group. Now this member could be already registered in the system or is a totally new to the system. For "in the system" users, it is easy but for "not yet in the system" my dilemma was whether to pre-register the new user and send the user an email saying all the details of what happened.
Now, the admin could have misspelled the members email and it went to the wrong email address. So for the new user who just received email, they might think the system is sending spam by auto-registering them.
I was thinking should it be mandatory for the user to be pre-registered before the admin could add to the group?
One option is when the admin adds new users(not yet in the system) to the group, the user's email is added to the group but there is no email sent to the new user. The user when willingly registers using the same email, then the user is already part of the group.
Now there are multiple options how the webapp treats the new email addresses
*
*If the email address does not exist, then create a new user, send an activation link with temporary password to the email address
*The webapp ignores the email address and notifies the Team admin to have the user pre-register prior to getting added to the team.
1 is more convenient and a better user experience but it has potential for someone to abuse the system for spamming
2 Is safe as the team admin and the member have already communicated prior to joining into the webapp, they register and then the admin can add the user as its own team member.
How do webapp handle these kind of situation? What is the best practice?
A: Without more details its hard to answer, but if users can add them selves to a system what is the value of admins?
I would advise against that, it just violates most tenants of security. If the users can be preregistered than you have some information about them. I would let the admins add them to the system with the known email address. When the user goes to register them self, if the email is not found send a notice to an admin, who can decide whether to add the user or fix the typo. The typo should be the rare occurrence (not the norm), so users should be able to activate themselves immediately most of the time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multicast message on same host using boost::asio I'm implementing sender/receiver applications to talk multicast on the same host.
In my constructor, I have the following code to setup the socket.
boost::asio::ip::udp::endpoint listenEndpoint(listenAddr, mcastPort);
m_socket.open(listenEndpoint.protocol());
m_socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
m_socket.set_option(boost::asio::ip::multicast::enable_loopback(true));
m_socket.set_option(boost::asio::ip::multicast::hops(1));
m_socket.bind(listenEndpoint);
// Join the multicast group
m_socket.set_option(boost::asio::ip::multicast::join_group(mcastAddr));
m_socket.async_receive_from(boost::asio::buffer(m_data, MAX_PTP_MSG_LENGTH),
m_senderEndpoint, boost::bind(&PtpIpc::HandleReceiveFrom, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
Where listenAddr is 0.0.0.0.
My sending method code is as follows:
m_socket.async_send_to(boost::asio::buffer(data, size), m_remoteEndpoint,
boost::bind(&PtpIpc::HandleSendTo, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
Where m_remoteEndpoint is multicast address 224.0.1.129 and muticast port 320.
Application A doesn't seem to receive multicast messages from Application B and vice versa when both are on the same host. But if I move Application B to another machine on the same subnet... then Application A hears multicast message and reply back to Application B, which can also receive the reply message from Application A. I've enabled loopback and also set the socket reuse_address option. What am I missing?
A: What happens when you remove the loopback option. I've had a similar issue and removing that fixed it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Remotipart with Rails 3.1 - forms always submitted as HTML instead of JS In Rails 3.1 I'm submitting forms with attachments via paperclip and remotipart.
I want my forms to submit via ajax but they are submitting via html.
It was working right in 3.0 but seems to have broken in 3.1. Note that by broken I simply mean that the form always submits via HTML and not JS so I can't render JS which I was doing before. The form still submits and the attachment gets saved, but I can't render JS. And yes, I have :remote => true
Thanks
A: I had the same issue. I restarted my Webrick server, and the request was processed as JS.
A: Remotipart submits forms that have multipart attachments via a hidden iframe (html). Remotipart then wraps the desired json response in a <textarea> wrapper. That is why you are seeing the html respones. You can then call parseJSON on the data.responseText so to get your json resonse object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the right way to use geolocation for desktop PCs? Different geolocation demos show very different results when it comes to detecting my location.
I'm from France, Bordeaux, and expecting at least the city to be shown. Unfortunately, in most cases the city is wrong, and corresponding probably to the location of the servers of the ISP.
Here are the results taken at the same moment from three of top five Google "geolocation ip" results:
http://www.ip2location.com/ - wrong answer
http://www.ipligence.com/geolocation - another, different wrong answer
http://www.infosniper.net/ - right answer
Even if the last one, on the very home page, ensures that I have an error in my SQL syntax, it is at least the only website that displayed the right location among those I've tried.
None of the three websites use HTML5, unlike Google Maps. Google Maps, using HTML5, seems to get the right city too.
*
*How those non-HTML5 websites get a location of a desktop PC?
*Why most of them are totally wrong?
*How to get it right?
A:
How those non-HTML5 websites get a location of a desktop PC?
Looking up your IP address against a database which maps IP addresses to locations.
Why most of them are totally wrong?
Because they have wrong data in the database.
How to get it right?
Ask the user.
A: The only reliable IP to location database is maxmind
Try the following and you will see : http://www.maxmind.com/app/mylocation
This is the same database that adult ads makers are using to show you that the same girl live in your city, even if you move :-)
In the examples you gave, one is simply using an updated database.
A: In reality, Firefox and Google Chrome, and maybe other browsers, can also rely on Wi-Fi triangulation for determining the user's location, if the computer supports Wi-Fi. This is especially the case for most recent laptops, phones, and tablets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disconnecting Sparse SVN Updates From Eclipse I have previously written an eclipse feature that works with eclipse to
*
*sparsely update directories from svn, and
*delete directories from the working copy without deleting them from the repository.
In this way you can pick and chose which subsystems you wish to work with. This feature works with subclipse.
For example, the effect if executed as a command sequence would be:
# check out the libs folder but not its children
svn update --depth empty libs
# check out the libs I am interested in
svn update libs/lib1 libs/lib7
... <work on them> ...
# not interested in lib1 anymore
rm -rf libs/lib1
# update to let libs know that lib1 is no longer checked out
svn update libs
I have recently noticed that subversive is now able to handle updating from svn sparsely. My question is, aside from the command line or writing an eclipse feature as I have, is there a way to disconnect and delete a sparse update from the working copy without deleting from the svn repository through eclipse? Has anyone else dealt with this issue using subclipse, subversive or any other team provider?
I am currently testing with Indigo SR1.
Matt
A: You want to run:
svn up --set-depth=exclude lib1
In Subclipse you can do Team > Update to Version ... and then choose Exclude in the Depth drop-down and check the box to change the WC to the selected depth.
I personally prefer using depth=empty because then the folder still exists and it is easy later to change the folder depth back to infinity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MergeAdapter layout issue in a fragment I'm trying to make a layout in Android with Fragments. I started to use Commonsware's MergeAdapter but I'm having a weird bit of trouble. The layout worked fine before, but now I get this:
http://img856.imageshack.us/img856/2796/layoutbug.png
There are a couple problems: The white strip should have text going all the way across its length. I set the TextView with a white background to make sure the width was being set correctly. The checkbox right below it should also say "Issue?" but it's trying to wrap the text for some reason.
Here is the layout code that is being added:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Instructions" />
<TextView android:id="@+id/tvInstructions" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Instructions go here" android:textSize="32dp" android:background="#FFFFFF"></TextView>
<LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="horizontal" android:paddingTop="24dp">
<CheckBox android:id="@+id/cbIssues" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="0dp" android:text="Issues?" />
<TextView android:id="@+id/tvStation" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight=".5" android:text="Station:" />
<Spinner android:id="@+id/spStation" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight=".5"/>
</LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pending data" />
</LinearLayout>
and here's how I'm inflating it inside the Fragment's onActivityCreated:
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MergeAdapter _adapter = new MergeAdapter();
View observationHeaderView = inflater.inflate(R.layout.observationheader, getListView(), false);
_adapter.addView(observationHeaderView);
I get a feeling it has something to do with how I'm inflating the layout. Any help would be appreciated. Thanks.
A: Don't use match_parent for android:layout_height for something going into an AdapterView, such as your root LinearLayout.
You might also consider temporarily putting your header layout outside the ListView (e.g., in a vertical LinearLayout also holding the ListView) and get it debugged before adding the complication of having it in the ListView.
Beyond that, fire up Hierarchy View (Eclipse perspective or standalone edition) and try to figure out where your layout rules are going wrong.
Also, I am uncertain how well your Spinners will work inside of a ListView on Honeycomb.
A: It appears my problem was with layout_width being match_parent in certain places in my header, when it should have been wrap_content. The following worked:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Instructions" />
<TextView android:id="@+id/tvInstructions" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Instructions go here" android:textSize="32dp" android:background="#FFFFFF"></TextView>
<LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="horizontal" android:paddingTop="24dp">
<CheckBox android:id="@+id/cbIssues" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:text="Issues?" />
<TextView android:id="@+id/tvStation" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight=".5" android:text="Station:" />
<Spinner android:id="@+id/spStation" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight=".5"/>
</LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pending data" />
</LinearLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can you use pattern matching to bind the last element of a list? Since there is a way to bind the head and tail of a list via pattern matching, I'm wondering if you can use pattern matching to bind the last element of a list?
A: The other answers explain the ViewPatterns-based solutions. If you want to make it more pattern matching-like, you can package that into a PatternSynonym:
tailLast :: [a] -> Maybe ([a], a)
tailLast xs@(_:_) = Just (init xs, last xs)
tailLast _ = Nothing
pattern Split x1 xs xn = x1 : (tailLast -> Just (xs, xn))
and then write your function as e.g.
foo :: [a] -> (a, [a], a)
foo (Split head mid last) = (head, mid, last)
foo _ = error "foo: empty list"
A: This is my first day of Haskell programming and I also encountered the same issue, but I could not resolve to use some kind of external artifact as suggested in previous solutions.
My feeling about Haskell is that if the core language has no solution for your problem, then the solution is to transform your problem until it works for the language.
In this case transforming the problem means transforming a tail problem into a head problem, which seems the only supported operation in pattern matching. It turns that you can easily do that using a list inversion, then work on the reversed list using head elements as you would use tail elements in the original list, and finally, if necessary, revert the result back to initial order (eg. if it was a list).
For example, given a list of integers (eg. [1,2,3,4,5,6]), assume we want to build this list in which every second element of the original list starting from the end is replaced by its double (exercise taken from Homework1 of this excellent introduction to Haskell) : [2,2,6,4,10,6].
Then we can use the following:
revert :: [Integer] -> [Integer]
revert [] = []
revert (x:[]) = [x]
revert (x:xs) = (revert xs) ++ [x]
doubleSecond :: [Integer] -> [Integer]
doubleSecond [] = []
doubleSecond (x:[]) = [x]
doubleSecond (x:y:xs) = (x:2*y : (doubleSecond xs))
doubleBeforeLast :: [Integer] -> [Integer]
doubleBeforeLast l = ( revert (doubleSecond (revert l)) )
main = putStrLn (show (doubleBeforeLast [1,2,3,4,5,6,7,8,9]))
It's obviously much longer than previous solutions, but it feels more Haskell-ish to me.
A: Yes, you can, using the ViewPatterns extension.
Prelude> :set -XViewPatterns
Prelude> let f (last -> x) = x*2
Prelude> f [1, 2, 3]
6
Note that this pattern will always succeed, though, so you'll probably want to add a pattern for the case where the list is empty, else last will throw an exception.
Prelude> f []
*** Exception: Prelude.last: empty list
Also note that this is just syntactic sugar. Unlike normal pattern matching, this is O(n), since you're still accessing the last element of a singly-linked list. If you need more efficient access, consider using a different data structure such as Data.Sequence, which offers O(1) access to both ends.
A: You can use ViewPatterns to do pattern matching at the end of a list, so let's do
{-# LANGUAGE ViewPatterns #-}
and use reverse as the viewFunction, because it always succeeds, so for example
printLast :: Show a => IO ()
printLast (reverse -> (x:_)) = print x
printLast _ = putStrLn "Sorry, there wasn't a last element to print."
This is safe in the sense that it doesn't throw any exceptions as long as you covered all the possibilities.
(You could rewrite it to return a Maybe, for example.)
The syntax
mainFunction (viewFunction -> pattern) = resultExpression
is syntactic sugar for
mainFunction x = case viewFunction x of pattern -> resultExpression
so you can see it actually just reverses the list then pattern matches that, but it feels nicer.
viewFunction is just any function you like.
(One of the aims of the extension was to allow people to cleanly and easily use accessor functions
for pattern matching so they didn't have to use the underlying structure of their data type when
defining functions on it.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Forward link in HTML email I need to create a "forward to friend" link in a HTML email that will mimic the forward button on the mail client (ie launch a new window with a pre-filled body), is this possible?
ie:
<a href="forward-action">Forward this email to a friend</a>
If not, what's a simple approach to achieve an as similar as possible result?
ps. I'm aware this is pretty much pointless functionality, it's a request from client.
A: You cannot imitate or initiate the forward action in any mail client (web or desktop) currently on the market today. You have several other options available though:
*
*Offer an online version of your email and include a link to it in your mailto tag:
<a href="mailto:Enter%20an%20email?subject=Your%20Subject%20Line&body=Thought%20you%20might%20be%20interested%20in%20this%20http://www.yourdomain.com">
Forward to a friend</a>
*Include a callout in your email (near the top, preferably) encouraging your recipients to forward the message to their friends.
*Include a link to a web form where your recipients can provide other people's email addresses and send these new email addresses copies of the mailing. (The only issue with this one is that the recipient's address book is not available to them easily, which probably hinders sharing - test to know what your demographic is like).
A: No, this is not possible. At least, I really, really, really hope it's not possible.
Why? Because if it was possible, spammers could put links in e-mails that might cause people to unintentionally forward something. For this reason, forwarding has to be self-instigated by the user with the functionality provided by their e-mail client.
You can have links that use the mailto protocol, like this
<a href="mailto:person@example.com">Link</a>
but this probably isn't what you are looking for. All this does is open the compose mail page with the e-mail field filled in (assuming that their default e-mail client is configured to do so).
You could do something like this:
<a href="mailto:person@example.com?subject=FW: Email Subject
&body=Body of email text
&cc=anotherperson@example.com
&bcc=onemore@example.com">Forward email</a>
And fill out all the fields in the compose mail dialog, but there is nothing you can do that emulates the forwarding functionality.
A: I wonder if your client would go for this:
*
*create a jazzy Forward to a Friend button.
*that button should open up a page on the client site.
*that page should contain an email a friend form.
Much easier to accomplish.
A: If you can extract from HTML email client Subject and Body of the email then you can do this:
<a href="mailto:person@foo.com?subject=..extracted subject...&body=...extracted body...">Forward</a>
One major minus is your whole URI inside 'a' can not be longer then 1024 characters.
Oh and don't forget to URL escape subject and body when composing URI string.
A: Forwarding is not possible.
But I've done some research on the same like as I wanted to promote an event.
I've create this following link,
<a href="mailto:?&subject=Webinar%20on+Leveraging+Artificial+Intelligence+to+Build+Algorithmic+Trading+Strategies&body=Check%20out%20this%20webinar%20on%20developing%20robust%20quantitative%20trading%20strategies%20using%20AI.%20http%3A//bit.ly/1MqTMzg" target="_blank">Spread the word</a>
Hope it helps!
A: I am not a web developer, but just writing web pages for myself. I have stopped directly putting email addresses into html in order to avoid being captured by bots for spamming purpose or whatever it may be.
I wrote a simple js to concat pieces of information together instead:
function ml(name, dom, sub, body) {
var mailname = name + "@";
var nl = "%C2%A0%0A";
var nlcol = "%3A" + nl;
var dom = dom + ".";
var msg = "mai" + "lto:" + mailname + dom + "com" + "?subject=" + sub + "&body=" + body;
window.location.href = msg;
}
in the html:
<a onclick="ml('emailName', 'domain Name', 'subject string', 'greeting in content or any text in content')" >
<input type="button" value="Share with a friend">
</a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Issue with formatting dates in XML file when validating against XSD schema Here is a sample of code for formatting dates for an XML in C#:
Datatable dt = Data.GetMyDataTable();
foreach(DataRow row in dt.Rows)
{
//Create XElement with date
XElement element = new XElement("MyElement", Convert.ToDateTime(row["MyDateColumn"]).ToString("yyyy-MM-dd")));
}
When I look at the XML file in the Visual Studio 2008 XML Visualizer while debugging the application it show the date in the correct format of "2011-09-27".
When I use the following DecisionSoft XML Schema Validator to validate against the XSD file, I get the following error:
cvc-datatype-valid.1.2.1: '20110927' is not a valid value for 'date'.
Why does the XML Visualizer in Visual Studio 2008 show the correct format and the DecisionSoft does not? Also, how can I modify my code to fix the issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simple Php String Matching Pattern I have two strings I need to compare. Let's say for example that the strings are as follows:
$A = "A fox jumped over the log";
$B = "A fox jumped";
Now how would I compare these two strings in PHP in order to return a percentage of character matching.
So I would like my algorithm to return (for the example above)
10/20 or .5 Since $B has exactly half of the matches of the length of $A.
I figured I could iterate through each character, but this seemed a bit tedious and my research indicated that preg_match wouldn't help me much here. Thanks for the help!
A: Try the levenshtein or similar_text functions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Animate a CALayer's bounds w/redraws I am wondering how one might animate a CALayer's bounds so, on each bounds change, the layer calls drawInContext:. I've tried the 2 following methods on my CALayer subclass:
*
*Setting needsDisplayOnBoundsChange to YES
*Returning YES for the + (BOOL)needsDisplayForKey:(NSString*)key for the bounds key
Neither work. CALayer seems determined to use the layer's original contents and simply scale them according to contentsGravity (which, I assume, is for performance.) Is their a workaround for this or am I missing something obvious?
EDIT: And, incidentally, I noticed that my custom CALayer subclass is not calling initWithLayer: to create a presentationLayer - weird.
Thanks in advance,
Sam
A: You can use the technique outlined here: override CALayer's +needsDisplayForKey: method and it will redraw its content at every step of the animation.
A: I'm not sure that setting the viewFlags would be effective. The second solution definitely won't work:
The default implementation returns NO. Subclasses should * call super
for properties defined by the superclass. (For example, * do not try
to return YES for properties implemented by CALayer, * doing will
have undefined results.)
You need to set the view's content mode to UIViewContentModeRedraw:
UIViewContentModeRedraw, //redraw on bounds change (calls -setNeedsDisplay)
Check out Apple's documentation on providing content with CALayer's. They recommend using the CALayer's delegate property instead of subclass, which might be a lot easier than what you're trying now.
A: I don't know if this entirely qualifies as a solution to your question, but was able to get this to work.
I first pre-drew my contents image into a CGImageRef.
I then overrode the -display method of my layer INSTEAD OF -drawInContext:. In it I set contents to the pre-rendered CGImage, and it worked.
Finally, your layer also needs to change the default contentsGravity to something like @"left" to avoid the contents image being drawn scaled.
The problem I was having was that the context getting passed to -drawInContext: was of the starting size of the layer, not the final post-animation size. (You can check this with the CGBitmapContextGetWidth and CGBitmapContextGetHeight methods.)
My methods are still only called once for the entire animation, but setting the layer's contents directly with the -display method allows you to pass an image larger than the visible bounds. The drawInContext: method does not allow this, as you cannot draw outside the bounds of the CGContext context.
For more about the difference between the different layer drawing methods, see http://www.apeth.com/iOSBook/ch16.html
A: I'm running into the same problem recently. This is what I found out:
There is a trick you can do it, that is animating a shadow copy of bounds like:
var shadowBounds: CGRect {
get { return bounds }
set { bounds = newValue}
}
then override CALayer's +needsDisplayForKey:.
However, this MAY NOT be what you want to do if your drawing depends on bounds. As you have already noticed, core animation simply scales the contents of layer to animate bounds. This is true even if you do the above trick, that is, the contents are scaled even if the bounds changed during animation. The result is your animation of drawings looks inconsistent.
How to resolve it? Since the content is scaled, you can calculate the values of custom variables determining your drawing by reverse-scaling them so that your drawing on the final but scaled content looks the same as the original and unscaled one, then set the fromValues to these values, the toValues to their old values, animate them at the same time with bounds. If the final values are to be changed, set the toValues to these final values. You must animate at least one custom variable so as to causing the redraw.
A: This is your custom class:
@implementation MyLayer
-(id)init
{
self = [super init];
if (self != nil)
self.actions = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNull null], @"bounds",
nil];
return self;
}
-(void)drawInContext:(CGContextRef)context
{
CGContextSetRGBFillColor(context,
drand48(),
drand48(),
drand48(),
1);
CGContextFillRect(context,
CGContextGetClipBoundingBox(context));
}
+(BOOL)needsDisplayForKey:(NSString*)key
{
if ([key isEqualToString:@"bounds"])
return YES;
return [super needsDisplayForKey:key];
}
@end
These are additions to xcode 4.2 default template:
-(BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
// create and add layer
MyLayer *layer = [MyLayer layer];
[self.window.layer addSublayer:layer];
[self performSelector:@selector(changeBounds:)
withObject:layer];
return YES;
}
-(void)changeBounds:(MyLayer*)layer
{
// change bounds
layer.bounds = CGRectMake(0, 0,
drand48() * CGRectGetWidth(self.window.bounds),
drand48() * CGRectGetHeight(self.window.bounds));
// call "when idle"
[self performSelector:@selector(changeBounds:)
withObject:layer
afterDelay:0];
}
----------------- edited:
Ok... this is not what you asked for :) Sorry :|
----------------- edited(2):
And why would you need something like that? (void)display may be used, but documentation says it is there for setting self.contents...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Detecting mouse clicks when another program has focus This program works well when the left mouse button is pressed in the window of application, but what i need is that the program also registers when the button is pressed out of the application. I am running under windows 7.
#include <windows.h>
const char g_szClassName[] = "myWindowClass";
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_LBUTTONDOWN:
{
char szFileName[MAX_PATH];
HINSTANCE hInstance = GetModuleHandle(NULL);
GetModuleFileName(hInstance, szFileName, MAX_PATH);
MessageBox(hwnd, szFileName, "This program is:",
MB_OK | MB_ICONINFORMATION);
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
g_szClassName,
"The title of my window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
A: You can try the Windows Raw Input API, which ignores focus.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.