text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Windows Phone - SavePicture - InvalidOperationException Why this code throws InvalidOperationException no metter if I am conncted to PC or not?
MemoryStream ms = new MemoryStream();
picture.SaveAsJpeg(ms, 480, 800);
ms.Seek(0, SeekOrigin.Begin);
MediaLibrary l = new MediaLibrary();
l.SavePicture("test11", ms);
l.Dispose();
ms.Dispose();
I use WP7 RC Tools and XNA
picture is an Texture2D instance
A: Just solved the problem.
I forgot I've played with permissions (manifest file), and accidentaly deleted this permission
<Capability Name="ID_CAP_MEDIALIB" />
A: found this example here: How to: Encode a JPEG for Windows Phone and Save to the Pictures Library
hopefully it helps, it is saving the stream in the IsolatedStorage first then loading from there and saving in the MediaLibrary in the end...
private void btnSave_Click(object sender, RoutedEventArgs e)
{
// Create a file name for the JPEG file in isolated storage.
String tempJPEG = "TempJPEG";
// Create a virtual store and file stream. Check for duplicate tempJPEG files.
var myStore = IsolatedStorageFile.GetUserStoreForApplication();
if (myStore.FileExists(tempJPEG))
{
myStore.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);
// Create a stream out of the sample JPEG file.
// For [Application Name] in the URI, use the project name that you entered
// in the previous steps. Also, TestImage.jpg is an example;
// you must enter your JPEG file name if it is different.
StreamResourceInfo sri = null;
Uri uri = new Uri("[Application Name];component/TestImage.jpg", UriKind.Relative);
sri = Application.GetResourceStream(uri);
// Create a new WriteableBitmap object and set it to the JPEG stream.
BitmapImage bitmap = new BitmapImage();
bitmap.CreateOptions = BitmapCreateOptions.None;
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode the WriteableBitmap object to a JPEG stream.
wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
myFileStream.Close();
// Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);
// Save the image to the camera roll or saved pictures album.
MediaLibrary library = new MediaLibrary();
if (radioButtonCameraRoll.IsChecked == true)
{
// Save the image to the camera roll album.
Picture pic = library.SavePictureToCameraRoll("SavedPicture.jpg", myFileStream);
MessageBox.Show("Image saved to camera roll album");
}
else
{
// Save the image to the saved pictures album.
Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream);
MessageBox.Show("Image saved to saved pictures album");
}
myFileStream.Close();
}
A: If you're connected to the PC, you can't use the MediaLibrary. Instead connect with WPConnect.exe
See this answer for details on how: Unable to launch CameraCaptureTask or PhotoChooserTask while debugging with device
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to z-index parent's background So here is what I'm trying to do.
<div class="gallery">
<a href="link_to_large_image.jpg" style="z-index:2; position:relative; background: url(roundedcorners.jpg) norepeat;">
<img src="thumbnail.jpg" style="z-index:1; position:relative;" />
</a>
</div>
In the gallery I'm trying to place <a> (and its background) tag which is the parent of the <img> tag on top with the z-index. So that way I can add rounded corners to the images.
But looks like no matter what I do it places the background of the <a> (which is the rounded corners) under the image.
Any one know the fix?
Here is the link http://ewsbuild.com/~markdemi/gallery.html
A: If you want rounded corners on images, just do:
.lightbox{
border-radius:15px;
-moz-border-radius:15px;
}
You can change the radius and what elements it affects of course.
A: Place a Div inside the a tag and apply the following styling to each div.
background: url("images/gallery/Giallo-Sienna-Fireplace.jpg") no-repeat scroll 0 0 transparent;
border-radius: 15px;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
height: 153px;
A: The problem is twofold:
*
*When you raise the z-index of the a you raise the z-index of its children too, so that you're effectively not doing anything by doing this. Lowering the z-index of the img tag should do it.
*z-index only applies to positioned elements. So you need to add position:relative to anything you add a z-index to (assuming it doesn't already have a position of course).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android, AsyncTask, check status? This is my code:
In onCreate:
new LoadMusicInBackground().execute();
Then towards the end of my main class I have this code
/** Helper class to load all the music in the background. */
class LoadMusicInBackground extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... unused) {
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(A1,
soundPool.load(GameScreen_bugfix.this, R.raw.a, 1));
soundPoolMap.put(A3,
soundPool.load(GameScreen_bugfix.this, R.raw.b, 1));
soundPoolMap.put(A5,
soundPool.load(GameScreen_bugfix.this, R.raw.c_s, 1));
soundPoolMap.put(A6,
soundPool.load(GameScreen_bugfix.this, R.raw.d, 1));
soundPoolMap.put(A8,
soundPool.load(GameScreen_bugfix.this, R.raw.e, 1));
soundPoolMap.put(A10,
soundPool.load(GameScreen_bugfix.this, R.raw.f_s, 1));
soundPoolMap.put(A12,
soundPool.load(GameScreen_bugfix.this, R.raw.g_s, 1));
soundPoolMap.put(wrong,
soundPool.load(GameScreen_bugfix.this, R.raw.wrong2, 1));
publishProgress("");
Log.v("SOUNDPOOL", "" + soundPoolMap);
return (null);
}
@Override
protected void onProgressUpdate(String... item) {
// text1.setText(item[0]);
}
@Override
protected void onPostExecute(Void unused) {
//Toast.makeText(GameScreen_bugfix.this, "music loaded!", Toast.LENGTH_SHORT).show();
}
}
If the music has not loaded I am getting a nullpointer exception, looking at the docs I see there is a getStatus() but I have tried something like this:
music_load_status=LoadMusicInBackground.getStatus()
and that is not working :(
How do I check if the background task is complete and the music has loaded?
Thanks!
Ryan
A: Create asynctask with listener
class ClearSpTask extends AsyncTask<Void, Void, Void> {
public interface AsynResponse {
void processFinish(Boolean output);
}
AsynResponse asynResponse = null;
public ClearSpTask(AsynResponse asynResponse) {
this.asynResponse = asynResponse;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
@Override
protected Void doInBackground(Void... voids) {
cleardata();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
hideProgressDialog();
asynResponse.processFinish(true);
}
}
And use the Asynctask
new ClearSpTask(new ClearSpTask.AsynResponse() {
@Override
public void processFinish(Boolean output) {
// you can go here
}
}).execute();
I hope this might help some people
A: This is asynchronous programing - you should not check from UI thread, because this means that you are blocking the UI thread ( presumably running check in loop with Thread.sleep()?).
Instead you should be called when AsyncTask is done: from it's onPostExecute() call whatever method in Activity you need.
Caveat: the downside of this approach is that Activity must be active when background thread finishes. This is often not the case, for example if back is prwssed or orientation is changed. Better approach is to send a broadcast from onPostExecute() and then interested activities can register to receive it. Best part is that Activity only receives broadcast if it's active at that time, meaning that multiple Activities can register, but only the active one will receive it.
A: getStatus() checks whether the the AsyncTask is pending, running, or finished.
LoadMusicInBackground lmib = new LoadMusicInBackground();
if(lmib.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(lmib.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(lmib.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
}
If you want to check if your action actually succeeded (i.e. the music was successfully loaded), then you need to come up with your own method that determines that. The getStatus() can only determine the state of the actual thread in AsyncTask.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: Is WPF required to learn XAML I am planning to learn XAML. I wanted to know if I should first learn about WPF and then start XAML?
Please advice.
A: It depends on what your future plans are with XAML/WPF. If you want to get up and running and use it as quick as possible you might consider starting with XAML and WPF at the same time (but note that you can't learn or use WPF just be learning about XAML).
If you plan to work with XAML/WPF for a long time and you will have a lot of WPF projects ahead you probably should consider starting with "pure" WPF.
I belong to the latter camp and it helped me a lot to first get to know the WPF object model, rendering and layout system and then start with XAML, styles, templates etc. For me it made thinks easier to understand (and there is a lot to understand). I understood that XAML is just another way to represent/serialize a .NET object graph that is built as a layer on top.
This is also the way Charles Petzold's book is structured and I think it is the perfect book to start with when you want to get to know WPF really well.
A: Its not a good question but WPF applications are is built on XAML. I started learning from WPFTUTORIAL
A: You will find that you will are likely to learn both at the same time. That said, XAML is a designed to be a mark-up language and is used for several technologies, e.g. WPF and WCF et. al.
As @bitbonk mentions, several books on the subject first give you an introduction to WPF (Dependency Objects, Visual Tree and Logical Tree, Controls, etc) before showing any XAML markup.
A: Whatever you do make sure that your first 2 or 3 applications are throw away apps (not production code). I have seen way too many developers code themselves into a hole when learning to code with WPF. I would recommend studying the MVVM pattern as well. This is critical to building stable WPF applications.
Here are some blog posts I have written that may be of some assistance.
http://tsells.wordpress.com/category/mvvm/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: DbUnit testing a PostgreSQL database using JPA without Hibernate or Spring I'm trying to write a Java EE 6 application using JPA but without using Hibernate or Spring. I used Netbeans to generate the JPA classes, and I created the tables in Postgres, but I am not able to run DbUnit tests in those JPA classes.
I have tried to base my test unit on the example described in this site: http://www.roseindia.net/testingtools/DbUnit/gettingstarted.shtml but it does not work. I keep getting a "java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory" even though I added slf4j to the project libraries in the IDE.
One thing that I find rather odd about the roseindia site example is that it does not seem to have a caller object for the test object created. I am not sure if a caller object is even needed (complete n00b in JavaEE programming, and kind of lost still).
A: If you choose to use entities (java classes annotated with @Entity, representing database records), you have to use some JPA provider. You are not restricted to Hibernate, though.
If you're frightened by JPA, your other option is to use plain JDBC. It is far easier to understand, if it's your learning-exercise application, it might be a good idea to try and see how it works. JPA is built on top of JDBC, so when you think you're ready for it, you'll have a solid knowledge base.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Testing whether an ordered infinite stream contains a value I have an infinite Stream of primes primeStream (starting at 2 and increasing). I also have another stream of Ints s which increase in magnitude and I want to test whether each of these is prime.
What is an efficient way to do this? I could define
def isPrime(n: Int) = n == primeStream.dropWhile(_ < n).head
but this seems inefficient since it needs to iterate over the whole stream each time.
Implementation of primeStream (shamelessly copied from elsewhere):
val primeStream: Stream[Int] =
2 #:: primeStream.map{ i =>
Stream.from(i + 1)
.find{ j =>
primeStream.takeWhile{ k => k * k <= j }
.forall{ j % _ > 0 }
}.get
}
A: If the question is about implementing isPrime, then you should do as suggested by rossum, even with division costing more than equality test, and with primes being more dense for lower values of n, it would be asymptotically much faster. Moreover, it is very fast when testing non primes which have a small divisor (most numbers have)
It may be different if you want to test primality of elements of another increasing Stream. You may consider something akin to a merge sort. You did not state how you want to get your result, here as a stream of Boolean, but it should not be too hard to adapt to something else.
/**
* Returns a stream of boolean, whether element at the corresponding position
* in xs belongs in ys. xs and ys must both be increasing streams.
*/
def belong[A: Ordering](xs: Stream[A], ys: Stream[A]): Stream[Boolean] = {
if (xs.isEmpty) Stream.empty
else if (ys.isEmpty) xs.map(_ => true)
else Ordering[A].compare(xs.head, ys.head) match {
case less if less < 0 => false #:: belong(xs.tail, ys)
case equal if equal == 0 => true #:: belong(xs.tail, ys.tail)
case greater if greater > 0 => belong(xs, ys.tail)
}
}
So you may do belong(yourStream, primeStream)
Yet it is not obvious that this solution will be better than a separate testing of primality for each number in turn, stopping at square root. Especially if yourStream is fast increasing compared to primes, so you have to compute many primes in vain, just to keep up. And even less so if there is no reason to suspect that elements in yourStream tend to be primes or have only large divisors.
A: *
*You only need to read your prime stream as far as sqrt(s).
*As you retrieve each p from the prime stream check if p evenly divides s.
This will give you a trial division method of prime checking.
A: To solve the general question of determining whether an ordered finite list consisted entirely of element of an ordered but infinite stream:
The simplest way is
candidate.toSet subsetOf infiniteList.takeWhile( _ <= candidate.last).toSet
but if the candidate is large, that requires a lot of space and it is O(n log n) instead O(n) like it could be. The O(n) way is
def acontains(a : Int, b : Iterator[Int]) : Boolean = {
while (b hasNext) {
val c = b.next
if (c == a) {
return true
}
if (c > a) {
return false
}
}
return false
}
def scontains(candidate: List[Int], infiniteList: Stream[Int]) : Boolean = {
val it = candidate.iterator
val il = infiniteList.iterator
while (it.hasNext) {
if (!acontains(it.next, il)) {
return false
}
}
return true
}
(Incidentally, if some helpful soul could propose a more Scalicious way to write the foregoing, I'd appreciate it.)
EDIT:
In the comments, the inestimable Luigi Plinge pointed out that I could just write:
def scontains(candidate: List[Int], infiniteStream: Stream[Int]) = {
val it = infiniteStream.iterator
candidate.forall(i => it.dropWhile(_ < i).next == i)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is it possible to mock a type with an attribute using Rhino.Mocks I have this type:
[RequiresAuthentication]
public class MobileRunReportHandler : IMobileRunReportHandler
{
public void Post(MobileRunReport report)
{
...
}
}
I am mocking it like so:
var handler = MockRepository.GenerateStub<IMobileRunReportHandler>();
handler.Stub(x => x.Post(mobileRunReport));
The problem is that the produced mock is not attributed with the RequiresAuthentication attribute. How do I fix it?
Thanks.
EDIT
I want the mocked type to be attributed with the RequiresAuthentication attribute, because the code that I am testing makes use of this attribute. I would like to know how can I change my mocking code to instruct the mocking framework to attribute the produced mock accordingly.
A: Adding an Attribute to a type at runtime and then getting it using reflection isn't possible (see for example this post). The easiest way to add the RequiresAuthentication attribute to the stub is to create this stub yourself:
// Define this class in your test library.
[RequiresAuthentication]
public class MobileRunReportHandlerStub : IMobileRunReportHandler
{
// Note that the method is virtual. Otherwise it cannot be mocked.
public virtual void Post(MobileRunReport report)
{
...
}
}
...
var handler = MockRepository.GenerateStub<MobileRunReportHandlerStub>();
handler.Stub(x => x.Post(mobileRunReport));
Or you could generate a stub for the MobileRunReportHandler type. But you'd have to make its Post method virtual:
[RequiresAuthentication]
public class MobileRunReportHandler : IMobileRunReportHandler
{
public virtual void Post(MobileRunReport report)
{
...
}
}
...
var handler = MockRepository.GenerateStub<MobileRunReportHandler>();
handler.Stub(x => x.Post(mobileRunReport));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: extjs4 how to automatically set grid column width to max width of contents? If you create a grid with no column width or flex attributes, the columns will default to 100px each.
If you then double click on a header separator, the column to the left auto expands to the size of the largest data item in that column.
Is there any way to configure some columns to automatically have that behavior?
A: forceFit: true on your GridView config will force the columns to fill all remaining space.
forceFit : Boolean Specify true to have the column widths
re-proportioned at all times.
The initially configured width of each column will be adjusted to fit
the grid width and prevent horizontal scrolling. If columns are later
resized (manually or programmatically), the other columns in the grid
will be resized to fit the grid width.
Columns which are configured with fixed: true are omitted from being
resized.
A: So I guess forceFit is no longer recommended by sencha, you should try using the autoSize method:
Edit: There you go with an brief example, it works on the first column :)
Ext.create('Ext.grid.Panel', {
title: 'Simpsons',
store: Ext.data.StoreManager.lookup('simpsonsStore'),
columns: [
{ text: 'Name', dataIndex: 'name', width: 150, autoSizeColumn: true },
{ text: 'Email', dataIndex: 'email', width: 150, autoSizeColumn: true, minWidth: 150 },
{ text: 'Phone', dataIndex: 'phone', width: 150 }
],
viewConfig: {
listeners: {
refresh: function(dataview) {
dataview.panel.columns[0].autoSize();//works on the first colum
}
}
},
width: 450,
renderTo: Ext.getBody()
});
I had the same problem, hope it helps!
A: some of the column might be very wide, for example:description text or a long name. If you set the field width auto, some of the column may take up significant space on your view. What should be the maximum width limit in this scenario. 50 CHAR, 100 CHAR ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Is there something like data-* attributes for css? I want to pass a value that's set in a stylesheet so it can be read by javascript/jQuery? I thought of creating an invisible element and giving it a value, but then I would have to include that element in all the pages, which is pretty hacky. Just want to know if there's an alternative to that.
I have a js resize script for images that resizes based on area instead of height or width, so I can't feed it a maxwidth or maxheight, per se. if you give it 100, it makes the area of an image = 100^2. I suppose I could set the maxWidth of the element to twice the number I want, but I'm just wondering if there's a classier way to pull it off.
A: As far as I know, browsers throw away attributes they don't understand, so unfortunately you can't just inject your own data-*. I think you might have to do it via a hidden element, something like below, which uses the content attribute:
# styles.css
.data {
display: none;
content: "my data variable"
}
# index.html
<span class="data"></span>
# javascript
myData = $(".data").css('content')
Update
Playing around in Chrome, it looks like you can set the 'content' of an image and it won't show up. So you could do
# styles.css
img {
content: "100"
}
Not sure how well that works cross browser though, also looking at the w3c spec, it says that 'content' has to be used with :before or :after, so not sure if you'll run into validation issues there.
A: Why not just use javascript to query the actual element, and read its properties that way? Then you don't rely on the CSS at all.
$('someDiv').getWidth()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting an Error when trying to connect Visual Studio application to Oracle I am new to Oracle.I amy trying to connect my Visual Studio 2010 VB application with an Oracle Server on a remote server.
I configured my tnsnames.ora by proving the host name and service name. When I tried to test the connection using the Add Connection functionality in Server Exploreer I got the following error:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
Does this mean the values I entered into tnsnames.ora are wrong. Or do I need to configure anyother documents- listener.ora for example? I have not made any other changes except what I have mentioned above. Please let me know how to resolve this issue as it is time sensitive.
Thanks
A: Take Visual Studio out of the picture first. You need to confirm your Oracle client is configured properly on your machine.
If you installed the Oracle connection tools, you should have tnsping installed. From the command line, enter
tnsping <server_name>
This will try to find the Oracle server using the configuration specified in your tnsnames file (if your sqlnet file is configured to have Oracle use the tnsnames protocol). If it finds it, it will tell you what method it used. You can then use this information for your Visual Studio connection.
Make sure your sqlnet file is correct. You use this file to tell Oracle the order of protocols to use to resolve servers (e.g. tnsnames, ldap, etc.). Mine looks as follows:
SQLNET.AUTHENTICATION_SERVICES = (NTS)
NAMES.DIRECTORY_PATH = (LDAP,TNSNAMES)
NAMES.DEFAULT_DOMAIN = <domain_name>
A: This usually means one of two things.
*
*You don't have ODP.Net installed or it is missing some dll's (unlikely)
*You have more than one version of the oracle client on the machine and .net can't find the correct one.
Go to the system path for the machine and make sure that the FIRST oracle path in the path statement is pointing to the correct oracle client installation.
To remove oracle
*
*Stop DTC service and oracle mts service if running
*Delete All oracle directories (C:\Program Files, C:\Oracle, C:\App, etc)
*Remove Oracle from the path statement (all entries)
*Remove any environment variables
*Remove Oracle entries in the Local Machine registry and Current User section (if exists)
*Reboot the machine
*Reinstall the correct version
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ClickOnce application won't accept command-line arguments I have a VB.NET application that takes command-line arguments.
It works fine when debugging provided I turn off Visual Studio's ClickOnce security setting.
The problem occurs when I try to install the application on a computer via ClickOnce and try to run it with arguments. I get a crash when that happens (oh noes!).
There is a workaround for this issue: move the files from the latest version's publish folder to a computer's C: drive and remove the ".deploy" from the .exe. Run the application from the C: drive and it will handle arguments just fine.
Is there a better way to get this to work than the workaround I have above?
Thanks!
A: "Command-line arguments" only work with a ClickOnce app when it is run from a URL.
For example, this is how you should launch your application in order to attach some run-time arguments:
http://myserver/install/MyApplication.application?argument1=value1&argument2=value2
I have the following C# code that I use to parse ClickOnce activation URL's and command-line arguments alike:
public static string[] GetArguments()
{
var commandLineArgs = new List<string>();
string startupUrl = String.Empty;
if (ApplicationDeployment.IsNetworkDeployed &&
ApplicationDeployment.CurrentDeployment.ActivationUri != null)
{
// Add the EXE name at the front
commandLineArgs.Add(Environment.GetCommandLineArgs()[0]);
// Get the query portion of the URI, also decode out any escaped sequences
startupUrl = ApplicationDeployment.CurrentDeployment.ActivationUri.ToString();
var query = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
if (!string.IsNullOrEmpty(query) && query.StartsWith("?"))
{
// Split by the ampersands, a append a "-" for use with splitting functions
string[] arguments = query.Substring(1).Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries).Select(a => String.Format("-{0}", HttpUtility.UrlDecode(a))).ToArray();
// Now add the parsed argument components
commandLineArgs.AddRange(arguments);
}
}
else
{
commandLineArgs = Environment.GetCommandLineArgs().ToList();
}
// Also tack on any activation args at the back
var activationArgs = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;
if (activationArgs != null && activationArgs.ActivationData.EmptyIfNull().Any())
{
commandLineArgs.AddRange(activationArgs.ActivationData.Where(d => d != startupUrl).Select((s, i) => String.Format("-in{1}:\"{0}\"", s, i == 0 ? String.Empty : i.ToString())));
}
return commandLineArgs.ToArray();
}
Such that my main function looks like:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
var commandLine = GetArguments();
var args = commandLine.ParseArgs();
// Run app
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to have SQL INNER JOIN accept null results I have the following query:
SELECT TOP 25 CLIENT_ID_MD5, COUNT(CLIENT_ID_MD5) TOTAL
FROM dbo.amazonlogs
GROUP BY CLIENT_ID_MD5
ORDER BY COUNT(*) DESC;
Which returns:
283fe255cbc25c804eb0c05f84ee5d52 864458
879100cf8aa8b993a8c53f0137a3a176 126122
06c181de7f35ee039fec84579e82883d 88719
69ffb6c6fd5f52de0d5535ce56286671 68863
703441aa63c0ac1f39fe9e4a4cc8239a 47434
3fd023e7b2047e78c6742e2fc5b66fce 45350
a8b72ca65ba2440e8e4028a832ec2160 39524
...
I want to retrieve the corresponding client name (FIRM) using the returned MD5 from this query, so a row might look like:
879100cf8aa8b993a8c53f0137a3a176 126122 Burger King
So I made this query:
SELECT a.CLIENT_ID_MD5, COUNT(a.CLIENT_ID_MD5) TOTAL, c.FIRM
FROM dbo.amazonlogs a
INNER JOIN dbo.customers c
ON c.CLIENT_ID_MD5 = a.CLIENT_ID_MD5
GROUP BY a.CLIENT_ID_MD5, c.FIRM
ORDER BY COUNT(*) DESC;
This returns something like:
879100cf8aa8b993a8c53f0137a3a176 126122 Burger King
06c181de7f35ee039fec84579e82883d 88719 McDonalds
703441aa63c0ac1f39fe9e4a4cc8239a 47434 Wendy's
3fd023e7b2047e78c6742e2fc5b66fce 45350 Tim Horton's
Which works, except I need to return an empty value for c.FIRM if there is no corresponding FIRM for a given MD5. For example:
879100cf8aa8b993a8c53f0137a3a176 126122 Burger King
06c181de7f35ee039fec84579e82883d 88719 McDonalds
69ffb6c6fd5f52de0d5535ce56286671 68863
703441aa63c0ac1f39fe9e4a4cc8239a 47434 Wendy's
3fd023e7b2047e78c6742e2fc5b66fce 45350 Tim Horton's
How should I modify the query to still return a row even if there is no corresponding c.FIRM?
A: Instead of doing an INNER join, you should do a LEFT OUTER join:
SELECT
a.CLIENT_ID_MD5,
COUNT(a.CLIENT_ID_MD5) TOTAL,
ISNULL(c.FIRM,'')
FROM
dbo.amazonlogs a LEFT OUTER JOIN
dbo.customers c ON c.CLIENT_ID_MD5 = a.CLIENT_ID_MD5
GROUP BY
a.CLIENT_ID_MD5,
c.FIRM
ORDER BY COUNT(0) DESC
http://www.w3schools.com/sql/sql_join.asp
A: An inner join excludes NULLs; you want a LEFT OUTER join.
A: use LEFT JOIN instead of INNER JOIN
A: Replace INNER JOIN with LEFT JOIN
A: SELECT a.CLIENT_ID_MD5, COUNT(a.CLIENT_ID_MD5) TOTAL, IsNull(c.FIRM, 'Unknown') as Firm
FROM dbo.amazonlogs a
LEFT JOIN dbo.customers c ON c.CLIENT_ID_MD5 = a.CLIENT_ID_MD5
GROUP BY a.CLIENT_ID_MD5, c.FIRM ORDER BY COUNT(*) DESC;
This will give you a value of "Unknown" when records in the customers table don't exist. You could obviously drop that part and just return c.FIRM if you want to have actual nulls instead.
A: Change your INNER JOIN to an OUTER JOIN...
SELECT a.CLIENT_ID_MD5, COUNT(a.CLIENT_ID_MD5) TOTAL, c.FIRM
FROM dbo.amazonlogs a
LEFT OUTER JOIN dbo.customers c
ON c.CLIENT_ID_MD5 = a.CLIENT_ID_MD5
GROUP BY a.CLIENT_ID_MD5, c.FIRM
ORDER BY COUNT(*) DESC;
A: WITH amazonlogs_Tallies
AS
(
SELECT a.CLIENT_ID_MD5, COUNT(a.CLIENT_ID_MD5) TOTAL
FROM dbo.amazonlogs a
GROUP
BY a.CLIENT_ID_MD5
),
amazonlogs_Tallies_Firms
AS
(
SELECT a.CLIENT_ID_MD5, a.TOTAL, c.FIRM
FROM amazonlogs_Tallies a
INNER JOIN dbo.customers c
ON c.CLIENT_ID_MD5 = a.CLIENT_ID_MD5
)
SELECT CLIENT_ID_MD5, TOTAL, FIRM
FROM amazonlogs_Tallies_Firms
UNION
SELECT CLIENT_ID_MD5, TOTAL, '{{NOT_KNOWN}}'
FROM amazonlogs_Tallies
EXCEPT
SELECT CLIENT_ID_MD5, TOTAL, '{{NOT_KNOWN}}'
FROM amazonlogs_Tallies_Firms;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: Is it possible for JavaScript to prevent people from right clicking to save images? I have been studying JavaScript and I've found so many things what it can do and I feel comfortable using this language, but I'm getting worried about the right click savers out there. Is there a way to prevent people from ever saving the images from my website and put it onto their desktop?
*
*Some girl
*Some person
*That person took the images
*Store it on his/her desktop
*Makes fun of the girl
A: No, there isn't any way to do this that isn't easily circumvented.
A: You can put some overlay onto the image, but that wont stop people with a dev console for their browser.
Another way is to load images from a script and only allow them to be shown when they are on a certain page (using php or any other server implementation)
A: No. If someone has gone to your web page and can see your image the browser has already downloaded the image and saved it to the local cache, whether or not the user knows how to get to it.
Also, they can always turn off Javascript in their browser
A: You can make it hard to download the image but it's IMPOSSIBLE to prevent image theft!
Using a grid of small images and showing just a part of whole image when user zoom in is the way most photography site uses to make it hard to steal the image. When you use grid of images then drag and drop or Save As wouldn't save whole image.
But it's still possible to steal the image by collection all parts of image and connecting them together via an image editing tool
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Help with Ajax post to action method I am a new to MVC an need a little help.
In my view I make an ajax post as below.
function PostCheckedPdf(e) {
var values = new Array();
$('input:checked').each(function () { values.push(this.value); });
$.post("/UnregisteredUserPreview/DownloadPdfInvoice",
{ checkedList: values });
}
This post the values of any checkboxes that are checked inside a third party Grid component (Telerik). The Action method receives the array fine and loops through each value rendering a pdf report and putting the report into a ZipStream which is attached to the Response. After the loop the zipstream is closed and I return View();
When the Action is invoked through the $.post it runs through the action method but nothing happens in the browser.
If I call the Action through an action link (with a couple of hard coded value instead of passing the checked boxes values) the zip file with all the pdfs is downloaded.
What am I doing wrong or how can I post the checked values with an ActionLink?
Thanks in Advance!
Toby.
A: The difference is that your ActionLink is emitting an <a> tag, which is performing a GET operation. The browser interprets the contents of the response and opens the PDF.
Your jQuery method is performing a POST, but does nothing with the response, and thus silently throws it away in the background.
You need to actually do something with the return contents, like write it out to another window.
var w = window.open('', '', 'width=800,height=600,resizeable,scrollbars');
$.post("/UnregisteredUserPreview/DownloadPdfInvoice",
{ checkedList: values },
function(content){
w.document.write(content);
w.document.close(); // needed for chrome and safari
});
A: You are making an Ajax call to the server there and client side code should receive the returned result which seems that you are not doing there. It should be something like below :
$.ajax({
type: 'POST'
url: '/UnregisteredUserPreview/DownloadPdfInvoice',
data: { checkedList: values },
success: function (r) {
alert(r.result);
}
});
And assume that your controller is like below :
public ActionResult DownloadPdfInvoice() {
//do you stuff here
return Json(new { result = "url_of_your_created_pdf_might_be_the_return_result_here"});
}
NOTE
If you are posting your data with anchor tag, it is better to
prevent the default action of this tag so that it won't do anything
else but the thing you're telling it to do. You can do that by adding the
following code at the end of your click event function :
$("#myLink").click(function(e) {
//do the logic here
//ajax call, etc.
e.preventDefault();
});
Have a look at the below blog post as well. It might widen your thoughts :
http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: os.walk multiple directories at once
Possible Duplicate:
How to join two generators in Python?
Is there a way in python to use os.walk to traverse multiple directories at once?
my_paths = []
path1 = '/path/to/directory/one/'
path2 = '/path/to/directory/two/'
for path, dirs, files in os.walk(path1, path2):
my_paths.append(dirs)
The above example doesn't work (as os.walk only accepts one directory), but I was hoping for a more elegant solution rather than calling os.walk twice (plus then I can sort it all at once). Thanks.
A: Use itertools.chain().
for path, dirs, files in itertools.chain(os.walk(path1), os.walk(path2)):
my_paths.append(dirs)
A: Others have mentioned itertools.chain.
There's also the option of just nesting one level more:
my_paths = []
for p in ['/path/to/directory/one/', '/path/to/directory/two/']:
for path, dirs, files in os.walk(p):
my_paths.append(dirs)
A: To treat multiples iterables as one, use itertools.chain:
from itertools import chain
paths = ('/path/to/directory/one/', '/path/to/directory/two/', 'etc.', 'etc.')
for path, dirs, files in chain.from_iterable(os.walk(path) for path in paths):
A: since nobody mentioned it, in this or the other referenced post:
http://docs.python.org/library/multiprocessing.html
>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
... return x*x
...
>>> p.map(f, [1,2,3])
in this case, you'd have a list of directories. the call to map would return a list of lists from each dir, you could then choose to flatten it, or keep your results clustered
def t(p):
my_paths = []
for path, dirs, files in os.walk(p):
my_paths.append(dirs)
paths = ['p1','p2','etc']
p = Pool(len(paths))
dirs = p.map(t,paths)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: FTP added extra character I have a instream that takes in raw binary data from Bluetooth on Android 2.2 phone. The data coming in goes into a buffer 1024 in size. I read() the data and then take that and write to a file. I send that file via FTP to my computer. I noticed a disturbing pattern when ftp'ing that an extra character gets inserted every once in a while. So I printed out the buffer first to LogCat and noticed the character was not there. Here is my read write code.
FTPClient con = new FTPClient();
File file = new File(Environment.getExternalStorageDirectory() + "/ftp/new/" + "testdata.bin");
try {
con.connect("someIPAddress");
if (con.login("anonymous", "anonymous@anon.com")) {
con.enterLocalPassiveMode(); // important!
FileInputStream in = new FileInputStream(file);
boolean result = con.storeFile("testdata.bin", in);
in.close();
if (result) {
Log.v("upload result", "succeeded");
}
}
} catch (Exception e) {e.printStackTrace();}
Here is an example of the output from the logcat:
09 15 D0 0D 17 0A 06 08 07
and here is what is in the file after ftp'ing:
09 15 D0 0D 17 0D 0A 06 08 07
Well I thought that hmm 0A something is injecting 0D to make (CRLF) but it doesn't happen at every 0A. I can write the same program in C# and this doesn't happen at all. So any ideas or help?
On further investigation I found it occurs when the data going in is 17 0A and the file shows 17 0D 0A.
A: Solution: The FTPClient will send the file by default as ASCII. Set the fileType to Binary file by using this command:
con.setFileType(FTP.BINARY_FILE_TYPE);
A: Windows, unix and mac all have different line endings.
FTP "fixes" this for you in ASCII mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to parse YouTube Playlist into ListView I have a GDATA link that contains a playlist from a public YouTube Channel. I need the videos of this playlist to appear in a listview. Is this possible? If os, how can I implement it? Could someone point me towards an example?
EDIT:
Here is the gdata link I need to parse:
http://gdata.youtube.com/feeds/base/users/interactivemedialab1/playlists/42E77F93E83D3FE4
A: Take a look at my sample Android application for displaying a YouTube playlist in a list view.
https://github.com/akoscz/YouTubePlaylist
Note that you MUST have a valid API key for this sample application to work. You can register your application with the Google Developer Console and enable the YouTube Data API. You need to Register a Web Application NOT an Android application, because the API key that this sample app uses is the "Browser Key".
A: For creating a list try searching the API Demos, loads of list view example there with code you can use. And as LeiNaD rightly pointed out first parse the XML using XMLPullParser or XMLSAXParser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Matlab: how to find which variables from dataset could be discarded using PCA in matlab? I am using PCA to find out which variables in my dataset are redundand due to being highly correlated with other variables. I am using princomp matlab function on the data previously normalized using zscore:
[coeff, PC, eigenvalues] = princomp(zscore(x))
I know that eigenvalues tell me how much variation of the dataset covers every principal component, and that coeff tells me how much of i-th original variable is in the j-th principal component (where i - rows, j - columns).
So I assumed that to find out which variables out of the original dataset are the most important and which are the least I should multiply the coeff matrix by eigenvalues - coeff values represent how much of every variable each component has and eigenvalues tell how important this component is.
So this is my full code:
[coeff, PC, eigenvalues] = princomp(zscore(x));
e = eigenvalues./sum(eigenvalues);
abs(coeff)/e
But this does not really show anything - I tried it on a following set, where variable 1 is fully correlated with variable 2 (v2 = v1 + 2):
v1 v2 v3
1 3 4
2 4 -1
4 6 9
3 5 -2
but the results of my calculations were following:
v1 0.5525
v2 0.5525
v3 0.5264
and this does not really show anything. I would expect the result for variable 2 show that it is far less important than v1 or v3.
Which of my assuptions is wrong?
A: EDIT I have completely reworked the answer now that I understand which assumptions were wrong.
Before explaining what doesn't work in the OP, let me make sure we'll have the same terminology. In principal component analysis, the goal is to obtain a coordinate transformation that separates the observations well, and that may make it easy to describe the data , i.e. the different multi-dimensional observations, in a lower-dimensional space. Observations are multidimensional when they're made up from multiple measurements. If there are fewer linearly independent observations than there are measurements, we expect at least one of the eigenvalues to be zero, because e.g. two linearly independent observation vectors in a 3D space can be described by a 2D plane.
If we have an array
x = [ 1 3 4
2 4 -1
4 6 9
3 5 -2];
that consists of four observations with three measurements each, princomp(x) will find the lower-dimensional space spanned by the four observations. Since there are two co-dependent measurements, one of the eigenvalues will be near zero, since the space of measurements is only 2D and not 3D, which is probably the result you wanted to find. Indeed, if you inspect the eigenvectors (coeff), you find that the first two components are extremely obviously collinear
coeff = princomp(x)
coeff =
0.10124 0.69982 0.70711
0.10124 0.69982 -0.70711
0.9897 -0.14317 1.1102e-16
Since the first two components are, in fact, pointing in opposite directions, the values of the first two components of the transformed observations are, on their own, meaningless: [1 1 25] is equivalent to [1000 1000 25].
Now, if we want to find out whether any measurements are linearly dependent, and if we really want to use principal components for this, because in real life, measurements my not be perfectly collinear and we are interested in finding good vectors of descriptors for a machine-learning application, it makes a lot more sense to consider the three measurements as "observations", and run princomp(x'). Since there are thus three "observations" only, but four "measurements", the fourth eigenvector will be zero. However, since there are two linearly dependent observations, we're left with only two non-zero eigenvalues:
eigenvalues =
24.263
3.7368
0
0
To find out which of the measurements are so highly correlated (not actually necessary if you use the eigenvector-transformed measurements as input for e.g. machine learning), the best way would be to look at the correlation between the measurements:
corr(x)
ans =
1 1 0.35675
1 1 0.35675
0.35675 0.35675 1
Unsurprisingly, each measurement is perfectly correlated with itself, and v1 is perfectly correlated with v2.
EDIT2
but the eigenvalues tell us which vectors in the new space are most important (cover the most of variation) and also coefficients tell us how much of each variable is in each component. so I assume we can use this data to find out which of the original variables hold the most of variance and thus are most important (and get rid of those that represent small amount)
This works if your observations show very little variance in one measurement variable (e.g. where x = [1 2 3;1 4 22;1 25 -25;1 11 100];, and thus the first variable contributes nothing to the variance). However, with collinear measurements, both vectors hold equivalent information, and contribute equally to the variance. Thus, the eigenvectors (coefficients) are likely to be similar to one another.
In order for @agnieszka's comments to keep making sense, I have left the original points 1-4 of my answer below. Note that #3 was in response to the division of the eigenvectors by the eigenvalues, which to me didn't make a lot of sense.
*
*the vectors should be in rows, not columns (each vector is an
observation).
*coeff returns the basis vectors of the principal
components, and its order has little to do with the original input
*To see the importance of the principal components, you use eigenvalues/sum(eigenvalues)
*If you have two collinear vectors, you can't say that the first is important and the second isn't. How do you know that it shouldn't be the other way around? If you want to test for colinearity, you should check the rank of the array instead, or call unique on normalized (i.e. norm equal to 1) vectors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Authorize attribute Need help on this authorize code to define a specific sub group in my controller.
[Authorize(Roles = "RABEE\domain user accounts\zam gas industry\california\domain local groups\ZamReader")]
RABEE is the domain name that is why I have \
Group Name i have added users is: ZamReader
what I am doing wrong?
A: Are you using Active Ditrectory? If so, make sure that your using a "Security Group" not a "Distribution Group".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java setText make application error I have simple application in Android
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/id_txt"
android:text="go"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
and TestActivity.java
package test.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView t = (TextView) findViewById(R.id.id_txt);
t.setText("gone");
}
}
and after executing in android emulator a recive message The application Test has stopped unexpectedly. Please try again later, but why ??
A: You aren't overriding the onCreate(...) method correctly. It should be as follows...
// NOTE: Use @Override and also the method is 'protected' and not 'public'
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView t = (TextView) findViewById(R.id.id_txt);
t.setText("gone");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The Live stream Plugin - When people share it post to wall. the link back does not go to my site,instead my fb app, how to make go to my site? Newbee - The Live stream Plugin - When people share in the discussion it posts to their wall. The link back from their wall does not go to my site,instead to my fb app. I do not want this. How to make the link go to my site?
Here is my meta tags, do not know if you need this to help.
<meta property="fb:222552801135886" content="{222552801135886}"/>
<meta property="og:title" content="The Green Zone Kicker" />
<meta property="og:type" content="book" />
<meta property="og:url" content="http://www.greenzonekicker.com" />
<meta property="og:image" content="http://www.greenzonekicker.com/img/bookforSale60.JPG" />
<meta property="og:site_name" content="The Green Zone Kicker" />
<meta property="fb:admins" content="100002932010605" />
Here is the code for my live stream plugin.
<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#appId=222552801135886&xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));</script>
<div class="fb-live-stream" data-event-app-id="222552801135886" data-width="873" data-height="500" data-always-post-to-friends="false"></div>
Thanks in advance!!
Also , I was just going with the flow and made a fb app for my site. But I dont get what that is doing for in terms of its usefulness? Can someone explain under what circumstance I would want my website to be embedded in my faceBook app?
Adam
A: I figured it out. You need to put your url in BOTH (in my case"http://www.greenzonekicker.com/") in both the app > edit app > url and in the live stream plugin wizard where is says Via Attribution URL (?).
SO I put the above in both places, and now when someone shares in my discussion and goes to their wall, the link back does not go to a fan page or the embedded app, it will go straight to your site.
So to clarify, put the url your want the link to go to in BOTH the live stream code generator from facebook, AND in facebook > app > app name > edit > website > url.
I have heard of problems if you do not put the trailing forward slash after your url, so just do it to be safe.
Adam
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Force Hibernate Insert Without Select Statements I am attempting to insert a new record into a table that I know is unique before hand. I have tried calling save() on the object, but that does a bunch of SELECT statements before doing any INSERTs, which I don't want to do because I know the object is already unique.
I am opening a new session for each transaction, which I can see being an issue, but that is a constraint of my domain. Is there some way to force Hibernate to not do any SELECTs before it INSERTs?
A: Hibernate is trying to determine if the object is transient or not, so is performing a SELECT before INSERT. You might be able to adapt this answer from Hibernate OneToOne mapping executes select statement before insert; not sure why to avoid the SELECT.
Or, I remember a post in a forum about overriding the version column that hibernate uses in the transient check (and for optimistic locking). I'll edit this answer when I find it.
A: You can use the persist() method rather than save().
https://forum.hibernate.org/viewtopic.php?f=1&t=1011405
However, unlike save(), persist() does not guarantee that the identifier value will be set immediately on the persisted instance.
https://forum.hibernate.org/viewtopic.php?f=1&t=951275
(and you can jump to christian's last post in the thread)
A: Hibernate doesn't issue a select to see if an object is unique upon a save(). In point of fact, Hibernate doesn't even issue an insert when you call save(). That happens when you flush() or commit the transaction. You'll need to find out exactly what the selects are for and what's initiating them. To help narrow it down, you could write a quick test like
Session session = openSession();
Transaction tx = session.beginTransaction();
session.save(myObject);
tx.commit();
and see what statements that produces.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: vba positive lookahead is too greedy I'm using Access VBA to parse a string with regex. Here's my regex function:
Function regexSearch(pattern As String, source As String) As String
Dim re As RegExp
Dim matches As MatchCollection
Dim match As match
Set re = New RegExp
re.IgnoreCase = True
re.pattern = pattern
Set matches = re.Execute(source)
If matches.Count > 0 Then
regexSearch = matches(0).Value
Else
regexSearch = ""
End If
End Function
When I test it with:
regexSearch("^.+(?=[ _-]+mp)", "153 - MP 13.61 to MP 17.65")
I'm expecting to get:
153
because the only characters between this and the first instance of 'MP' are the ones in the class specified in the lookahead.
but my actual return value is:
153 - MP 13.61 to
Why is it capturing up to the second 'MP'?
A: Because .+ is greedy by default. The .+ gobbles up every character until it encounters a line break char, or the end-of-input. When that happens, it backtracks to the last MP (the second one in your case).
What you want is to match ungreedy. This can be done by placing a ? after .+:
regexSearch("^.+?(?=[ _-]+MP)", "153 - MP 13.61 to MP 17.65")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: I don't understand the code for avoiding DoubleRenderError The official page has this snippet:
def show
@book = Book.find(params[:id])
if @book.special?
render :action => "special_show" and return
end
render :action => "regular_show"
end
Why isn't this equivalent?
def show
@book = Book.find(params[:id])
if @book.special?
render :action => "special_show"
return
end
render :action => "regular_show"
end
Or, why isn't this used?
def show
@book = Book.find(params[:id])
if @book.special?
render :action => "special_show" and return
else
render :action => "regular_show"
end
end
I don't understand the need for render ... and return
A: That's a really bad example. I'm really opposed to the and return method of short-circuiting because a lot of people don't understand what it means, and further, it's liable to be overlooked unless you're paying careful attention.
The better approach is as you describe where you have an explicit if statement that breaks out the two possibilities. I'd go one further to collapse this all into a single render call with the action argument identified ahead of time:
def show
@book = Book.find(params[:id])
# Determine the template to be used for this action
render_action = @book.special? ? 'special_show' : 'regular_show'
# Render the appropriate template
render(:action => render_action)
rescue ActiveRecord::RecordNotFound
render(:action => 'not_found', :status => :not_found)
end
Also missing from the example was the trap for the find call which can produce an exception if the record isn't found. This is a common over-sight and I'm pretty sure most people forget about it entirely. Remember you shouldn't be rendering 500 "server error" in a well designed app even when receiving bad requests.
The easiest way to avoid a double render error is to have only one render call, after all.
A: They are in fact all equivalent. Your example just happened to go with the least intuitively obvious version. Not sure why, but that style is something I've seen frequently in Rails examples.
Essentially, and is a boolean operator with really low binding precedence, so a line like expression_a and expression_b will result in expression_a being evaluated, and then, as long as it didn't evaluate to nil or false, it'll evaluate expression_b. Since render returns... well, something non-false - don't know what, exactly ...your example behaves exactly like render whatever; return (or with a line break instead of the semicolon, like in the second snippet).
Personally, I prefer the third snippet, with the if/else block (which doesn't need the and return, 'cause it's at the end of the function anyway). It's in-your-face obvious what it does, and I like that in my code.
Hope this helps!
A: In the first snippet, if the and return was absent, and @book.special? was truthy, you would get a DoubleRenderError. That's because both the render calls would be executed.
With that in mind, all of the snippets are equivalent in that they will prevent render from being called twice. Also, in the last snippet, the and return is not needed since only one of the render's will ever get called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to programatically determine if an Android application is obfuscated? I have and Android app where various people test both development builds and release builds. The development builds are not obfuscated and I would like to be able to programatically determine at runtime if the application has been obfuscated or not.
Is there a way to do this?
A: Here's one idea: add a class to your code base that is not used at all. Proguard will obfuscate and/or remove it. So, loading it via reflection in the app ought to cause ClassNotFoundException if it's been run through ProGuard.
A: As @Sean proposed use a class which has no (external) dependencies.
But beware, ProGuard can detect the use of reflection, so you must somehow load class from string name, by not using a string literal (text resource maybe?): http://proguard.sourceforge.net/index.html#/FAQ.html%23forname
A: Select a class which is always renamed by Proguard after obfuscation. Its name is ExampleClass.java in the code below. Check its name in runtime with the following line:
ExampleClass.java
...
public static final boolean OBFUSCATED = !ExampleClass.class.toString().contains("ExampleClass");
That's all. No helper class or method is required and works without causing exceptions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ruby On Rails jQuery AJAX Post Ok, in PHP I can do this in 5 minutes. With Rails I am completely lost. I am so new to Rails and I have a requirement to do more advanced stuff with it then I am comfortable with currently. The Big guy decided lets go Rails from PHP. So its crash course learning. Fun times..
I understand from the javascript side making the post/get with jquery remains the same. On the ruby side however I am completely lost. What do I need to do in order to do a post/get to a Rails App. How would I define my controller? Lets say from the HTML side I am posting
input1 and input2 standard jquery $.post with a JSON request for data back. With php I would make a simple controller like:
public function myFormPostData(){
$errors = "none";
$errorMsg = "";
if($_POST['input1'] == ""){$errors = "found"; $errorMsg .= "Input 1 Empty<br>";}
if($_POST['input2'] == ""){$errors = "found"; $errorMsg .= "Input 2 Empty<br>";}
if($errors == "found"){ $output = array("error" => "found", "msg" => $errorMsg); }
else{
$output = array("error" => "none", "msg" => "Form Posted OK!!");
}
echo json_encode($output);
}
but in ruby I dunno how to translate that concept. I'm open to suggestions and good practices. Grant it the above is a super mediocre rendition of what I am needing to do I would sanitize things more than that and all else, but it gives the idea of what I am looking for in Rails..
A: First, you need to tell Rails that a certain page can accept gets and posts.
In your config/routes.rb file:
get 'controller/action'
post 'controller/action'
Now that action in that controller (for example, controller "users" and action "index") can be accessed via gets and posts.
Now, in your controller action, you can find out if you have a get or post like this:
def index
if request.get?
# stuff
elsif request.post?
# stuff
redirect_to users_path
end
end
Gets will look for a file corresponding to the name of the action. For instance, the "index" action of the "users" controller will look for a view file in app/views/users/index.html.erb
A post, however, is usually used in conjunction with the redirect (like in the above example), but not always.
A: First of all, Rails 3 has a nice feature called respond_with. You might check out this Railscast episode that talks about it. http://railscasts.com/episodes/224-controllers-in-rails-3. The examples he uses are great if you are dealing with resources.
Having said that, I'll give you an example with a more traditional approach. You need to have a controller action that handles requests which accept JSON responses.
class MyController < ApplicationController
def foo
# Do stuff here...
respond_to do |format|
if no_errors? # check for error condition here
format.json { # This block will be called for JSON requests
render :json => {:error => "none", :msg => "Form Posted OK"}
}
else
format.json { # This block will be called for JSON requests
render :json => {:error => "found", :msg => "My bad"}
}
end
end
end
end
Make sure that you have a route set up
post '/some/path' => "my#foo"
Those are the basics that you will need. Rails gives you a lot for free, so you may find that much of what you are looking for already exists.
If you post a more concrete example of what you are trying to you might get even better advice. Good luck!
A: its hard at first to understand that you have to do things "the rails way", because the whole philospohy of rails is to enforce certain standards. If you try to fit PHP habits in a rails suit, it will just tear apart. The Rails Guides are your best friend here...
To be more specific about your problem, you should try to build something from ActiveModel. ActiveModel lets you use every feature ActiveRecord has, except it is meant to be used to implement non-persistent objects.
So you can create, say, a JsonResponder model:
class JsonResponder
include ActiveModel::Validations
validates_presence_of :input_1, :input_2
def initialize(attributes = {})
@attributes = attributes
end
def read_attribute_for_validation(key)
@attributes[key]
end
end
In your controller, you now create a new JsonResponder :
# this action must be properly routed,
# look at the router chapter in rails
# guides if it confuses you
def foo
@responder = JsonResponder.new(params[:json_responder])
respond_to do |format|
if @responder.valid?
# same thing as @wizard's solution
# ...
end
end
end
now if your your input fields are empty, errors will be attached to your @responder object, same as any validation error you can get with an ActiveRecord object. There are two benefits with this approach :
*
*all of your logic is kept inside a model of its own. If your response has to be improved later (process a more complicated request for instance), or used from different controllers, it will be very simple to reuse your code. It helps keeping your controllers skinny, and thus is mandatory to take a real advantage out of MVC.
*you should be able (maybe with a little tweaking) to use rails form helpers, so that your form view will only have to be something vaguely like this :
(in the equivalent of a "new" View)
<% form_for @responder do |f| %>
<%= f.input_field :field_1 %>
<%= f.input_field :field_2 %>
<%= f.submit %>
<% end %>
feel free to ask for more precisions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: T-SQL (date) - how to get value within one hour? I am looking for an optimal decision of how to get table values according to their date and time but within just ONE past hour.
I mean something in this way (a pseudocode):
SELECT value FROM Table WHERE date BETWEEN getdate() AND getdate()-ONE_HOUR
For the purpose of this question Table has these columns:
*
*value
*date
Any useful snippet is appreciated :)
A: SELECT Value
FROM Table
WHERE Date between dateadd(hour, -1, getdate()) and getdate()
Description of the DATEADD function:
DATEADD (datepart , number , date )
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
datepart Abbreviations
----------- -------------
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
More information:
*
*DATEADD (Transact-SQL)
A: Something like this should work.
SELECT value
FROM Table
WHERE date >= dateadd(hour,-1,getdate())
and date <= getdate()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: jQuery: Why is it that `:first` only returns the first of the result array and not of the selector http://jsfiddle.net/vol7ron/s5fS8/
*
*HTML:
<div class="container">
<span class="foo">a</span>
<span class="bar">1a</span>
<span class="bar">2a</span>
</div>
<div class="container">
<span class="foo">b</span>
<span class="bar">1b</span>
<span class="bar">2b</span>
</div>
<div class="container">
<span class="foo">c</span>
<span class="bar">1c</span>
<span class="bar">2c</span>
</div>
<div class="title">Debug:</div>
<pre id="debug"></pre>
*JS:
var debug = $('#debug');
var containers = $('.container');
var foos = containers.children('.foo');
var bars = foos.siblings('.bar:first');
bars.each(function(){
debug.append($(this).text() + '\n');
});
What happens is the first bar is returned, whereas from an OOP POV, you'd think the first bar from each container would be returned.
As I left in a comment, I'm hung on why :first is applied to the result set, rather than the search set.
I thought the logic was: loop through the array of foos, find all the siblings that are bars, but only return the first one, add it to the array result stack, continue on to the next foo.
Instead, it's: loop through array of foos, find all siblings that are bars, add them to the result stack, select the first one.
I think it should work more like find() where:
*
*containers.find('.bar:first') returns the result I'm looking for
*containers.find('.bar').first(':first') returns the result I'm currently getting (the OOP makes sense)
A: When you use first you are telling jQuery to get the first it finds from the list you give it not taking into account the parents. To get the result you ask about use this instead:
var bars = foos.next('.bar');
Demo: http://jsfiddle.net/s5fS8/1/
You can also loop over the containers instead:
var debug = $('#debug');
var containers = $('.container');
containers.each(function(){
debug.append($(this).find(".bar:first").text() + '\n');
});
A: It's just how it's designed:
http://api.jquery.com/first-selector/
By definition, it can only return one element. I wish the functionality was how you described. It is more intuitive to me, but it does not work that way by construction.
A: Because that's just the way it is. :first is just short-hand for .eq(0) (it's not even really shorter, it's just another way of doing it).
If I've understood what you think :first should be doing, then you should have a look at :first-child.
From the jQuery docs:
The :first pseudo-class is equivalent to :eq(0). It could also be
written as :lt(1). While this matches only a single element,
:first-child can match more than one: One for each parent.
A: The definitions took a bit of wrapping my head around when I first read them, but basically:
*
*:first returns the first element from a wrapped set, while
*:first-child returns any element that is the first child in its parent container.
So :first looks at your jQuery object, and :first-child looks at the actual HTML container.
That sounds a bit whacked, but hopefully that made sense. :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: why doesnt my jsp request.getParameter() get the data? ive created a form in which user will check off checkboxes, select radio buttons, and drop downs in 1.jsp...
i want to use the information from 1.jsp to determine the output of 2.jsp...
jsfiddle for 1.jsp: http://jsfiddle.net/VWczQ/
action="/2.jsp">
now in 2.jsp i have this:
<% if(request.getParameter("extra") != null) { %>
<page:cmsElement id="cmsContent" name="/otcmarkets/traderAndBroker/market-data-vendors/wizard-results" />
<% } else if(request.getParameter("all") != null) { %>
<page:cmsElement id="cmsContent" name="/otcmarkets/traderAndBroker/market-data-vendors/con-all" />
<% } else { %>
<h1>holy crap everything is null!!!</h1>
<% } %>
when i randomly choose options from the form everything is NULL...
what am i doing wrong?!?
A: You seem to be expecting that the id attribute of the HTML input elements is been sent as request parameter name. This is wrong. It's the name attribute which is been sent as request parameter name. Its value is then the value attribtue which is been set on the named input element.
So, instead of for example your incorrect check
if(request.getParameter("extra") != null) {
// ...
}
for the following radio button
<input type="radio" name="choice" value="extranet" id="extra"/>
you need to get the parameter by name choice and test if its value is extranet.
if ("extranet".equals(request.getParameter("choice"))) {
// ...
}
As to the all checkbox, I am confused. It is possible to send the both values, yet you're checking them in an if-else. Shouldn't the all be inside the same radio button group? Shouldn't you remove the else? In any way, the point should be clear. It's the input elements' name attribtue which get sent as request parameter name, not the id attribute.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: In .NET, System.Threading.Thread.CurrentPrincipal isn't updating I'm missing something elementary here when debugging some .NET code:
public static void CreateServiceSessionStore()
{
ServiceSessionStore serviceSessionStore = new ServiceSessionStore();
serviceSessionStore.SetIdentity(System.Threading.Thread.CurrentPrincipal.Identity);
System.Threading.Thread.CurrentPrincipal = serviceSessionStore;
// Here, CurrentPrincipal still isn't a serviceSessionStore!
}
In this code, everything seems to chug merrily along. However...when I debug and am just before the last line, I'm looking at System.Threading.Thread.CurrentPrincipal. The value is a WebSessionStore object, which is what I expect, and what I am thinking the last line should change it to a ServiceSessionStore object. But it doesn't. I can look at serviceSessionStore, and it's holding a ServiceSessionStore object, but after the line runs CurrentPrincipal still contains a WebSessionStore object. No error is thrown.
Now, aside from what these objects actually do, can someone offer an idea about why it seems to be refusing to update CurrentPrincipal?
A: This is a debugger artifact. Debug expressions are evaluated on a dedicated debugger thread. CurrentPrincipal is a property of the thread's execution context. Also the reason it can be a static property. Different threads will have different principals and the debugger thread's principal is therefore not the same.
You don't have a real problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Oracle ODP.NET Cursor Leak? I'm running into an open cursor limit issue with using the following code. The open cursor limit on the oracle db is set to around 1000. The following code seems to hold onto the cursors even though I've got everything in a using statement (I think) that requires it. (Note, I don't need to read anything from outRefCursor2)
Am I missing a using or some other clean up with ODP.net?
The exception occurs consistently at iteration 596.
static List<Thing> GetDetailsForItems(List<string> items) {
DateTime start = DateTime.UtcNow;
var things = new List<Thing>();
var spname = "SP_GET_THING_DETAILS";
var outRefCursorName1 = "p_ref_cursor1";
var outRefCursorName2 = "p_ref_cursor2";
// Create params
var pInput1 = new OracleParameter("p_input1",
OracleDbType.Varchar2, ParameterDirection.Input);
pInput1.Value = "";
// Input 2 can be blank
var pInput2 = new OracleParameter("p_input2",
OracleDbType.Varchar2, ParameterDirection.Input);
pInput2.Value = "";
var outRefCursor1 = new OracleParameter(outRefCursorName1,
OracleDbType.RefCursor, ParameterDirection.Output);
var outRefCursor2 = new OracleParameter(outRefCursorName2,
OracleDbType.RefCursor, ParameterDirection.Output);
int count = 0;
using (var conn = new OracleConnection(CONN_STR)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.Parameters.Add(pInput1);
cmd.Parameters.Add(pInput2);
cmd.Parameters.Add(outRefCursor1);
cmd.Parameters.Add(outRefCursor2);
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
foreach (string value in items) {
count++;
cmd.Parameters[pInput1.ParameterName].Value = value;
var execVal = cmd.ExecuteNonQuery();
using (var refCursor = (Types.OracleRefCursor)
cmd.Parameters[outRefCursorName1].Value) {
using (var reader = refCursor.GetDataReader()) {
while (reader.Read()) {
// read columns
things.Add(reader["COLUMN_A"].ToString());
}
} // close reader
} // close cursor
} // end foreach
} // close command
} // close connection
int seconds = (DateTime.UtcNow - start).Seconds;
Console.WriteLine("Finished in {0} seconds", seconds);
return things;
}
I'm using this snippet found online to monitor DB cursors. I can watch the cursors add up while stepping through the code. And they just keep adding at the cmd.ExecuteNonQuery() line. I never see a drop after any using statement closes.
select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur,
s.username, s.machine
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid
and b.name = 'opened cursors current'
and machine='MY COMPUTER'
group by s.username, s.machine
order by 1 desc;
A: Even though you're not using outRefCursor2 you still need to extract it and close it if it returns a valid cursor. ODP.net doesn't dispose of resources as nicely as the .Net version did so you need to make sure you dispose everything that is returned by ODP.net commands. As an extra step, it may not hurt to go and call .Close() explicitly on the cursors either to ensure that you're actually closing them (though the dispose should take care of that).
A: You need to dispose of the parameters:
*
*yes I confirmed this before showing native resource leaks (Virtual working set) when we didn't
*I prefer to dispose of the params within the life-time of the connection so as to prevent any issues when the ref cursors need/want to use the connection on dispose (superstition, probably)
static List GetDetailsForItems(List items)
{
DateTime start = DateTime.UtcNow;
var things = new List();
var spname = "SP_GET_THING_DETAILS";
var outRefCursorName1 = "p_ref_cursor1";
var outRefCursorName2 = "p_ref_cursor2";
try
{
int count = 0;
using (var conn = new OracleConnection(CONN_STR))
try
{
conn.Open();
// Create params
var pInput1 = new OracleParameter("p_input1", OracleDbType.Varchar2, ParameterDirection.Input);
pInput1.Value = "";
// Input 2 can be blank
var pInput2 = new OracleParameter("p_input2", OracleDbType.Varchar2, ParameterDirection.Input);
pInput2.Value = "";
var outRefCursor1 = new OracleParameter(outRefCursorName1, OracleDbType.RefCursor, ParameterDirection.Output);
var outRefCursor2 = new OracleParameter(outRefCursorName2, OracleDbType.RefCursor, ParameterDirection.Output);
using (var cmd = conn.CreateCommand())
{
cmd.Parameters.Add(pInput1);
cmd.Parameters.Add(pInput2);
cmd.Parameters.Add(outRefCursor1);
cmd.Parameters.Add(outRefCursor2);
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
foreach (string value in items)
{
count++;
cmd.Parameters[pInput1.ParameterName].Value = value;
var execVal = cmd.ExecuteNonQuery();
using (var refCursor = (Types.OracleRefCursor)
cmd.Parameters[outRefCursorName1].Value)
{
using (var reader = refCursor.GetDataReader())
{
while (reader.Read())
{
// read columns
things.Add(reader["COLUMN_A"].ToString());
}
} // close reader
} // close cursor
} // end foreach
} // close command
} // close connection
finally
{
pInput1.Dispose();
pInput2.Dispose();
outRefCursorName1.Dispose();
outRefCursorName2.Dispose();
}
}
int seconds = (DateTime.UtcNow - start).Seconds;
Console.WriteLine("Finished in {0} seconds", seconds);
return things;
}
A: I wouldn't go for GC.collect()... It is an overkill...http://blogs.msdn.com/b/scottholden/archive/2004/12/28/339733.aspx
But making sure disposing the command object worked for me. Easy is to use the "Using"
Something like this:
using(DbCommand command = dbConn1.CreateCommand())
{
command.CommandText = sql;
using (var dataReader = command.ExecuteReader())
{
dbRows = ToList(dataReader);
}
mvarLastSQLError = 0;
}
A: None of the suggestions had worked thus far. So in desperation, I ended up force GC collection every 200 iterations. With the following code.
if (count % 200 == 0) {
GC.Collect();
}
What's strange is that when calling this method from a unit test, the manual GC.Collect() does not release any cursors. But when calling the method from the business layer, it actually does work and I can see the open cursors get released by monitoring the oracle DB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: User authentication for mobile clients in RESTful WCF 4 service I'm trying to develop a web service to be consumed by mobile clients (iOS clients, for now), I read that RESTful services are much more lightweight than SOAP services, so I'd like to try my hand at this.
Most methods will require authentication, but I'm not sure how to handle this, as I read REST is supposed to be stateless, so how can I validate the user accessing the service from iOS and then use that authentication to validate successive calls to other web methods?
Note: I'll be using WCF 4's WebHttp on IIS.
Thank you!
A: There are a number of fairly established patterns for doing this.
*
*The simplest way to do so would be to provide the username:password as an Authorization header or part of the request (querystring/form data). This would require you to authenticate/authorize the user on each call. Not ideal for you, perhaps, but if you're using WebHttp (if you didn't mean this, I'd take a serious look at WCF Web Api), it would be fairly easy to build an HttpModule or something in the WCF channel stack to intercept the calls and authenticate the user.
*A very common way is to expose an endpoint that takes user:password and generates an API token. The user then takes that API token and uses it to authenticate subsequent calls. That token can be anything from weakly-encrypted data to a hash consisting of a shared secret key, the HTTP verb, requested resource, etc. You'll find several example of this if you google "HMAC Authentication". Azure's authentication schemes are an example of a really granular token. The nice thing about this approach is that you have one endpoint concerned with authentication and building the tokens, and your other endpoints just need to know how to validate the hash or decrypt the token; a nice separation of concerns.
*OAuth/OAuth2 are pretty much the de facto standard if you expect your API's consumer to be a third-party application.
A: I would suggest using a strategy similar to OAuth. You would write one service specifically to validate credentials and hand out access tokens, and require a valid access token for any request to your API.
If you're hosting in IIS, I've accomplished this before using an HttpModule to inspect all incoming requests for a valid token. If there isn't one, the module just ends the request with a 401 Unauthorized Http status code.
EDIT:
If you'd like to do more fine-grained authorization on a per operation basis, I'd suggest using a custom authorization policy. Check out http://msdn.microsoft.com/en-us/library/ms731181.aspx for more details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Play! - End Job dynamically So, let's say I start a job from a controller asynchronously and then render some template.
MyJob job = new MyJob();
job.doJob();
render();
MyJob looks like:
import play.jobs.*;
public class MyJob extends Job {
public void doJob() {
// execute some application logic here until I say to quit via a controller method
}
}
From the UI, I do some actions, and I trigger a request to another route in the controller which would end the job. I don't want to have complicated, continuous DAO actions handled on the client side, so what is the best way to go about this? I have an EC2 elastic cache setup, so the main problem is assigning an ID to a job.
job.endJob(id); ?
A: If you look at JobsPlugin class - it uses ScheduledThreadPoolExecutor executor to maintain a list of jobs.
This class has a remove method, which you can try to use.
A: I'm not aware of a way to easily stop a Job. As Play is stateless, probably your best bet would be to have some flag in the database that the job can check to decide to stop, but doesn't look a great solution to me.
Have you checked Continuations in Play? I believe they may suit your scenario better.
A: private static ScheduledFuture<?> future;
private static final TestJob testJob = new TestJob();
future = JobsPlugin.executor.scheduleWithFixedDelay(testJob, 1, 1, TimeUnit.SECONDS);
future.cancel(true);
future = JobsPlugin.executor.scheduleWithFixedDelay(testJob, 5, 5, TimeUnit.SECONDS);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How does Mongoid "criteria" work? I'm trying to do something straight forward such as:
User.all(:criteria => {:project_id => 2})
This returns an instance of Mongoid::Criteria
What can I do with this criteria? What if I just want the array of documents returned for further evaluation?
A: Criteria is something like Relation object in ActiveRecord
You can use it this way
users = User.where(:project_id => 2)
users.each do |user|
puts user.name
end
# or
users.all
This will return [] if there is no any user
users.all.each do |user|
puts user.name
end
A: To get an array from a Mongoid::Criteria: use the method .to_a
A: In Mongoid, the criteria represents the query, not the elements.
You can think of a criteria as a filter, a scope, a query object.
Once you have a criteria (scope), you can get the elements, executing an actual query to the database, with a method that is supposed to iterate over the elements or return one element, for example: .first, .last, .to_a, .each, .map, etc.
This is more efficient and allows you to compose a complex "query" from other simple ones.
For example, you can create some named scopes in your class:
class User
include Mongoid::Document
field :name, type: String
field :age, type: Integer
field :admin, type: Boolean
scope :admins, where(admin: true) # filter users that are admins
scope :with_name, (name)-> { where(name: name) } # filter users with that name
end
Then you can create some criteria objects:
admins = User.admins
johns = User.with_name('John')
admin_johns = User.admins.with_name('John') # composition of criterias, is like doing ANDs
young = User.where(:age.lt => 25) # the Mongoid method .where also returns a criteria
Up to this point, you didn't fire any query to the mongo database, you were just composing queries.
At any time, you can keep chaining criterias, to refine the query even further:
young_admins = admins.merge(young)
old_admins = admins.where(age.gt => 60)
And finally, get the Array with the elements:
# Execute the query and an array from the criteria
User.all.to_a
User.admins.to_a
admins.to_a
young_admins.to_a
# Execute the query but only return one element
User.first
admins.first
johns.last
# Execute the query and iterate over the returned elements
User.each{|user| ... }
User.admins.each{|admin_user| ... }
johns.map{|john_user| ... }
So, define some named scopes in the Class, then use them to create a criteria, and do the real query when you need it (lazy loading). Criterias handle all of this for you even if you didn't know you needed it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Dynamically generate a webpage in GWT I have a unique challenge that I'm not sure how to approach:
I need to manufacture a new HTML page from scratch, one that contains a script tag and a paragraph tag with some words in it. Very simple! Once the page is built, I just need to open it in a new tab. As long as a I can call the script tag from within it, a popup is fine too. Basically, I am going to use a library called MathJax which will typeset all the elements on the html page it loads on.
I'm not even sure what this functionality is formally called, or if it's even possible in GWT! Any guidance at all would be appreciated, thanks!
A: There is no need to use GWT for it. Just write simple servlet that will spit out html with required script tags to load GWT and do whatever else you need and you are done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery, Ajax tooltip help im using a Jquery + Ajax tooltip which displays a box displaying the context thru AJAX, but the title of the tooltip box is set to be "kbay.in" and the text in the "a" tag ,, now how do i change it to display the title as the value, id, name ,or anythin else of the "a" tag , than the text in it:
$(this).qtip(
{
content: {
// Set the text to an image HTML string with the correct src URL to the loading image you want to use
text: '<img class="throbber" src="http://www.craigsworks.com/projects/qtip/images/throbber.gif" alt="Loading..." />',
ajax: {
url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
},
title: {
text: 'Kbay.in' + $(this).name(), // Give the tooltip a title using each elements text
button: true
}
},
A: Like this?
title: {
text: $(this).prop('value'); // this is the 'value'.. for example
}
A: I THINK that you are looking for $(this).attr("name");
or $(this).attr("id");
etc etc
A: Firstly, make sure $(this) is actually your "a" element so that you know you're grabbing the correct value. Once you know that for sure, the following code should help you:
<a id="mylink" class="foo" href="blah.html">Testing link text</a>
var _link = $(this); // Helps keep track of $(this)
_link.qtip(
{
...
title: {
text: 'Kbay.in ' + _link.text(), // Kbay.in Testing link text
// text: 'Kbay.in ' + _link.attr('id'), // Kbay.in mylink
// text: 'Kbay.in ' + _link.attr('href'), // Kbay.in blah.html
// text: 'Kbay.in ' + _link.attr('class'), // Kbay.in foo
button: true
}
}
$.text() and $.value() grab whatever is between your link's open and close tags without HTML as opposed to the $.html() method which returns the markup:
// $(this).text() = "Testing link text"
// $(this).html() = "Testing link text"
<a href="blah.html">Testing link text</a>
// $(this).text() = "Testing link text"
// $(this).html() = "Testing <b>link</b> text"
<a href="blah.html">Testing <b>link</b> text</a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiline Regular Expression replace Ok, there's lots of regular expressions, but as always, none of them seem to match what I'm trying to do.
I have a text file:
F00220034277909272011
H001500020003000009272011
D001500031034970000400500020000000025000000515000000000
D001500001261770008003200010000000025000000132500000000
H004200020001014209272011
D004200005355800007702200005142000013420000000000000000
D004200031137360000779000005000000012000000000000000000
H050100180030263709272011
D050100001876700006000300019500000025000000250000001500
D050100001247060000071500030000000025000000280000000000
D050100002075670000430400020000000025000000515000000000
D050100008342500007702600005700000010000000000000000700
D050100009460270000702100015205000025000000000000006205
D050100008135120000702400015000000010000000000000001000
D050100006938430000702200026700000010000000000000001000
D050100006423710008000200025700000000000000000000001000
D050100009488040008000600007175000000000000000000001000
D050100001299190000800100016300000000000000000000003950
D050100001244850000800400005407000000000000000000001607
D050100001216280000840200020000000000000001000000006200
D050100001216840000479000008175000000000000100000001000
D050100001265880000410200014350000000000000100000001000
D050100007402650002000300026700000000000000100000001000
D050100001305150002000200016175000000000001000000000000
D050100005435430000899700022350000000000001000000000000
D050100031113850000500200008200000000250000100000001000
and, with a multiline regex (.NET flavored), I want to do a replace so that I get:
H050100180030263709272011
D050100001876700006000300019500000025000000250000001500
D050100001247060000071500030000000025000000280000000000
D050100002075670000430400020000000025000000515000000000
D050100008342500007702600005700000010000000000000000700
D050100009460270000702100015205000025000000000000006205
D050100008135120000702400015000000010000000000000001000
D050100006938430000702200026700000010000000000000001000
D050100006423710008000200025700000000000000000000001000
D050100009488040008000600007175000000000000000000001000
D050100001299190000800100016300000000000000000000003950
D050100001244850000800400005407000000000000000000001607
D050100001216280000840200020000000000000001000000006200
D050100001216840000479000008175000000000000100000001000
D050100001265880000410200014350000000000000100000001000
D050100007402650002000300026700000000000000100000001000
D050100001305150002000200016175000000000001000000000000
D050100005435430000899700022350000000000001000000000000
D050100031113850000500200008200000000250000100000001000
so that, basically, I grab everything that starts with [HD]0501 and nothing else.
I know this seems more suited to a match that a replace, but I'm going through a pre-built engine that accepts a Regex pattern string and a regex replace string only.
What can I supply for a pattern and a replace string to get my desired result? Multiline Regex is a hardcoded configuration?
I originally thought something like this would work:
search:
(?<Match>^[HD]0501\d+$), but this matched nothing.
search:
(?!^[HD]0501\d+$), but this matched a bunch of empty strings, and I couldn't figure out what to put for the replace string.
search:
(?!(?<Omit>^[HD]0501\d+$)), "Group 'Omit' not found."
It seems this should be simple, but as always, Regex manages to make me feel dumb. Help would be greatly appreciated.
A: Try matching the following pattern:
(?m)^(?![HD]0501).+(\r?\n)?
and replace it with an empty string.
The following demo:
using System;
using System.Text.RegularExpressions;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
string input = @"F00220034277909272011
H001500020003000009272011
D001500031034970000400500020000000025000000515000000000
D001500001261770008003200010000000025000000132500000000
H004200020001014209272011
D004200005355800007702200005142000013420000000000000000
D004200031137360000779000005000000012000000000000000000
H050100180030263709272011
D050100001876700006000300019500000025000000250000001500
D050100001247060000071500030000000025000000280000000000
D050100002075670000430400020000000025000000515000000000
D050100008342500007702600005700000010000000000000000700
D050100009460270000702100015205000025000000000000006205
D050100008135120000702400015000000010000000000000001000
D050100006938430000702200026700000010000000000000001000
D050100006423710008000200025700000000000000000000001000
D050100009488040008000600007175000000000000000000001000
D050100001299190000800100016300000000000000000000003950
D050100001244850000800400005407000000000000000000001607
D050100001216280000840200020000000000000001000000006200
D050100001216840000479000008175000000000000100000001000
D050100001265880000410200014350000000000000100000001000
D050100007402650002000300026700000000000000100000001000
D050100001305150002000200016175000000000001000000000000
D050100005435430000899700022350000000000001000000000000
D050100031113850000500200008200000000250000100000001000";
string regex = @"(?m)^(?![HD]0501).+(\r?\n)?";
Console.WriteLine(Regex.Replace(input, regex, ""));
}
}
}
prints:
H050100180030263709272011
D050100001876700006000300019500000025000000250000001500
D050100001247060000071500030000000025000000280000000000
D050100002075670000430400020000000025000000515000000000
D050100008342500007702600005700000010000000000000000700
D050100009460270000702100015205000025000000000000006205
D050100008135120000702400015000000010000000000000001000
D050100006938430000702200026700000010000000000000001000
D050100006423710008000200025700000000000000000000001000
D050100009488040008000600007175000000000000000000001000
D050100001299190000800100016300000000000000000000003950
D050100001244850000800400005407000000000000000000001607
D050100001216280000840200020000000000000001000000006200
D050100001216840000479000008175000000000000100000001000
D050100001265880000410200014350000000000000100000001000
D050100007402650002000300026700000000000000100000001000
D050100001305150002000200016175000000000001000000000000
D050100005435430000899700022350000000000001000000000000
D050100031113850000500200008200000000250000100000001000
A quick explanation:
*
*(?m)
*
*enable multi-line mode so that ^ matches the start of a new line;
*^
*
*match the start of a new line;
*(?![HD]0501)
*
*look ahead to see if there's no "H0501" or "D0501";
*.+
*
*match one or more chars other than line break-chars;
*(\r?\n)?
*
*match an optional line break.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Fetch Data by variable with Javascript How would I go about fetching a piece of text that has been outputted via a piece of javascript code and assigning it to the end of the link in the below script:
$(document).ready(function(){
$(document).bind('deviceready', function(){
var name = $('#name');
var logo = $('#logo');
var attacking = $('#attacking');
var midfield = $('#midfield');
var defence = $('#defence');
var rating = $('#rating');
var url = 'http://79.170.44.147/oftheday.co/fifa/team.php?name=(Piece of text needs to be inputted at the end here, so that the correct data can be fetched)';
$.ajax({
url: url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var name1 = ''+item.name+'';
name.append(name1);
});
$.each(data, function(i,item){
var logo2 = '<img src="'+item.logo+'" />';
logo.append(logo2);
});
$.each(data, function(i,item){
var attacking2 = ''+item.attacking+'';
attacking.append(attacking2);
});
$.each(data, function(i,item){
var midfield2 = ''+item.midfield+'';
midfield.append(midfield2);
});
$.each(data, function(i,item){
var defence2 = ''+item.defence+'';
defence.append(defence2);
});
$.each(data, function(i,item){
var rating2 = ''+item.rating+'';
rating.append(rating2);
});
},
error: function(){
name.text('There was an error loading the name.');
logo.text('There was an error loading the logo.');
attacking.text('There was an error loading the attacking data.');
midfield.text('There was an error loading the midfield data.');
defence.text('There was an error loading the defence data.');
rating.text('There was an error loading the rating data.');
}
});
});
});
I understand how to do this in PHP it would be something like inserting "'.$name.'" to the end of the link where $name is equal to the outputted content. I don't quite understand how to this here though, the script used to output the previous text is in a separate javascript file too.
Any help would be greatly appreciated!
A: var url = '.../oftheday.co/fifa/team.php?name='+encodeURIComponent(someVar);
where does the variable part come from? A dropdown?
If so then
var url = '.../oftheday.co/fifa/team.php?name='+encodeURIComponent($("#someId").val())
UPDATE:
<div onload="onBodyLoad()" id="international"></div>
would mean
var url = '.../oftheday.co/fifa/team.php?name='+encodeURIComponent($("#international").text())
But what is
onload="onBodyLoad()"
supposed to do? - I do not believe there is such an attribute on a div
A: Rather than constructing the query parameters yourself with string concatenations you would be better off using the data parameter of jQuery.ajax(). See the docs at http://api.jquery.com/jQuery.ajax/.
Your ajax call would then look something like this:
// Notice that there is no name= in the url
var url = 'http://79.170.44.147/oftheday.co/fifa/team.php';
$.ajax({
url: url,
data: {
name: $("#international").text() // this will put the name=... in the query
},
dataType: 'jsonp',
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Returning *Bare* JSON from WCF Web Service I have a WCF web service that returns JSON data back to an app (not an ASP.NET web app.) Here is the code:
[ServiceContract(Namespace = "Navtrak.Services.WCF.MobileAPI")]
public interface IJobServiceJSON
{
[OperationContract]
[ServiceKnownType(typeof(Job))]
[WebInvoke(
Method = "GET",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
PagedResult<Job> ReadJobs(int userId, int? startIndex, int? maxResults, string searchTerm, string sortBy);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class JobServiceJSON : IJobServiceJSON
{
public PagedResult<Job> ReadJobs(int userId, int? startIndex, int? maxResults, string searchTerm, string sortBy)
{
var service = new JobService();
return service.ReadJobs(userId, startIndex, maxResults, searchTerm, sortBy);
}
}
<%@ ServiceHost Language="C#" Debug="true" Service="Navtrak.Services.WCF.MobileAPI.JobServiceJSON" CodeBehind="JobServiceJSON.svc.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
And here is the web.config settings:
<services>
<service name="JobServiceJSON" behaviorConfiguration="HttpGetMetadata">
<endpoint contract="Navtrak.Services.WCF.MobileAPI.Interfaces.IJobServiceJSON" binding="basicHttpBinding" behaviorConfiguration="AjaxBehavior" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="HttpGetMetadata">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<!--<enableWebScript />-->
<webHttp defaultOutgoingResponseFormat="Json"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
The issue with this approach is that it returns the JSON wrapped in a "d" object, which isn't that terrible, but it also returns a "___type" property for each object with the namespace of the class. This really bloats the size of the JSON, as seen here:
{"d":{"__type":"PagedResultOfJobPUkCTgiD:#Navtrak.Business.Schemas.CommonSchemas.Schemas","Results":[{"__type":"Job:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Address":"1011 Granite Ct, Salisbury, MD 21804-8609,","Contact":null,"CreateDate":"\/Date(1313514808000-0400)\/","DstActive":0,"Id":18416,"JobAttributes":[{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":0,"Value":"1011 Granite Ct, Salisbury, MD 21804-8609"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":1,"Value":"1011 Granite Ct, Salisbury, MD 21804-8609,"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":0,"Name":"","Sequence":4,"Value":"2:00p ET"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":5,"Value":"test job!"}],"JobTextForMobileDisplay":null,"Latitude":38352974,"Longitude":-75563528,"Name":"1011 Granite Ct, Salisbury, MD 21804-8609","Notes":"test job!","Phone":null,"PromisedDate":"\/Date(1313604000000-0400)\/","ScheduledDay":"\/Date(1313553600000-0400)\/","ScheduledTimeFrom":0,"ScheduledTimeTo":0,"Status":10,"TimeZoneOffset":0},{"__type":"Job:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Address":", , ,","Contact":null,"CreateDate":"\/Date(1313515111000-0400)\/","DstActive":0,"Id":18419,"JobAttributes":[{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":1,"Value":", , ,"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":0,"Value":"1 test place jul 13"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":0,"Name":"","Sequence":4,"Value":"2:00p ET"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":5,"Value":"test"}],"JobTextForMobileDisplay":null,"Latitude":38774850,"Longitude":-96554630,"Name":"1 test place jul 13","Notes":"test","Phone":null,"PromisedDate":"\/Date(1313604000000-0400)\/","ScheduledDay":"\/Date(1313553600000-0400)\/","ScheduledTimeFrom":0,"ScheduledTimeTo":0,"Status":10,"TimeZoneOffset":0},{"__type":"Job:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Address":"1011 Granite Ct, Salisbury, MD 21804-8609,","Contact":null,"CreateDate":"\/Date(1313515357000-0400)\/","DstActive":0,"Id":18420,"JobAttributes":[{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":0,"Value":"1011 Granite Ct, Salisbury, MD 21804-8609"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":1,"Value":"1011 Granite Ct, Salisbury, MD 21804-8609,"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":0,"Name":"","Sequence":4,"Value":"2:00p ET"},{"__type":"JobAttribute:#Navtrak.Business.Schemas.CommonSchemas.Schemas.Job","Id":0,"JobAttributeId":0,"JobId":0,"MobileDisplay":1,"Name":"","Sequence":5,"Value":"test"}],"JobTextForMobileDisplay":null,"Latitude":38352974,"Longitude":-75563528,"Name":"1011 Granite Ct, Salisbury, MD 21804-8609","Notes":"test","Phone":null,"PromisedDate":"\/Date(1313604000000-0400)\/","ScheduledDay":"\/Date(1313553600000-0400)\/","ScheduledTimeFrom":0,"ScheduledTimeTo":0,"Status":10,"TimeZoneOffset":0}],"TotalRecords":4}}
I've been trying to return BARE JSON but haven't been able to figure it out. If I change the BodyStyle to WebMessageBodyStyle.Bare then it gives me an error that any type except WrappedRequest is incompatible with web script behavior. If I remove the Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" from the svc file then if I try to call the json service/method from a web browser, it returns a 400 bad request error.
One other site note related to that, I thought that setting "enableWebScript" in the AjaxBehavior section would do the same as the Factory= setting in the svc file, however it isn't doing anything. I have to set the Factory= in order for it to to correctly return the JSON and not give the 400 error.
So, any suggestions on how I can get this working? This JSON service is being called by mobile apps so I really don't want to return all of the "___type" attributes.
A: If you're using the WebScriptServiceHostFactory, you don't need to use config at all (and since the "name" attribute in the <service> element doesn't have a namespace, I think it's being ignored anyway). WebScriptServiceHostFactory is intended for use with the ASP.NET AJAX framework, not gor general usage. If you replace it with WebServiceHostFactory, you should see both the {"d": wrapping and the __type hints for objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Keyboard dismisses after multiple UIAlertViews are opened I am having a weird issue with my keyboard automatically closing and then reopening when I open multiple UIAlertViews. If I have a keyboard (from a separate UITextField) and I display a UIAlertView, then upon dismissal of that alert I open another (opening the second one in the didDismissWithButtonIndex). When I dismiss the 2nd one it dismisses the keyboard which then comes back up. If i try this with more than 2 alerts in a row, it will still close my keyboard after the 2nd alert is dismissed, but it doesn't show up until the last alert is dismissed. The problem is that the keyboard delegate functions are NOT called so I cannot respond to it being dismissed. I have other UI elements (textfield and images) that get shifted when the keyboard opens, so when it closes those elements float in the screen and look strange. Any idea why that keyboard automatically dismisses? Thanks
BTW, I use an NSMutableArray of NSDictionary objects to queue up alerts that need to be displayed if an alert is already displayed. I am not creating and displaying more than 1 alert at a time.
EDIT: Here's sample code. If you run this you'll see both alerts open (0 then 1) after you dismiss '1' you'll see '0' under it. After you dismiss '0' you'll see what I mean - they keyboard briefly closes and opens but no delegate functions are called. If you set i to a value higher than 2, you'll see that the keyboard still closes after dismissing the 2nd alert, but will stay closed until the last alert is dismissed. I also tried opening just 1 UIAlert, and opening the others one at a time from a queue as each one was dismissed, and still noticed that same behavior. Any ideas?
EDIT: After some more digging I found that if I register for the notifications UIKeyboardDidShowNotification and UIKeyboardDidHideNotification they are in fact fired when the keyboard is automatically dismissed and presented. I still would like to know what in the underlying API is causing it to even happen so it can hopefully be avoided.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 100, 320, 48)];
[textField setDelegate:self];
[textField setBackgroundColor:[UIColor redColor]];
[window addSubview:textField];
[textField release];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *) textField{
NSLog(@"textFieldShouldReturn called with %@", textField);
[textField resignFirstResponder];
return YES;
}
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"textFieldDidBeginEditing called with %@", textField);
for (int i=0; i< 2; i++) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"test" message: [NSString stringWithFormat:@"%d", i] delegate:self cancelButtonTitle:NSLocalizedString(@"OK",@"") otherButtonTitles:nil];
[alert show];
[alert release];
}
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog(@"++++ textFieldShouldEndEditing %@", textField);
return YES;
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
NSLog(@"++++ textFieldDidEndEditing %@", textField);
}
A: the keyboard is only shown when the corresponding UI element is the first responder.. somehow multiple alert views modify the responder chain for a short time. Seems like a framework issue..
I would suggest this workaround:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
dispatch_async(dispatch_get_main_queue(), ^{
/* show new alert view here */
});
}
EDIT
actually i now think it has to do with the Window hierarchy of the application. UIAlertViews create their own window (at window level UIWindowLevelAlert), make them the key window to recieve touch input and then make the old window key window again upon dismissal. When you show a new alert view on didDismiss, UIKit seems to lose (temporarily) track of key windows and the responder chain..
The fix above of course still applies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get lightbox(or its alternatives) to dynamically show a gallery when a link is clicked Note: I have used lightbox and its many alternatives in an attempt to fix this and im using clearbox at the moment.
The Problem: Currently i have javascript code that depending on the element that is clicked, the modal popup of the lightbox should show the user a different set of images. Below is the code I am currently modifying.
$("download").html(" \
<span style='color:white'> \
<a href='img/26.jpg' rel='clearbox' title='Caption'>View Screenshots</a> \
</span><br /> \
However the link does not initiate the lightbox (works on links already on the page) and i have spent two days looking through google and stackoverflow trying to find a fix.
Outline of what I am trying to achieve: A Showcase of my work where one image will be dynamically added through javascript as a hyperlink depending on the work chosen. When the user clicks it will allow them to go through all the other images that are hidden but part of the gallery. There will be multiple galleries. Thank you for reading.
Edit 1: Please excuse the mspaint job
http://i.stack.imgur.com/rN8q1.jpg
A: The issue is that you have to call clearbox on any links that are pulled into the page via ajax. When you call clearbox initially, jQuery grabs all of the elements from your selector and adds the functionality to them. If you then, pull in additional links via ajax (or even add them to the dom later), then clearbox has not been instantiated for those elements.
The jQuery .live() function fixes this for elements added to the dom, but clearbox is not built to use .live(). Therefore, you'll have to call clearbox on any additional links that are added to the page separately.
http://api.jquery.com/live/
EDIT
I've had a quick look at the clearbox doc page: http://www.clearbox.hu/index_en.html
It states that you can call CB_Init() to add clearbox to new items:
Using the script with AJAX
If you load new content with AJAX in your
webpage without refreshing it and you want, that the clearbox work
with the new content too, you have to call CB_Init(); function AFTER
your AJAX content-load.
So you can just do this:
$("download").html(" \
<span style='color:white'> \
<a href='img/26.jpg' rel='clearbox' title='Caption'>View Screenshots</a> \
</span><br /> \ ");
CB_Init();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: static or objects what's better in this case? I have WCF method that looks something like this:
public GetRecordsResponse GetRecords(GetRecordsRequest request)
{
GetRecordsResponse response = new GetRecordsResponse();
Util.GetRecords.VerifyMandatoryParameters(request);
//make sure mandatory parameters have correct values.
Util.GetRecords.SetDefaultValues(request);
Util.GetRecords.SetDefaultResponseValues(request, response);
DataReader.GetRecords.GetAllRecords(request, response);
return response;
}
Is it wrong that i have the entire DAL and many Helper methods as static classes and methods? If so, why?
A: This is subjective matter, but I think that static methods are evil in general (except very few situations).
Here is a link to a talk discussing why this is a problem:
http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/
Although the speaker is talking about Java, but it is quite similar language, and static methods are being used almost the same way in both languages.
A: As a result of using Static method you can access instance variables like properties and fields this means you need to pass the request to every method.
If you used instances of GetRecords you could do somehting liek
GetRecords gr = new gr();
gr.Request = request;
gr.VerifyMandatoryParameters();
gr.SetDefaultValues();
gr.SetDefaultResponseValues(response);
gr.GetAllRecords();
Also if you implment a fluent interfaces you could have written it like this.
GetRecords gr = new gr();
gr.SetRequest(request)
.VerifyMandatoryParameters()
.SetDefaultValues()
.SetDefaultResponseValues(response)
.GetAllRecords();
But there's nothing "wrong" with what you did
A: In short, Yes.
I imagine that you are performing few to no unit tests against your code. If you plan on adding any, at any point; a statically accessed DAL will cause you no end of grief (I am dealing this exact scenario right now).
Instead, you should be passing in, say a DataAccessService interface, that can be mocked for testing, and implemented pointing to your actual data store in production.
So, I would expect your code to look more like:
public GetRecordsResponse GetRecords(GetRecordsRequest request, DataAccessService dataAccess)
{
var response = new GetRecordsResponse();
Util.GetRecords.VerifyMandatoryParameters(request);
Util.GetRecords.SetDefaultValues(request);
Util.GetRecords.SetDefaultResponseValues(request, response);
dataAccess.GetAllRecords(request, response);
return response;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Nested EditorTemplates in Telerik MVC Grid Edit Popup Window Not Displaying in Custom Edit Template I have a grid using AJAX DATABINDING.
When I issue a POPUP EDITING command with TEMPLATENAME SPECIFIED my NESTED EDITOR TEMPLATES are not populating.
My Models
namespace eGate.BackOffice.WebClient.Model
{
public class TemplateTesterModel
{
public int TemplateModelId { get; set; }
public string TemplateModelName { get; set; }
public List<UserRole> UserRoles { get; set; }
}
}
{
public class TemplateTesterModels : List<TemplateTesterModel>
{
}
}
My View
@model eGate.BackOffice.WebClient.Model.TemplateTesterModels
@Html.EditorFor(m=>m)
@( Html.Telerik().Grid<eGate.BackOffice.WebClient.Model.TemplateTesterModel>()
.Name("Grid")
.DataKeys(keys => { keys.Add(m=>m.TemplateModelId); })
.Columns(columns =>
{
columns.Bound(o => o.TemplateModelId);
columns.Bound(o => o.TemplateModelName).Width(200);
columns.Bound(o => o.UserRoles).ClientTemplate(
"<# for (var i = 0; i < UserRoles.length; i++) {" +
"#> <#= UserRoles[i].RoleName #> <#" +
"} #>")
;
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Text);
}).Width(180).Title("Commands");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("_SelectAjaxEditing", "TemplateTester")
.Insert("_InsertAjaxEditing", "Grid")
.Update("_SaveAjaxEditing", "TemplateTester")
.Delete("_DeleteAjaxEditing", "TemplateTester")
)
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("TemplateTesterModel"))
)
My Controller
namespace eGate.BackOffice.WebClient.Controllers
{
public class TemplateTesterController : Controller
{
public ActionResult Index()
{
return View(GetTemplateTesters());
//return View(new GridModel(GetTemplateTesters()));
}
private TemplateTesterModels GetTemplateTesters() {
TemplateTesterModels returnme = new TemplateTesterModels();
returnme.Add(new TemplateTesterModel());
returnme[0].TemplateModelId = 0;
returnme[0].TemplateModelName = "Template Tester 0";
returnme[0].UserRoles = new List<UserRole>();
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role1", IsChecked = true, Description = "Role for 1" });
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role2", IsChecked = false, Description = "Role for 2" });
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role3", IsChecked = false, Description = "Role for 3" });
return returnme;
}
[GridAction]
public ActionResult _SelectAjaxEditing()
{
return View(new GridModel(GetTemplateTesters()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _SaveAjaxEditing(int id)
{
return View(new GridModel(GetTemplateTesters()));
}
[GridAction]
public ActionResult _InsertAjaxEditing(){
return View(new GridModel(GetTemplateTesters()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _DeleteAjaxEditing(int id)
{
return View(new GridModel(GetTemplateTesters()));
}
}
}
My EditorTemplates
Shared/EditorTemplates/TemplateTesterModel.cshtml
@model eGate.BackOffice.WebClient.Model.TemplateTesterModel
<div>TemplateTesterModel Editor</div>
<div>@Html.EditorFor(m=>m.TemplateModelId)</div>
<div>@Html.EditorFor(m=>m.TemplateModelName)</div>
<div>Roles</div>
<div>@Html.EditorFor(m=>m.UserRoles)</div>
Shared/EditorTemplates/UserRole.cshtml
@model eGate.BackOffice.WebClient.Model.UserRole
<div>
I can has user role?
@Html.CheckBoxFor(m=>m.IsChecked)
</div>
This renders out as such:
As you can see the @Html.EditFor statements that precede the grid filter down through to the userrole EditorTemplate as expected. Additionally we can see that role data is in the grid because it is showing up in the role column.
But click the edit window and this is the result:
As you can see the UserRoles template is not populating with the roles on the UserRoles property of the TemplateTesterModel we're editing.
Am I missing something? Why is the .UserRoles property not populating in the telerik grid pop-up window?
A: This could be a "by design" decision of ASP.NET MVC. It does not automatically render display and editor templates for nested complex objects. I even have a blog post discussing this.
Long story short you need to create a custom editor template for the parent model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add new column to existing SSIS package
I've created an SSIS package using the Import/Export Wizard - it involves several tables with some of the original columns dropped(). It seems like I 'ignored' one too many columns, but I can't figure out how to get it back. When I go to edit the mappings, I can see the column name on the left, but not on the destination table. Any idea how to fix this without rebuilding the package?Any help is greatly appreciated!
A: SSIS validates package metadata often, and as such, it automatically notifies You whether You have to refresh source/destination metadata or not. (or maybe you have turned Work-Offline option on, in this case turn it off)
This leads me to conclusion that You instructed import/export wizard to make package create destination table if it does not exist. Since that column was not generated in the destination database at the moment of the first package execution, you will never see any new column in the destination. You have to manually add column to destination table in database (watch out for data type, collation, ... column should be the same as in source). Then package will recognize that column.
A: ^^^
On your destination server, you need to add the ignored column(s) to the table. Then when you go back into the mapping, the column will be available on the destination table.
ALTER TABLE
dbo.MySemiReplicatedTable
ADD
IForgotThisDamnColumn varchar(35) NULL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "Freeze" the slider Is it possible to "freeze" the slider (NSSlider)? I'd like to make my slider unmovable (with a fixed value) when I press the button "Start", which starts my application... And when I press the button "Stop", which terminates my apllication, I'd like the slider to become movable again.
Thanks for the answer!
A: Just use the enabled property:
yourSlider.enabled = NO; // this will "freeze"
yourSlider.enabled = YES; // this will "unfreeze"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Three Entity Constraint in Object Role Model in NORMA I am trying to model the constraint depicted in the ORM diagram below using NORMA for Visual Studio 2010:
Merchant transacts in a Currency if and only if that Merchant uses a Processor that supports that Currency.
According to this link, what I am trying to model is a join subset constraint. Here is an example from the link above:
Which reads as a Person can only work on a Project if that Person works in a Department that Spansors that Project.
That seems identical to what I am trying to model.
I've tried several combinations if adding a subset constraint, clicking one role then another, but always end up with errors such as:
*
*Constraint 'SubsetConstraint1' in model 'ORMModel1' has role players in column '1' with incompatible types.
*Constraint 'SubsetConstraint1' in model 'ORMModel1' has role players in column '2' with incompatible types.
How can I go about modeling this constraint?
A: You're heading in the right direction. You need to define a superset role pair and a subset role pair. Each pair has one Merchant role and one Currency role, and the order of these roles in the pairs must match. You can check the matching my clicking on the constraint; the roles are then highlighted in blue with 1,1 1,2 2,1 2,2 which shows the role sequences.
The superset Merchant role is the role of Merchant in "Merchant uses Processor".
The superset Currency role is the role of Currency in "Processor supports Currency".
The subset Merchant and Currency roles are the two roles of "Merchant transacts in Currency".
A similar example is the subset constraint on "DirectOrderMatch" in the Warehousing example here: ActiveFacts Example Models. Note the two arrow heads that point to PurchaseOrderItem and SalesOrderItem. In CQL, this constraint is expressed (in verbose form; that site shows the terse form):
some Purchase Order Item matches some Sales Order Item
only if that Purchase Order Item is for some Product that is in that Sales Order Item;
So, by way of comparison, your example written in CQL would read:
some Merchant transacts in some Currency
only if that Merchant uses some Processor that supports that Currency;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PowerShell Start-Job and Oracle I have a ps script (say Set-Data.ps1) that calls a ps Run.ps1 with Start-Job as :
Start-Job -FilePath Run.ps1 -ArgumentList 1, 2
In Run.ps1 I have a line of code as:
$cs = ...;
Write-Output "1";
$conn = New-Object Oracle.DataAccess.Client.OracleConnection($cs);
$conn.Open();
Write-Output "2";
From cmd prompt I run Set-Data.ps1.
The program never prints "2" from line ==> Write-Output "2";
The job stats keeps showing as Running.
Why is this so?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to sort items in ListView by column bound to an Observable Collection? How to sort items in ListView by column bound to an Observable Collection ?
I've looked all over the place and I can't find anything easy enough or simple on this.
A: Is the example here too complicated? It just shows how to use a ListCollectionView to provide the data in the correct order, and to perform the sorting.
A: You can use SortDescriptions in CollectionViewSource. Here is an example. If you want it dynamically, you need to code around this. but this should give you an idea.
List<Product> products = Client.GetProductList();
public ICollectionView ProductView = CollectionViewSource.GetDefaultView(products);
ProductView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Titanium Developer, Android Emulator - Passing Custom Arguments I seem to be plagued by an issue that a lot of people run into, when I run my Android Emulator it fails to have any usable internet connection. If I run the emulator manually and pass "-dns-server 8.8.8.8" it works just fine.
emulator.exe -dns-server 8.8.8.8 -avd {NAME}
What I'd like to do is add this "-dns-server 8.8.8.8" as a custom argument when launching the emulator through Titanium Studio. I've figured out how to do this in Eclipse for the Android SDK, but not through Titanium Studio as the same options are not available.
Titanium appears to launch the emulator with the following arguments:
\tools\emulator.exe -avd titanium_15_HVGA -port 5560 -sdcard C:\Users\dhiggins\.titanium\titanium_15_HVGA.sdcard -logcat *:d,* -no-boot-anim -partition-size 128
On a side note, it appears that if I setup my NIC to "Obtain Automatically" rather than use a static address, the Android Emulator works just fine with the internet. I, however, require a static address on my development machine.
A: I would first start with diagnosing the source of the problem on the static allocation. Does your static IP have the appropriate DNS server listed? When obtain automatically, there are several parameters DHCP provides, including the DNS server list.
In any case, it is fairly simple to update the commands to start the android emulator, at least for the Windows platform. I have to think that there is something similar in the mobile SDK for Apple.
Locate the mobile SDK folder. Under Win 7 it is C:\ProgramData\Titanium\mobilesdk. Under the mobile SDK folder open \android\builder.py and locate the following (search for -avd gets you right to it):
# start the emulator
emulator_cmd = [
self.sdk.get_emulator(),
'-avd',
avd_name,
'-port',
'5560',
'-sdcard',
self.sdcard,
'-logcat',
'*:d,*',
'-no-boot-anim',
'-partition-size',
'128' # in between nexusone and droid
]
debug(' '.join(emulator_cmd))
p = subprocess.Popen(emulator_cmd)
Edit this section and add one or more lines for your custom parameter(s).
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jquery / javascript: regex to replace instances of an html tag I'm trying to take some parsed XML data, search it for instances of the tag and replace that tag (and anything that may be inside the font tag), and replace it with a simple tag.
This is how I've been doing my regexes:
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //Test against valid email
console.log('regex: ' + emailReg.test(testString));
and so I figured the font regex would be something like this:
var fontReg = /'<'+font+'[^><]*>|<.'+font+'[^><]*>','g'/;
console.log('regex: ' + fontReg.test(testString));
but that isn't working. Anyone know a way to do this? Or what I might be doing wrong in the code above?
A: If I understand your problem correctly, this should replace all font tags with simple span tags using jQuery:
$('font').replaceWith(function () {
return $('<span>').append($(this).contents());
});
Here's a working fiddle: http://jsfiddle.net/RhLmk/2/
A: I think namuol's answer will serve you better then any RegExp-based solution, but I also think the RegExp deserves some explanation.
JavaScript doesn't allow for interpolation of variable values in RegExp literals.
The quotations become literal character matches and the addition operators become 1-or-more quantifiers. So, your current regex becomes capable of matching these:
# left of the pipe `|`
'<'font'>
'<''''fontttt'>
# right of the pipe `|`
<@'font'>','g'
<@''''fontttttt'>','g'
But, it will not match these:
<font>
</font>
To inject a variable value into a RegExp, you'll need to use the constructor and string concat:
var fontReg = new RegExp('<' + font + '[^><]*>|<.' + font + '[^><]*>', 'g');
On the other hand, if you meant for literal font, then you just needed:
var fontReg = /<font[^><]*>|<.font[^><]*>/g;
Also, each of those can be shortened by using .?, allowing the halves to be combined:
var fontReg = new RegExp('<.?' + font + '[^><]*>', 'g');
var fontReg = /<.?font[^><]*>/g;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: reload current page in asp.net I have a session variable that changes some things about how a page looks. I have a button that changes the value of this session variable. But ... the onClick event happens after page load, so by the time I update the session variable based on the button click, it's too late, the page has already been loaded.
Theoretically I could put all the logic about changing the display into a function and call it from page load, and then call it again from the onclick after the variable as been updated. But this is impractical: there are many user controls that check the value, used on many different pages in different combinations. I would have to hard-code the list of user controls on each page, and if someone added a new user control to a particular page, they'd have to remember to update this function, which is lame.
Is there a way to force a page reload? (I can use response.redirect back to myself and it works. If all else fails I guess this is what I'll do. But it means an extra round trip to the server, which is clumsy.)
Is there a way to process the onclick before the page load?
Some other magic solution?
A: If you have to change the look and feel of a page based on a specific value which can change, then you should have dedicated functions that set up the look and feel in a single unified place, and then you call those functions in every case where a value that affects the look and feel is called.
Examples:
private void SetDivVisibility()
{
// display logic here based on variables
}
private void MyControl_Click(...)
{
myvalue = blah;
SetDivVisibility();
}
It helps to bear in mind that the actual rendering of the page is last thing that happens, after both page load AND event processing.
A:
Theoretically I could put all the logic about changing the display into a function and call it from page load
That's how you should do it. Cleanup your logic and markup - refactor and keep it DRY. That should help.
I can use response.redirect back to myself
That's the other option. Yes, a round trip is nasty.
A: you may put your code of styling your page in a void called by the page_load normally and called again from buttonclick
or call response.redirect to same url
or even onClick is client side use window.location.href
A: A design with a layout predicated on the existence of a session variable which won't exist until after it's been render is a huge design error. I like to call it the "Chicken or the Egg" syndrome. (yes, you can quote me.. ;)
I'd argue that your controls shouldn't get their layout completed in the on render. Instead, use a method (similar to databinding) where you can "rebind" the controls with the new session value on demand. This method would show/hide things based on the updated values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: expanding Dots pushing link or text down I created a spanned line with dots to fill in between text of links and phone number, but i cant get it so that if i have to many dots that the text does not go underneath. The problem is on some different brwosers and computers the .... will look fine or it will push it out of the way. How wouldi go about making it so the dots.... would span and the text would not go below the width its supposed to.
<style type="text/css">
#contactInfo {
margin:auto;
width: 480px;
height: auto;
}
</style>
<div id="contactInfo">
<p>Email: .........................................................................<a href="mailto:info@hereistheemail.com" class="redBold">info@hereistheemail.com</a></p>
<p>Phone: ..................................................................................<span class="redBold">888-888-8888</span></p>
</div>
I tried putting less dots buton some browsers it just doesnt look right.
A: A better way to do what you want is with a definition list. This will semantically present the information you want and not require you to type out a bunch of dots:
HTML
<dl>
<dt>Phone</dt>
<dd>123-4567</dd>
<dt>Email</dt>
<dd>info@email.com</dd>
</dl>
CSS
dl {
/* Adjust as needed. Note that dl width + dt width must not be greater */
width: 300px;
}
dt {
/* The definition term with a dotted background image */
float: left;
clear: right;
width: 100px;
background: url(1-pixel-dot.gif) repeat-x bottom left;
}
dd {
/* The definition description */
float: right;
width: 200px;
}
You can see an example of it here.
A: You will have to try and create a workaround for this, instead of just using characters.
Some solutions could be using a background image that repeats itself inside some div/span: http://www.htmlforums.com/html-xhtml/t-toc-style-dotted-line-tab-fill-in-html-103639.html
Or you could think of creating a span between the word e-mail and the e-mail address and try to create a border-bottom: dotted 1px black or something equivalent. Or maybe put the information in a table and create one td with that border-bottom.
Another solution would be to check the number of dots needed with some javascript, but this is most certain not robust at all and will not justify-align your content.
So, be creative with a solution. Filling the line with characters is probably not the way to go.
A: Try this:
#contactInfo {
[ your other styles ]
white-space: nowrap;
}
A: Another method is with position:absolute
Demo
#contactInfo p
{
position:relative;
}
#contactInfo span,#contactInfo a
{
position:absolute;
right:0px;
}
Edit (cleaned up version)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Inspect element attributes with Google Chrome Although the Google Chrome developer tools show the properties of a selected element, it doesn't list the attributes.
Am I missing something?
A: Under properties, click the top expandable menu. It should have all the attributes.
A: Just right click on the element you want to inspect and choose "Inspect element".
In the bottom panel select Elements tab. It will show the DOM element with the attribures in the form of HTML.
A: *
*Open Inspect Element by right clicking on the element or any other way you want.
*Find the element you want to add the attribute in.
*Right click on the attribute in Inspect Element. Click Add Attribute
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I display the same content on two pages with different styles? There are two related sites.
Each has its own CSS.
Some of the content (contact info, etc) needs to be appear on a page in each site, but with the appropriate styles applied.
Is there a way to do this without duplicating the content?
A: Define the same css classes in your two CSS files, and at the top of each page, bring in the proper file.
For the first page:
<link rel="Stylesheet" type="text/css" href="style/site1.css" />
Then the other page:
<link rel="Stylesheet" type="text/css" href="style/site2.css" />
A: This is content management issue, and the correct solution for you will depend on what sort of content management you're using for these sites. If you're not using any CMS, you could still use something like PHP or JavaScript to dynamically pull content from one of the sites and display it on the second.
For example, using jQuery you could do something like this on the second site:
$('#container-element').load('http://first-site/shared-content.html');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I retrieve a column value from a table into a PHP variable? This is my current code:
$thisImage = "Select * from `posts` where `id`=" . $id;
$imgRow = $d->GetData($thisImage); // returns one record through mysql_get_assoc
$scode = "#"; // init $scode
if (is_array($imgRow))
$scode = $imgRow["shortcode"]; // "shortcode" is the name of a column
This is where I'm getting stuck, as I am getting an "Undefined index" error.
As I am always expecting only one record ($id is unique), if I do this instead:
if (is_array($imgRow))
$scode = $imgRow[0]; //
I see that $scode is "Array", which is NOT the value that is in the "shortcode" column for that row.
Any pointers?
A: Even though it returns one record, I suspect it is still doing so as a multidimensional array, where each row has a numeric index (even if it's just one row at [0]) and columns are indexed by name. Try instead:
if (is_array($imgRow))
$scode = $imgRow[0]["shortcode"];
Always use print_r() or var_dump() to examine the structure of your arrays and objects when debugging.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I Insert records in database multiple Tables using winforms c# I have a winform which i have attached here.. When i Insert record in Customer table, I also want to add the record in the orderlineitems table in my database as of which the record in the Order table will also be inserted.
I have inserted the record in Customer table but when i insert record in OrderLineItems table, it shows an error.
I also wanted to ask that, my OrderLineItems Table in database contains columns as :
*
*ID(pk)
*OrderID(pk)
*Quantity
*Particular
*Rates
*Status
On my Form, I have only quantity, particular and rates fields from which i can get their values but i dont have Status and Orderid values on my winform. how do i get the values of status and orderId then?
My Code is:
private void buttonInsert_Click(object sender, EventArgs e)
{
string SQL = String.Format("Insert into Customer values ('{0}','{1}','{2}')", textBoxName.Text, textBoxContactNo.Text, textBoxAddress.Text);
//string SQL1 = String.Format("Insert into Order values ({0},'{1}','{2}',{3})",);
DataManagementClass dm = new DataManagementClass();
int result = dm.ExecuteActionQuery(SQL);
if (result > 0)
{
for (int i = 0; i < recordsDataGridView.RowCount ; i++)
{
string query = String.Format("Insert into OrderLineItems values({0},'{1}','{2}','{3}',{4})",7,QuantityColumn, ParticularColumn, RatesColumn,1);
dm.ExecuteActionQuery(query);
}
//string query = String.Format("Insert into OrderLineItems values ('{0}','{1},'{2}'
}
What am i doing wrong here. please guide me the correct way.
Thanx..
A: Suggest a few enhancements to get your business logic working and maintainable:
*
*write a stored procedure for your CreateCustomer and CreateLineItem routines in your database.
*use a SqlCommand and its Parameters collection. Stop whatever you're doing right now and guard against SQL injection.
*remove all this code from the button click event.
*create new methods like CreateCustomer and CreateLineItems. Call these method from your button click handler method.
private void buttonInsert_Click(object sender, EventArgs e)
{
int result = CreateCustomer(textBoxName.Text.Trim(),
textBoxContactNo.Text.Trim(),
textBoxAddress.Text.Trim());
if (result > 0)
{
foreach(var row in recordsDataGridView.Rows)
{
CreateLineItem(quantity, particulars, rates);
}
}
A: You are inserting values like this: '{1}','{2}','{3}'
This leads me to assume you are inserting string values.
If there is an apostroph in your string values, it will cause a syntax error.
Try
yourstring.replace("'", "''")
on the arguments.
Also, do as p.campbell suggest..
Use parameters to prevent SQL injection..
Somebody might malicously take advantage of your code's open security holes..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Question on Specular reflection behaviour? Why Specular reflected light will be in bright color(usually white) while other parts of the object are reflecting the perceived color wavelength?
A: From a physical perspective, this is because:
*
*specular reflection results from light bouncing off the surface of material
*diffuse reflection results from light bouncing around inside the material
Say you have a piece of red plastic with a smooth surface. The plastic is red because it contains a red dye or pigment. Incoming light that enters the plastic tends to be reflected if red, or absorbed if it is not; this red light bounces around inside the plastic and makes it back out in a more or less random direction (which is why this component is called "diffuse").
On the other hand, some of the incoming light never makes it into the plastic to begin with: it bounces off the surface, instead. Because the surface of the plastic is smooth, its direction is not randomized: it reflects off in a direction based on the mirror reflection angle (which is why it is called "specular"). Since it never hits any of the colorant in the plastic, its color is not changed by selective absorption like the diffuse component; this is why specular reflection is usually white.
I should add that the above is a highly simplified version of reality: there are plenty of cases that are not covered by these two possibilities. However, they are common enough and generally applicable enough for computer graphics work: the diffuse+specular model can give a good visible approximation to many surfaces, especially when combined with other cheap approximation like bump mapping, etc.
Edit: a reference in response to Ayappa's comment -- the mechanism that generally gives rise to specular highlights is called Fresnel reflection. It is a classical phenomenon, depending solely on the refractive index of the material.
If the surface of the material is optically smooth (e.g., a high-quality glass window), the Fresnel reflection will produce a true mirror-like image. If the material is only partly smooth (like semigloss paint) you will get a specular highlight, which may be narrow or wide based on how smooth it is at the microscopic level. If the material is completely rough (either at a microscopic level or at some larger scale which is smaller than your image resolution), then the Fresnel reflection becomes effectively diffuse, and cannot be readily distinguished from other forms of diffuse reflection.
A: Its a question of wavelength absorption vs reflection.
First, specular reflections do not exist in the real world. Everything you see is mostly reflected light (the rest being emissive or other), including diffuse lighting. Realistically, there is no real difference between diffuse and specular lighting : its all a reflection. Also keep in mind that real world lighting is not clamped to the 0-1 range as pixels are.
Diffusion of light reflected off of a surface is caused by the microscopic roughness of the surface (microfacets). Imagine a surface is made up of millions of microscopic mirrors. If they are all aligned, you get a perfect polished mirror. If they are all randomly oriented, light is scattered in every direction and the resulting reflection is "blurred". Many formulas in computer graphics try to model this microscopic surface roughness, like Oren–Nayar, but usually the simple Lambert model is used because it is computationally cheap.
Colors are a result of wavelength absorption vs reflection. When light energy hits a material, some of that energy is absorbed by that material. Not all wavelengths of the energy are absorbed at the same rate however. If white light bounces off of a surface which absorbs red wavelengths, you will see a green-blue color. The more a surface absorbs light, the darker the color will appear as less and less light energy is returned. Most of the absorbed light energy is converted to thermal energy, and is why black materials will heat up in the sun faster than white materials.
Specular in computer graphics is meant to simulate a strong direct light source reflecting off of a surface like it may do in the real world. Realistically though, you would have to reflect the entire scene in high range lighting and color depth, and specular would be the result of light sources being much brighter than the rest of the reflected scene and returning a much higher amount of light energy after one or more reflections than the rest of the light from the scene. That would be quite computationally painful though! Not feasible for realtime graphics just yet. Lighting with HDR environment maps were an attempt to properly simulate this.
Additional references and explanations :
Specular Reflections :
Specular reflections only differ from diffuse reflections by the roughness of a reflective surface. There is no inherent difference between them, both terms refer to reflected light. Also note that diffusion in this context simply means the scattering of light, and diffuse reflection should not be confused with other forms of light diffusion such as subsurface diffusion (commonly called subsurface scattering or SSS). Specular and diffuse reflections could be replaced with terms like "sharp" reflections and "blurry" reflections of light.
Electromagnetic Energy Absorption by Atoms :
Atoms seek a balanced energy state, so if you add energy to an atom, it will seek to discharge it. When energy like light is passed to an atom, some of the energy is absorbed which excites the atom, causing a gain in thermal energy (heat), the rest is reflected or transmitted (passes "through"). Atoms will absorb energy at different wavelengths at different rates, and the reflected light with modified intensity per wavelength is what gives color. How much energy an atom can absorb depends on it's current energy state and atomic structure.
So, in a very very simple model, ignoring angle of incidence and other factors, say i shine RGB(1,1,1) on a surface which absorbs RGB(0.5,0,0.75), assuming no transmittance is occurring, your reflected light value is RGB(0.5,1.0,0.25).
Now say you shine a light at RGB(2,2,2) on the same surface. The surface's properties have not changed. Reflected light is RGB( 1.5 , 2.0 , 1.25 ). If the sensor receiving this reflected light clamps at 1.0, then perceived light is RGB(1,1,1), or white, even though the material is colored.
Some references :
page at www.physicsclassroom.com
page on ask a scientist
Wikipedia : Atoms
Wikipedia : Energy Levels
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: HttpContext.Request.UrlReferrer null when changing domain Hi have a website that is host on 2 servers, on in Europe for the french version of the website (.fr) and the other in the Us for the other versions (.com). When I do a RedirectResult("http://domain.fr") from my .com website in a controller, my Referrer is null is it normal?
I think that I will have to post a querystring from a domain to an other so I will be able to know when it's comming from this site.
A: urlreferrer is collected from the client side browser
are you make sure that your test request site A from a link in Site B and not response.redirect
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you specify Cascade Delete for base tables using fluent api? Question: How do I get EF 4.1 to specify the ON DELETE CASCADE option on the foreign key constraint using the fluent api for base tables? I know how to do it with relationships to other tables, but how do I have it generate this for TPT (Table Per Type) tables?
Description:
Let me point out, I am not referring to foreign key relationships. With my DbContext I always use Mapping objects for my entities, only because in most cases I prefer to be explicit as opposed to accepting the convention approach. That being said, all the configuration for my TPT tables are being handled in the EntityTypeConfiguration<SomeEntityClass> classes.
When I define a TPT relationship by creating a new class which derives from another, the ON DELETE CASCADE does not get generated in the SQL constraint, which is the problem.
Have a look at the following code...
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
public class OtherPerson : Person
{
public string SomeOtherProperty { get; set; }
}
public class PersonMap : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Person>
{
public PersonMap()
{
this.HasKey(t => t.PersonId); // Primary Key
this.Property(t => t.PersonId)
.HasColumnName("PersonId") // Explicitly set column name
.IsRequired() // Field is required / NOT NULL
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); // Specify as Identity (Not necessary, but I'm explicit)
this.Property(t => t.Name)
.HasColumnName("Name") // Explicitly set column name
.IsRequired() // Field is required / NOT NULL
.HasMaxLength(50); // Max Length
this.ToTable("People"); // Map to table name People
}
}
public class OtherPersonMap : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<OtherPerson>
{
public OtherPersonMap()
{
this.Property(t => t.SomeOtherProperty)
.HasColumnName("SomeOtherProperty") // Explicitly set column name
.IsRequired() // Field is required / NOT NULL
.HasMaxLength(10); // Max Length
this.ToTable("OtherPeople"); /* Map to table name OtherPeople
* This also causes TPT to create a shared primary key from the base table
* and double serving as a foreign key to base table.
*/
}
The above code is really simple. I have 2 types and they are correctly create in the database. If I create a new OtherPerson and save to the database it correctly creates 2 records, 1st a record in the People table and another in the OtherPeople table with a shared primary key which is also the foreign key from OtherPeople to People.
Now, the DbContext or EF rather, correctly deletes both records if I delete the OtherPerson within my code. However, should I delete the record directly from the database, an orphan record is left behind in the People table.
So, how do I get the ON DELETE CASCADE to be specified for the foreign key constraints generated for base tables using the fluent api?
Sorry the question is so long but I just wanted to describe the best I could my problem.
Thanks in advance.
A:
Now, the DbContext or EF rather, correctly deletes both records if I
delete the OtherPerson within my code. However, should I delete the
record directly from the database, an orphan record is left behind in
the People table.
You seem to say that you want to delete a record from the OtherPeople table (derived entity) and cascading delete should ensure that the corresponding record in the People table (base entity) will be deleted as well.
But this is the wrong direction. EF creates a relationship and foreign key constraint which goes from the base entity table to the derived entity table, so: The PK table is People and the FK table is OtherPeople. With a cascading delete on this relationship you could only ensure that an OtherPeople record is deleted when the corresponding People record will be deleted, not the other way around.
This relationship alone - also without cascading delete - makes sure that you cannot get orphan records in the OtherPeople table because it would violate the FK constraint. (You cannot delete a Person without the related OtherPerson.)
For your special purpose you would actually need a second FK constraint in the database where PK table is OtherPeople and the FK table is People. This relationship isn't created by EF TPT mapping at all and it also would only work if the PK on People is not an identity (at least in SQL Server). But it is an identity in your model. So you can't even create this relationship with cascading delete in the database, not to mention with EF.
Back to the relationship which EF actually creates in the database (which is not the one you want with cascading delete) I don't think that there is a mapping option in EF Code-First which would allow you to control the relationship needed for TPT mapping. The only way is to do it directly in the database or - if you want to generate the database from your Code-First model - write a raw SQL statement (which sets up the cascading delete) in a custom initializer and send this to the database after all tables and relationships have been created.
Somehow in the database People is like Order and OtherPeople is like OrderItem- just not a 1-to-* but a 1-to-0..1 relationship. What you want is that the parent Order is deleted if the child OrderItem is deleted which means that the dependent will delete the principal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: QPointer in multi-threaded programs According to http://doc.qt.io/qt-5/qpointer.html, QPointer is very useful. But I found it could be inefficient in the following context:
If I want to show label for three times or do something else, I have to use
if(label) label->show1();
if(label) label->show2();
if(label) label->show3();
instead of
if(label) { label->show1();label->show2();label->show3(); }
just because label might be destroyed in another thread after label->show1(); or label->show2();.
Is there a beautiful way other than three ifs to get the same functionality?
Another question is, when label is destroyed after if(label), is if(label) label->show1(); still wrong?
I don't have experience in multi-threaded programs. Any help is appreciated. ;)
A: I think the only safe way to do it is to make sure you only access your QWidgets from within the main/GUI thread (that is, the thread that is running Qt's event loop, inside QApplication::exec()).
If you have code that is running within a different thread, and that code wants the QLabels to be shown/hidden/whatever, then that code needs to create a QEvent object (or a subclass thereof) and call qApp->postEvent() to send that object to the main thread. Then when the Qt event loop picks up and handles that QEvent in the main thread, that is the point at which your code can safely do things to the QLabels.
Alternatively (and perhaps more simply), your thread's code could emit a cross-thread signal (as described here) and let Qt handle the event-posting internally. That might be better for your purpose.
A: Neither of your approaches is thread-safe. It's possible that your first thread will execute the if statement, then the other thread will delete your label, and then you will be inside of your if statement and crash.
Qt provides a number of thread synchronization constructs, you'll probably want to start with QMutex and learn more about thread-safety before you continue working on this program.
Using a mutex would make your function would look something like this:
mutex.lock();
label1->show();
label2->show();
label3->show();
mutex.unlock()
As long as your other thread is using locking that same mutex object then it will prevented from deleting your labels while you're showing them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to install certificates on other's machine? On my machine, I’m using a signed application with an installed certificate to get a trusted publisher dialog from Windows. I’ve created a certificate with makecert.exe and installed it to the certification store in windows. From there, I’ve exported the PFX and signed with signtool.exe my application. In order to get the same trusted publisher dialog on another machine, a certificate is necessary. Instead of installing the certificate by hand, an installer should accomplish the importation of the certificate. Unfortunately, the windows installer doesn’t support this feature. Because of that, I’m looking for a solution like a classical API command in windows. Is there something built-in in windows to make it easier or something comparable?
A: To install certificate with respect of MSI setup you have to use custom actions. If you not familiar with custom actions I recommend you to use the simplest custom action which allows you to start an exe. It can be an existing utility like CertUtil.exe (see here some examples and try certutil -importPFX -? to see help about the import of PFX files).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a margins editor component like the one in Microsoft word I have a Java Swing application that i want to create a nice component in it like a component in Microsoft word. In Microsoft word you can change the margins of your document like in here :
The trick here is that if you change the Top margins to (Let's say) 1.5" then the Preview image will change to show this, so the lines will move down a bit in the image to show that change in the margins so the user can feel how much his document will be affected by this change. So for example if i change the left margin to (4.0") the image will look like this :
What i did is create 2 images a blank page image + another image that contains lines only(Lines image), like these 2 images :
I inserted each image in a JLabel above each other, and now when i change the JSpinner top margin value, i keep the "blank page" image fixed, but i change the border of the "lines image" to move it down a bit. The trick worked fine for the top margin, but the behavior goes totally wrong if i change the bottom/right/left margins.
Here is my code that i apply when changing any JSpinner value :
private void marginSpinnerStateChanged() {
//1. Get the approximate values of all margins :
int topMargin = (int)( Float.valueOf( topSpinner.getValue().toString() ) * 8 );
int bottomMargin = (int)( Float.valueOf( bottomSpinner.getValue().toString() ) * 8 );
int leftMargin = (int)( Float.valueOf( leftSpinner.getValue().toString() ) * 8 );
int rightMargin = (int)( Float.valueOf( rightSpinner.getValue().toString() ) * 8 );
//2. Apply all specified margins to the lines label :
linesLabel.setBorder( new EmptyBorder( topMargin, leftMargin, bottomMargin, rightMargin ) );
}
Can you help me continue this to work right ?
A: If you notice, they don't shift the textual image. Instead, they only show half of it. This is simple image manipulation. For a good example, see this.
A: You could just draw the image on top of the paper and scale the image as you go. So you would override the paintComponent() method of a JComponent to do something like:
g.drawImage(image, x, y, width, height, null);
x - would be the left margin
y - would be the top margin
width - would be (maxWidth - leftMargin - rightMargin)
height - would be (maxHeight - topMargin - bottomMargin)
If you don't like scaling the image you can always use a BufferedImage and then use the getSubImage(...) method to get an image the desired size to be painted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java, "Variable name" cannot be resolved to a variable I use Eclipse using Java, I get this error:
"Variable name" cannot be resolved to a variable.
With this Java program:
public class SalCal {
private int hoursWorked;
public SalCal(String name, int hours, double hoursRate) {
nameEmployee = name;
hoursWorked = hours;
ratePrHour = hoursRate;
}
public void setHoursWorked() {
hoursWorked = hours; //ERROR HERE, hours cannot be resolved to a type
}
public double calculateSalary() {
if (hoursWorked <= 40) {
totalSalary = ratePrHour * (double) hoursWorked;
}
if (hoursWorked > 40) {
salaryAfter40 = hoursWorked - 40;
totalSalary = (ratePrHour * 40)
+ (ratePrHour * 1.5 * salaryAfter40);
}
return totalSalary;
}
}
What causes this error message?
A: I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:
String cannot be resolved to a variable
With this Java code:
if (true)
String my_variable = "somevalue";
System.out.println("foobar");
You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?
Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.
If you put braces around the conditional block like this:
if (true){
String my_variable = "somevalue"; }
System.out.println("foobar");
Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.
A: If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)
The two variables you are having trouble with are passed as parameters to the constructor.
The error message is because 'hours' is out of scope in the setter.
A: public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: GZipStream effectivness I am trying to save big UInt16 array into a file. positionCnt is about 50000, stationCnt is about 2500. Saved directly, without GZipStream, the file is about 250MB which can be compressed by external zip program to 19MB. With the following code the file is 507MB. What do I do wrong?
GZipStream cmp = new GZipStream(File.Open(cacheFileName, FileMode.Create), CompressionMode.Compress);
BinaryWriter fs = new BinaryWriter(cmp);
fs.Write((Int32)(positionCnt * stationCnt));
for (int p = 0; p < positionCnt; p++)
{
for (int s = 0; s < stationCnt; s++)
{
fs.Write(BoundData[p, s]);
}
}
fs.Close();
A: For whatever reason, which is not apparent to me during a quick read of the GZip implementation in .Net, the performance is sensitive to the amount of data written at once. I benchmarked your code against a few styles of writing to the GZipStream and found the most efficient version wrote long strides to the disk.
The trade-off is memory in this case, as you need to convert the short[,] to byte[] based on the stride length you'd like:
using (var writer = new GZipStream(File.Create("compressed.gz"),
CompressionMode.Compress))
{
var bytes = new byte[data.GetLength(1) * 2];
for (int ii = 0; ii < data.GetLength(0); ++ii)
{
Buffer.BlockCopy(data, bytes.Length * ii, bytes, 0, bytes.Length);
writer.Write(bytes, 0, bytes.Length);
}
// Random data written to every other 4 shorts
// 250,000,000 uncompressed.dat
// 165,516,035 compressed.gz (1 row strides)
// 411,033,852 compressed2.gz (your version)
}
A: Not sure what version of .NET you're running on. In earlier versions, it used a window size that was the same size as the buffer that you wrote from. So in your case it would try to compress each integer individually. I think they changed that in .NET 4.0, but haven't verified that.
In any case, what you want to do is create a buffered stream ahead of the GZipStream:
// Create file stream with 64 KB buffer
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None, 65536);
GZipStream cmp = new GZipStream(fs, CompressionMode.Compress);
...
GZipStream cmp = new GZipStream(File.Open(cacheFileName, FileMode.Create), CompressionMode.Compress);
BufferedStream buffStrm = new BufferedStream(cmp, 65536);
BinaryWriter fs = new BinaryWriter(buffStrm);
This way, the GZipStream gets data in 64 Kbyte chunks, and can do a much better job of compressing.
Buffers larger than 64KB won't give you any better compression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Configure one app to be built using two Android name spaces? I have an app that, for release, needs building as two apps. The app will self-reconfigure based on the app's namespace, so I just need to build two versions, each with its own slightly different namespace.
I obviously want to avoid changing source code package names, and would like to change the name space in one place so building either version is quick and easy.
Can I simply change the package name in the <manifest> tag in the Android manifest, making sure my references are fully qualified? Are there any gotchas with doing this?
A: Have two separate application projects, with separate package names, and have the common functionality - the bulk of your code - in a shared library project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I reauthenticate with Facebook after the OAuth 2.0 changes to the sdk? In our app we had some actions that we required the user to reauthenticate before proceeding. We used code like below to make this happen.
FB.login(
function(response) { /* code here */ },
{auth_type: 'reauthenticate', auth_nonce: '...'}
);
It looks like the auth_type option is no longer supported, because I am getting the following log message: 'FB.login() called when user is already connected.' and the user is not being asked to reauthenticate.
Does anyone have any ideas how to reauthenticate after the changes for OAuth 2.0?
A: It appears that, for the time being (and I qualify that because Facebook seems to change their API response on a whim), you can get auth_type: reauthenticate to work properly IF you also specify permissions (the scope parameter in OAuth 2.0). Check out this example:
http://www.fbrell.com/saved/a78ba61535bbec6bc7a3136a7ae7dea1
In the example, click Run Code, and then try the "FB.login()" and "FB.login() with Permissions" buttons. Both are coded to use auth_type: reauthenticate, but only the latter actually gives you the FB prompt once you are logged in.
Here are the relevant examples:
// DOES NOT PROMPT
document.getElementById('fb-login').onclick = function() {
FB.login(
function(response) {
Log.info('FB.login callback', response);
},
{ auth_type: 'reauthenticate' }
);
};
// PROMPTS AS EXPECTED
document.getElementById('fb-permissions').onclick = function() {
FB.login(
function(response) {
Log.info('FB.login with permissions callback', response);
},
{ scope: 'offline_access', auth_type: 'reauthenticate' }
);
};
So, the answer is, Yes, auth_type: reauthenticate DOES work, but ONLY if you also specify a valid scope parameter. (And yes, I tried it with an empty scope, and it acted the same as not using scope at all.)
A: You can use an iframe to make sure the cookie is always valid.
facebook auto re-login from cookie php
A: Using FacebookRedirectLoginHelper::getReAuthenticationUrl everything works fine.
Internally the method put 'auth_type' => 'reauthenticate' and pass also all the permissions required.
Now the issue is that only prompt to the user to re-enter the password without the possibility to "switch" between users or without the possibility to insert also the username.
Does someone found a solution for this issue?
I manage an application with multi accounts and when the user need to generate again the token this is an issue :(
Thanks, Alex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS - UIWebView - Need Submitted form to Open in Safari I have been developing an HTML5 / Javascript webapp for the iOS platform. I am relatively new to Objective and XCode, but I know my way around the program. I am attempting to have the UIWebView open a form, once submitted (submit button) in Safari as opposed to opening it in the current UIWebView.
The code below is suggested for opening standard <a> tags in Safari:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
( original post here )
I have tried adapting this code specifically for submitted forms like so:
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeFormSubmitted ) {
[[UIApplication sharedApplication] openURL:[request URL]];
return YES;
}
if ( inType == UIWebViewNavigationTypeFormResubmitted ) {
[[UIApplication sharedApplication] openURL:[request URL]];
return YES;
}
return YES;
}
And FYI I have switched the return values of each IF statement to YES / NO, however this doesn't seem to be the issue... Any thoughts? Code? Theory? Thank You!
A: The following achieved the "Open in Safari" result I was looking for.
First I implemented UIWebViewDelegate protocol by adding webView.delegate = self; to my viewDidLoad declaration:
appViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
if (htmlData) {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle bundlePath];
NSString *fullPath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:path];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]];
webView.delegate = self;
}
}
Secondly I added the following:
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request
navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = [[request URL] retain];
if (navigationType == UIWebViewNavigationTypeFormSubmitted || navigationType == UIWebViewNavigationTypeFormSubmitted)
{
return ![[UIApplication sharedApplication] openURL:url];
}
return YES;
}
One point of curiosity was that XCode returned the following warning flag:
warning: class 'appViewController' does not implement the 'UIWebViewDelegate' protocol
Not sure why... but! The app now opens the results of the submitted form in Safari.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: One to many mapping. NHibernate I was looking at 'NHibernate 3 Beginner's Guide' book and found interesting tip:
In a real life inventory application, you will probably want to avoid
putting a Products collection on the Category entity, as it is
possible that a category can have hundreds, if not thousands, of
associated products. To load the whole, huge collection of products
for a given category would be unwise and would lead to an application
having unsatisfactory response times.
Tip was right after an example of one-to-many relationships building. The entities were Product and Category. The example is quite straightforward:
public class Category : Entity // Entity probably contains an `Id` property
{
private List<Products> products;
public String CategoryName { get; set; }
public String Description { get; set; }
public IEnumerable<Product> Products { get { return products; } }
}
public class Product : Entity
{
public Decimal UnitPrice { get; set; }
public String ProductName { get; set; }
public Category Category { get; set; }
}
So what is the real life example of one-to-many relationships?
Would it be enough for the example just to put Category inside a product entity as a String property?
A: You may want to have a look a the lazy property of Nhibernate.It allows you not to load that property always unless we explicitly asks for it.
Nhibernate Lazy
A: The idea is that if you avoid the IList property all-together, you can still get to the products for a category e.g. like the following:
var products = session.QueryOver<Product>().Where(p => p.Category == someCategory).List();
But you now have the possibility to do paging, filtering, getting the top product etc.:
var product = session.QueryOver<Product>().Where(p => p.Category == someCategory).OrderBy(p => p.Relevance).Take(1).SingleOrDefault();
which you do not have if it is a simple IList property. In general (in my experience), the less two-way ascociations you have, the better your querying granularity will be. Also, it reduces your complexity when it comes to saving.
A: Let's ask different question: what if your application should present categories in tree-view control, which upon expanding category node will list all products? When you want to display all products there's no other way than ... actually querying database and loading all products.
That's actually pretty common real-life scenario and one of easiest approaches is indeed to simply have Category.Products property. Of course there's nothing wrong with having such property, but the real question is how you should manage those objects.
Luckily, you don't have to pull all the products with single category pull. Category.Products can be marked to load lazily (as opposed to eagerly, more information can be found here). What this means is, loading category won't query database for its products. Instead, NHibernate will create proxy object for Products, which can be initialized later - when they are actually needed (think user expanding category node).
And to answer your question...
If single product is bound to exactly one category, then it's good real-life one-to-many relation example. However, if product can be described by more than one category, it's many-to-many relation then.
A: I think the quote will say that you should not use the Products property in Category class at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC2 scaffolding - can't see any data I'm having a problem seeing any data in my MVC2 application.
I'm using your typical scaffolding setup, but when I view the index or details page I see no data at all.
I'm sure I'm missing something simple here as I get no errors when compiling or running.
Here is my model(Users.cs):
public class Users
{
public string UserName { get; set; }
[Required(ErrorMessage = "The Customer ID is required.")]
public string CustomerID { get; set; }
}
Here are the 2 controller(UsersController.cs) actions that matter:
public class UsersController : Controller
{
static List<Users> users = new List<Users>();
//
// GET: /Users/
public ActionResult Index()
{
return View(users);
}
//
// GET: /Users/Details/5
public ActionResult Details(Users u)
{
return View(u);
}
}
And here are my views.
Users/Index.aspx
<table>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new { id=item.UserName }) %> |
<%= Html.ActionLink("Details", "Details", item )%> |
<%= Html.ActionLink("Delete", "Delete", new { id = item.UserName })%>
</td>
<td>
<%= Html.Encode(item.UserName) %>
</td>
<td>
<%= Html.Encode(item.CustomerID) %>
</td>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
Users/Details.aspx
<fieldset>
<legend>Fields</legend>
<div class="display-label">UserName</div>
<div class="display-field"><%= Html.Encode(Model.UserName) %></div>
<div class="display-label">CustomerID</div>
<div class="display-field"><%= Html.Encode(Model.CustomerID) %></div>
</fieldset>
<p>
<%= Html.ActionLink("Edit", "Edit", new { id=Model.UserName }) %> |
<%= Html.ActionLink("Back to List", "Index") %>
</p>
All the pages load just fine with no errors, but no data is shown. If I run the debugger the users list has 0 entries.
I am using SQL Server. My connection string is in my web.config in the typical fashion:
My database has user data in it already. It was generated with the default asp.net Web Site Administration Tool, which I am using for authentication. This works perfectly.
So what am I doing wrong? Any help is appreciated and if I need to give more info please let me know.
A: Your UserController (as explained in comment on OP) instantiates your list of users with no data.
If you want to seed data, consider changing the declaration as follows:
public class UsersController : Controller
{
// static List<Users> users = GetSeededData(); -
// don't store a list locally, it isn't necessary if you have a database
// consider holding the context instead perhaps?
protected MyContext context = new MyContext();
//
// GET: /Users/
public ActionResult Index()
{
return View(context.users.ToList());
}
//
// GET: /Users/Details/5
public ActionResult Details(int userId)
{
return View(context.Users.SingleOrDefault(x => x.UserId.Equals(userId));
}
}
A quick suggestion regarding your "persistance" (ignore this if you like, just a friendly tip)...
Consider introducting a persistance layer. That is, if you want to persist data, consider storing it in a database, xml file, etc. Take a look here. It's a great resource on MVC with lots of samples and tutorials, and half way down under the "Models" section it introduces you to the Entity Framework which can be used to store, retrieve, and update your data on a database quite nicely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't figure how to retrieve data of a particular row from a ListView I am developing an android application pertaining to sms. I have managed to display a listView of all the messages in my android emulator, but i can't figure out what code should i write in the onItemClickListener such that whenever i click any row of my listview i should get the data(here.. message body) associated with it in another screen. What ahould i do about this?
My code is given below:
public class mainmenu extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
setContentView(R.layout.main);
super.onStart();
{
final ListView list = (ListView) findViewById(R.id.list);
List<String> msgList = getSMS();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, msgList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// TODO Auto-generated method stub
}
});
}
}
public List<String> getSMS()
{
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null,null,null);
while (cur.moveToNext())
{
String address=cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
return sms;
}
}
Please give me the code that i should write in the OnItemClickListener as per the specifications i mentioned above. It's a bit urgent.
A: Just use the adapter there as such:
String itemAtClickedIntex = (String)adapter.getItem(position);
Hope this helps your urgent request :) please don't forget to accept as it encourages us to keep contributing.
Best
-serkan
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java EE: EJB Entity, Web Standalone Can you please tell me how is best to do?
How can I create a new instance of an entity on web application if I have only the interface..
I have :
*
*EJB(3.1) Project
*Web project
I have an EJB Project like:
User.java
@Entity
public class User {
//variables.. getters and setters...
}
UserManagerBean.java
@Stateful
public class UserManagerBean implements UserManager {
//getters and setters...
//.......
public void addUser(User user) {
//implemented here
}
//.......
}
UserManager.java
@Local
@Remote
public interface UserManager {
//methods here
}
In the web application(a standalone web application) I have this:
UserManager.java
public interface UserManager {
//methods here
}
User.java
public interface User {
//methods here
}
Now.. in a bean... I am trying to get from the remote context my beans and use them:
//ctx is created with the specific properties to access remote context..
InitialContext ctx = new InitialContext();
userManager = (UserManager)ctx.lookup("java:global/project/projectEJB/UserManagerBean");
User user = userManager.getUserById(1); //working
User new_user = (User)ctx.lookup("java:global/project/projectEJB/User"); //not working
//I know this is not supposed to work.. but how can I do this?
I know you can't get an instance of an entity because it's not an ejb...
Do I have to create a normal class of user having everying as on projectEJB? isn't there a better solution?
What other solutions are there? I searched for google and it seems like everybody knows how to do this.. only I don't...
Thank you in advance..
A: Entity beans are not supposed to be created directly in web layer — because for making them persistent them you need the EntityManager, which is not guaranteed to be thread safe (and that's important in a servlet context).
What you probably want to do is writing a DAO EJB with a method to create a new user, inject/look it up in the servlet, and call it. Google for "GenericDAO" pattern to start with.
A: To create the User object you just create a regular Java instance with the 'new' operator and then invoke your EJB call.
User myNewUser = new User();
userManager.addUser(myNewUser);
Both the client side (your web application) and the server side (EJB 3.1 project) must know how to serialize and deserialize the User object therefore each side must have access to the User class and the EJB interfaces.
In terms of packaging you could bundle the EJB interface and User entity class all into a single JAR that is used by both the client and server sides.
An alternative deployment would be to bundle the web app and EJB into a single application deployed inside the same JVM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redirect after FB App Request I found some sample code that does fb requests:
But my goal is to redirect after this jquery post? Im not familiar with jquery post....
This code just brings the dialogue box then closes. I want to refresh the page or redirect to another. I am sending the requests to fbrequests which executes some php code that stores request info to my db on my server. I tried putting the redirect there but it doesnt work.
Its
function sendRequest(to) {
FB.ui({method: 'apprequests',
message: 'data',
data: to,
title: 'Invite your Facebook friends.'},
function (response) {
if (response && response.request_ids) {
//since csv, we convert to string
var requestIds = "";
for(var i = 0; i < response.request_ids.length; i++){
requestIds = requestIds + response.request_ids[i] +",";
}
//modifications
//now requestIds is 123,124,125, so we need to remove the last comma after the last id
requestIds = requestIds.substring(0,requestIds.length-1);
jQuery(function(){
jQuery.post("fbrequests", { request_ids: requestIds } ); //jquery post to send csv list of ids to php processing file
// window.location.href='http://mysite.com/my-friends';
});
} else {
//Do something if they don't send it.
//alert("Didnt send it");
}
});
}
A: Remove the wrapping jQuery(function(){}); and just use:
jQuery.post("fbrequests", { request_ids: requestIds }, function(data) {
// handle the response "data", refresh or redirect here
});
Also use the below to join the request_ids instead of your code:
var requestIds = response.request_ids.join(',');
Taken from my tutorial: How To: Handle Application Requests Using The Facebook Graph API
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display a custom login control in Windows Phone with Mvvm light Ok, so what I am looking to do is to display some sort of login control (maybe a UserControl with a TextBox and PasswordBox) when the app is started.
In a non-mvvm situation, a way of doing this would be to use the PopUp primitive control, add the usercontrol as a child element and off you go.
In an MVVM situation, i'm a bit confused about how you would achieve a simmilar result.
I have looked into messaging with the DialogMessage and this is fine for displaying a typical MessageBox, but what about a custom usercontrol?
any help would be fantastic! I can't seem to find any demo code of this anywhere.
A: In a MVVM situation you can use a delegate to let your View open the dialog when the ViewModel requests it.
You define a delegate at the VM:
public Func<LoginResult> ShowLoginDialogDelegate;
In your View you define the function that will be called:
private LoginResult ShowLoginDialog()
{
LoginResult result;
// show a dialog and get the login data
return result;
}
Then you "connect" the delegate and method in the View:
_viewModel = new MyViewModel();
DataContext = _viewModel;
_viewModel.ShowLoginDialogDelegate += ShowLoginDialog;
And now you can use it in your ViewModel e.g. when a command is executed like that:
LoginResult result = ShowLoginDialogDelegate();
A: An easier answer is to control it's visibility through a View State which with a little manipulation can be made to work through databinding allowing the view model to display the "Logon Page" state when required.
I just recently wrote about this for the Silverlight/XNA series which you can view here.
It would be much simplier if the SL4 DataEventrigger was available but hay ho.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert a List into a comma-separated list, using the class's Id property as the value I have a List<User> collection, and I want to create a comma seperated string using the User.Id property, so:
"12321,432434,123432452,1324234"
I have done it using a loop, but was hoping someone could show me the linq way?
A: string.Join( ",", list.Select( item => item.ID ).ToArray() );
A: In .NET 4:
string joined = string.Join(",", list.Select(x => x.Id));
In .NET 3.5:
string joined = string.Join(",", list.Select(x => x.Id.ToString()).ToArray());
The difference is that .NET 4's overload list for string.Join is wider than the one in .NET 3.5, and the overload you really want is one of the "new" ones:
public static string Join<T>(string separator, IEnumerable<T> values)
You can still do it in .NET 2.0, just using a List<T>-specific method instead of LINQ (I'm assuming you can still use C# 3):
string joined = string.Join(",", list.ConvertAll(x => x.Id.ToString())
.ToArray());
A: use
string myResult = string.Join (",", (from l in myList select l.ID.ToString()).ToArray());
A: Given this list:
List<User> users = (GetUsers() ?? new List<User>())
.Where(u => u != null).ToList();
// no more nulls
.NET 3.5 - String.Join
Join(String, String())
Join(String, String(), Int32, Int32)
Example:
return string.Join(",", users.Select(u => u.Id.ToString()).ToArray());
.NET 4.0 - String.Join
Join(String, IEnumerable(Of String))
Join(Of T)(String, IEnumerable(Of T))
Join(String, Object()) // really? Just joining "stuff"?
Join(String, String())
Join(String, String(), Int32, Int32)
Example
return string.Join(",", users.Select(u => u.Id));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: Managed C++, Object reference not set to an instance of an object I've run into this problem before, but never in a situation like this. I'm completely confused. As the question states, I'm getting the runtime error "Object reference not set to an instance of an object." Using the debugger tools, I think I've pinpointed the problem to this line:
dataFileLocation = path;
The entire function is here:
void DATReader::SetPath(String^ path)
{
if(!File::Exists(path))
{
MessageBox::Show( "DATReader (missing dat file: \n"+path+"\n )", "Error", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
return;
}
dataFileLocation = path;
}
dataFileLocation is declared here, but nothing is assigned to it:
ref class DATReader
{
private:
System::String^ dataFileLocation;
// ...
}
Now I know the reason I'm getting the error is because dataFileLocation is assigned to nothing. But I'm having problems assigning it. When I add = 0; to it, it won't build because its a ref class. When I try to assigned it to = 0; in the constructor, it yells at me for trying to convert it from a System::String^ to an int. If I assign it to a = gcnew String(""); it builds, but throws the same runtime exception.
I don't get it, am I reading the debugger wrong, and this isn't the source of the problem at all? I've just started to use managed code recently, so I'm confused :\
A: You may want to check and make sure your DATReader object isn't null as well It may be throwing the exception at your DATReader.SetPath() call.
A: This is a nicety in C# that's missing in C++/CLI. C# generates code that ensures this can never be null. Easily seen in the debugger by setting a breakpoint on the method and inspecting "this". Here's an example program that reproduces the exception:
#include "stdafx.h"
using namespace System;
ref class Example {
String^ dataFileLocation;
public:
void SetPath(String^ path) {
dataFileLocation = path; // Set breakpoint here and inspect "this"
}
};
int main(array<System::String ^> ^args)
{
Example^ obj /* = gcnew Example */;
obj->SetPath("foo");
return 0;
}
Remove the /* */ comments to fix. Fix your code by looking at the call stack to find the method that forgot to instantiate the object.
A: Managed C++ uses nullptr for null references. So you can check:
if (path == nullptr) { ... }
or use:
if (!String::IsNullOrEmpty(path))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: array manipulation results can someone provide me more insight on why this code works the way it works
#include <stdio.h>
int main()
{
int a[5] = {1,2,3,4,5};
int i;
for(i=0;i<5;i++)
{
printf("%d,%d \n",i[a],i[a]++);
}
return 0;
}
The result is
2,1
3,2
4,3
5,4
6,5
Thanks
A: The behavior is undefined.
N1256 6.5p2:
Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an expression.
Furthermore, the prior value shall be read only to determine the
value to be stored.
The program both modifies i[a] (in i[a]++) and reads its value (in the next argument), and the result of reading the value is not used to determine the value to be stored.
This is not just a matter of the unspecified order of evaluation of function arguments; the fact that there's no sequence point between i[a]++ and i[a] (since that's not a comma operator) means that the behavior, not just the result, is undefined.
A: It works by undefined behaviour. The order of evaluation of function arguments is not defined. The comma is not a sequence point.
EDIT: ooops, I read to fast. There is only one write to the a[i] object, so the behaviour is not undefined, only the results.
A: "i[a]++" is a post increment, so it will return the value of i[a] and then increment i[a] right away.
In your case, the third parameter of printf gets evaluated before the second (the evaluation order of function parameters is unspecified as far as I know), and thus the second parameter returns the already incremented value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android Issue with 'createBitmap' and Sub-pixel Data I'm currently developing a small Android application to familiarize myself with the API. However, I have come across a problem regarding sub-pixel data while using createBitmap. I currently have these blocks of code. (NOTE: Image being read in is a 128x128 RGB565 jpeg):
public class MainMenu extends View {
private int vWidth; // Width of our view
private int vHeight; // Height of our view
private Bitmap imgButtons;
private Rect rect;
private MenuItem testButton;
private MenuItem testButton2;
public MainMenu(Context context) {
super(context);
// Get our view dimensions
vWidth = getWidth();
vHeight = getHeight();
// Load our menu buttons' image
BitmapFactory.Options imgOptions = new BitmapFactory.Options();
imgButtons = BitmapFactory.decodeResource(getResources(), R.drawable.mainmenubuttons, imgOptions);
rect = new Rect(100, 400, 228, 528);
// Create our menu buttons and load their specific images
testButton = new MenuItem(100, 50);
testButton2 = new MenuItem(100, 200);
testButton.LoadImage(imgButtons, 128, 64, 0, 0);
testButton2.LoadImage(imgButtons, 128, 64, 0, 64);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawBitmap(imgButtons, null, rect, null);
testButton.Draw(canvas);
testButton2.Draw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN)
super.onTouchEvent(event);
return true;
}
}
class MenuItem {
private int xPos; // Center x-coordinate
private int yPos; // Center y-coordinate
private int width; // Button width
private int height; // Button height
private Rect rect;
private Bitmap buttonImage;
public MenuItem(int withXPos, int withYPos) {
xPos = withXPos;
yPos = withYPos;
}
public void LoadImage(Bitmap image, int imageWidth, int imageHeight, int xOffset, int yOffset) {
width = imageWidth;
height = imageHeight;
buttonImage = Bitmap.createBitmap(image, xOffset, yOffset, width, height);
rect = new Rect(xPos - (width >> 1), yPos - (height >> 1),
xPos + (width >> 1), yPos + (height >> 1));
}
public void Draw(Canvas canvas) {
canvas.drawBitmap(buttonImage, null, rect, null);
}
}
Below is an image displaying the issue:
I lied. I'm not allowed to post images yet, so here is a link to the image:
createBitmap issues
So, why is that I can display the original image correctly, but cannot correctly display images created from its sub-pixel data? I have run the application using versions 2.1 through 3.0, and 3.0 has no issues displaying the image correctly. Is it just an issue with devices before version 3.0, or am I missing something? I found an article on stacked describing issues between solid images used(RBG565), and images that contain alpha(ARGB8888). Where, my method wouldn't work if the image was of type ARGB8888, and if so I needed to physically handle the pixel data and copy the sub-pixel data myself and create my own pixel buffer for storing that data. I tried this on a whim and it lead me down to the same issue. I just figured why not try it? I have also tried other variations of Bitmap.createBitmap to no avail. At this point I'm a little stumped and figured I'd ask the community.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenID Architecture for Java I'm trying to understand the concept and benefits of implementing OpenID in your project. And, since I'm a Java developer, I'm more or less equally interested in understanding its main Java implementation, openid4java.
My understanding is that OpenID is a standard for provisioning decentralized IDs in a uniform way. Now, if that is totally (or even slightly) incorrect, please correct me!
Assuming I'm still on track, I see that all sorts or organizations have been using OpenID, such as MySpace, who identifies each of their users with a URL matching http://www.myspace.com/username.
So how does OpenID work as a system? Does it just manifest itself as a network of "OpenID Servers" that, like DNS machines, coordinate and make sure all IDs in their system are unique and match a certain pattern? Or, is it just an algorithm to be used which, like GUID, produces globally-unique IDs for each client domain (such as MySpace).
I'm just not understanding how OpenID actually manifests itself, and how frameworks like openid4java ineract with that "manifestation". (What their uses are).
A: First, there are two sides of the OpenID communication - the provider and the consumer. The consumer is the application that tries to authenticate using OpenID, and the provider is the server to which the authentication request is sent.
Each provider has a so-called Endpoint - url that accepts authentication requests. You should know that URL in advance when supporting an OpenID provider. First you have to discover what is the endpoint for a given openId, and then exchange messages with that provider. This is all wrapped in openid4java ConsumerManager.
Then happens the authentication - you redirect the user to a provider url, where the user confirms he wants to login using his account (should be logged in), then the provider redirects back to you, and then you can get the requested information about the user (through another request)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Redis ignores maxmemory setting Redis has the following settings:
"config get maxmemory"
1) "maxmemory"
2) "2147483648"
(which is 2G)
But when I do "info"
used_memory:6264349904
used_memory_human:5.83G
used_memory_rss:6864515072
Clearly it ignores all the settings... Why?
P.S.
"config get maxmemory-policy" shows:
1) "maxmemory-policy"
2) "volatile-ttl"
and: "config get maxmemory-samples" shows:
1) "maxmemory-samples"
2) "3"
What means, they should expire keys with the nearest expiration date...
A: Do you have expiration settings on all your keys? volatile-ttl will only remove keys with an expiration set. This should be in your info output.
If you don't have expiration ttls set try allkeys-lru or allkeys-random for your policy.
A: According to http://redis.io/topics/faq
You can also use the "maxmemory" option in the config file to put a limit to the memory Redis can use. If this limit is reached Redis will start to reply with an error to write commands (but will continue to accept read-only commands).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: When to access the attribute (vs the property)? I gather from this post that almost always one wants to be accessing the DOM property, not the HTML attribute.
So what are the rare useful exceptions? In what situation is accessing the HTML attribute better than accessing the DOM property?
A: A rare exception is the case of attributes of a <form> element that could clash with elements in the form. For example, consider the following HTML:
<form id="theForm" method="post" action="save.php">
<input name="action" value="edit">
</form>
The problem is that any input within a form creates a property corresponding to the input's name in the form element, overriding any existing value for that property. So in this case, the action property of the form element is a reference to the <input> element with name action. If that input did not exist, the action property would instead refer to the action attribute and contain the string "save.php". Therefore for properties of form elements corresponding to attributes, such as action and method, it's safest to use getAttribute().
var form = document.getElementById("theForm");
// Alerts HTMLInputElement in most browsers
alert( form.action );
// Alerts "save.php"
alert( form.getAttribute("action") );
// Alerts "post" because no input with name "method" exists
alert( form.method );
This is unfortunate; it would have been better if this mapping did not exist, since the elements property of the form already contains all the form elements keyed by name. I think we have Netscape to thank for this one.
Live demo: http://jsfiddle.net/z6r2x/
Other occasions to use attributes:
*
*When accessing custom attributes, such as <div mymadeupattr="cheese"></div>
*When serializing the DOM and you want values from the original HTML for input attributes such as value and checked.
A: I can only come up with 2 more situations where accessing/setting attribute would have benefits
over property.
Style attribute:
In a case where you are not allowed to use any framework, you can use style attribute to set multiple styles at once like so:
elem.setAttribute( "style", "width:100px;height:100px;" );
instead of doing this:
elem.style.width = "100px";
elem.style.height = "100px";
or this:
var styles = {width: "100px", height: "100px"}, style;
for( style in styles ) {
elem.style[style] = styles[style];
}
Be aware that setting style attribute overwrites the previous one. And its probably better to write
a multiple style setter function anyway.
Href attribute:
A href attribute will usually contain a value like "/products", however the property will contain the resolved url, as in:
"http://www.domain.com/products" instead of what you really want: "/products". So if you wanna do something dynamically with
links, then reading the href attribute instead of property is better because it has the value you intended it to be.
Update
I suddenly found 2 more uses and I am sure there are more like this.
If you want to see if an element has custom tab index set, the easy way is to see if the element has the attribute. Since the default
value for .tabIndex-property depends on element and cannot be easily used to see if the element has custom tabIndex.
Seeing if element has a custom .maxLength property. This cannot be seen from property either:
document.createElement("input").maxLength
//524288
It is impossible to tell if the value 524288 was there intentionally without dealing with the attribute.
A: Sometimes the attribute doesn't map to changes in the property.
One example is the checked attribute/property of a checkbox.
DEMO: http://jsfiddle.net/mxzL2/
<input type="checkbox" checked="checked"> change me
document.getElementsByTagName('input')[0].onchange = function() {
alert('attribute: ' + this.getAttribute('checked') + '\n' +
'property: ' + this.checked);
};
...whereas an ID attribute/property will stay in sync:
DEMO: http://jsfiddle.net/mxzL2/1/
<input type="checkbox" checked="checked" id="the_checkbox"> change me
var i = 0;
document.getElementsByTagName('input')[0].onchange = function() {
this.id += ++i;
alert('attribute: ' + this.getAttribute('id') + '\n' +
'property: ' + this.id);
};
And custom properties generally don't map at all. In those cases, you'll need to get the attribute.
Perhaps a potentially more useful case would be a text input.
<input type="text" value="original">
...where the attribute doesn't change with changes from the DOM or the user.
As noted by @Matt McDonald, there are DOM properties that will give you the initial value that would reflect the original attribute value.
HTMLInputElement.defaultChecked
HTMLInputElement.defaultValue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: how to persist grid-view row backcolor in EDIT MODE how to persist grid-view row in EDIT MODE backcolor when hover over the other rows
if the ROW is in EDIT MODE it highlighted with yellow backcolor
the problem is when you try to hover over the other rows then it loses the backcolor,
so my question is :
how can i keep that backcolor even if its hover outisde the edit mode?
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit))
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.BackColor = System.Drawing.Color.Yellow;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you set a session variable in JavaScript? Can this be done with a PageMethods call? I need to save some variables in a control so that they can be used by a control on another page at a later time. Is there a way to do this via JavaScript?
A: Sounds like you need cookies, localStorage, or sessionStorage.
A: You can use JS to change the values in a hidden field, and capture them on the postback, which personally I think preferable to cookie usage if the value is only needed for the life of the current session.
A: It's a very bad idea to do this with PageMethods.
You can add a generic handler (*.ashx) and then do a XMLhttpRequest to this URL, passing it parameters.
Note that the ashx handler needs to inherit from IRequiresSessionState, in order to access a session.
You can also get a session value that way.
Like this:
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler , IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string item = context.Request.QueryString["item"] ?? "";
string update = context.Request.QueryString["update"] ?? "";
switch (item)
{
case "A":
if (!string.IsNullOrEmpty(update))
context.Session["A"] = update
object a = context.Session["A"];
context.Response.Write(a != null ? (string) a : "none");
break;
case "B":
if (!string.IsNullOrEmpty(update))
context.Session["B"] = update
object b = context.Session["B"];
context.Response.Write(b != null ? (string) b : "none");
break;
}
}
public bool IsReusable
{
get { return false; }
}
}
See my post here for XMLhttpRequest:
Why does this JavaScript code ignore the timeout?
You might want to add a parameter no_cache=TIME_IN_MILLISECONDS, in order to beat browser caching.
A: I like to do it the following way:
javascript:
function SendData(data) {
var postbackarg = "@@@@@" + data;
__doPostBack("txtTest", postbackarg);
}
VB In Page_Load event:
If Me.IsPostBack Then
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim args As String = Request.Params.Get("__EVENTARGUMENT")
ProcessUserInterfaceData(controlName, args)
If (controlName = "txtTest" AndAlso args.IndexOf("@@@@@") = 0) Then
args = args.Substring(5, args.Length - 5)
'args now = data from the UI
End If
End If
This started from an example I found somewhere else. I cannot find it.. The only purpose for the 5 '@' is to identify the postback as coming from SendData.
A: Session variables cannot be set using Javascript directly
But you can use the following code to set session variables in aspx page
<%Session["SESSION VARIABLE NAME"] ="SOME STRING"; %>
You can check the same variable using an alert in javascript
alert('<%=Session["SESSION VARIABLE NAME"] %>');
Yes session variable can be set using Pagemethods using the below way
declare the below code in aspx.cs page
[WebMethod]
public static void functionname(string st)
{
Home h = new Home();
System.Web.HttpContext.Current.Session["SessionUserName"] = st;
h.strUserName = (string)System.Web.HttpContext.Current.Session["SessionUserName"];
}
and call the function using pagemethod in aspx
PageMethods.functionname("HELLO");
this will set the session variable to HELLO
You can also make an ajax call to the webmethod if you dont want to use pagemethods.function!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using time in a bash script: how to get the "normal" output? If I use time in the shell, I get an output like
$ time sleep 1
real 0m1.003s
user 0m0.000s
sys 0m0.000s
However, if I use the same command in a bash script, the output is this
0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 2176maxresident)k
0inputs+0outputs (0major+179minor)pagefaults 0swaps
I already found this post, but what I want is to use time in a script, while still getting the same output as if I was using it in a shell.
A: 0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 2176maxresident)k
0inputs+0outputs (0major+179minor)pagefaults 0swaps
...is the default output produced by the GNU version of the external time command.
real 0m1.003s
user 0m0.000s
sys 0m0.000s
...is the default output produced by the bash builtin time. This builtin version of time is a bash extension: a POSIX-compliant shell is not required to provide a builtin version of time.
However, POSIX does specify an external time utility, which can take -p option to produce yet another output format:
real 1.01
user 0.00
sys 0.00
...and the bash builtin also accepts the -p option to produce the same output format.
The bash builtin should work perfectly well in a shell script provided the script is actually being run by bash:
$ cat time.sh
#!/bin/bash
time sleep 1
$ ./time.sh
real 0m1.001s
user 0m0.000s
sys 0m0.000s
$
So it seems that your script is invoking the external utility rather than the bash builtin.
The most likely cause of this is that:
*
*your script says #!/bin/sh rather than #!/bin/bash; and
*the /bin/sh on your machine is not actually bash, but a more lightweight POSIX-compliant shell without the bash extensions (as found on some Linux distributions these days).
The solution is to ensure that the script specifically invokes bash by using #!/bin/bash if it relies on bash extensions.
A: Did you try the -p flag?
$ echo "time -p sleep 1" > x1
$ bash x1
real 1.01
user 0.00
sys 0.00
A: The difference is that output is not going to terminal when piped.
The terminal codes necessary to do the nice layout do not work on a filestream.
What did you want to achieve? If you intend to have the 'screenshot' have a look at script
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need a consistent TimePicker gizmo for mobile web site We have a mobile web site that requires users to enter a specific time value--basically in hh:mm form. We're having a great deal of difficulty with the consistency of displaying and entering time from various browsers.
In looking for existing examples, we keep encountering various sites that allow 'ball park' values for minutes--so for them, a dropdown with 15 minute (for example) increments is fine--but a dropdown with 60 values is ridiculous on any platform, mobile especially.
The HTML5 < input type="time" /> isn't getting us there. A standard text input isn't either, as it tends to cue the device to show the alpha keyboard, which doesn't have numbers on it. The HTML5 type="number" almost works, but for some Android browsers, which don't have the colon (:) on the numeric keyboard.
I'm well aware that we're in the land of chaos with mobile browsers, but does anyone have a good idea of what might function well for both Android and iPhone?
Note: I've tried googling, and checked out various jQuery plugins, and none provide a good user experience for mobile--and many are poor even for the desktop. Ideas?
A: I don't particularly like their approach, but I believe the Any+Time date/time picker would work reasonably well on a mobile device - it can be positioned statically and the aspect ratio and button sizes look Right.
That said, testing it on my iPhone shows that a few kinks need to be ironed out. Notably, after tapping a button in the picker widget, the "hidden" input field the picker populates is focused and the view moves around and the onscreen keyboard pops up.
A: I hate answering my own questions here, but it looks like Mobiscroll comes closest to solving the problem for our users. We also looked at the jQM-DateBox but felt that our users would not be comfortable with the hour value changing automatically when you roll forward past 59, or backward past 0.
In addition to this, we did evaluate using a jQuery Mobile select list on a standard dropdownlist, but it felt wrong as we used it, as it essentially pops a div on the page, and scrolling through that moves the entire page quite a bit. I think that one would be great for a few items, but not applicable to our user base.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: A developer tool for designing an SQLite database for Android I'm fairly new to Android, I'm trying to create a rather complex app (something more advanced than notepad or task reminder), with some serious underlying data model. I'm using Eclipse with the Android SDK plugin, everything is working well. But what should I use for database design?
I've gone through some sample apps that create databases programmatically, but those only contained a single table with a few columns. What I want to create is a database with multiple tables, private key/foreign key constraints, enumerations and all that jazz. If I had to do this manually, I'd probably go grey by the time I'm finished. I've designed quite a few databases in my time, be it in MS Visual Studio, MS SQL Server Management Studio, Oracle DB Designer and similar tools.
I realize that SQLite doesn't have some fancy shmancy DB server where I could run SQL scripts and it would create the database and keep it alive. I know it's all part of the application and the app itself must create and maintain its database.
Is there any visual DB design tool, which I could maybe integrate into Eclipse (not necessary) and which would, I don't know, generate the database creation code, so that the database would be usable in my application?
Thanks in advance.
PS: I'm aware of the limitations of the Android devices. The app will have a complex data structure, but it's not intended to hold that much data. The purpose of the exercise is to test what can be done with the platform and improve my skills by attempting to create something meaningful.
A: I use the SQLite editor from Nivacat (Navicat SQLite) for developing my android data bases on Mac OS X (also available for Windows and Linux).
A: SQLite addon for Firefox is quite nice.
A: If you're on Mac OSX I would recommend Base.
A: I've been using SQLite Database Browser for the past month, I've found it to be a really nice tool. You should try it out:
http://sqlitebrowser.org
A: SQLiteSpy, it is a bit better than SQLite Database Browser, also free.
http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: has_many :through in fixtures in rails 3.1 I want to set up some has_many, :through objects using fixtures for testing in rails 3.1.
If you look at the documentation on the association as an example, I want to know how to assign assemblies to parts. The only way I've found to do it is to explicitly create the manifest object in it's own file, but if I'm happy with the defaults on that model and all I want to specify are the part/assembly id's then is there a way to do it directly?
http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many
I want something like:
my_assembly:
parts: my_first_part, my_second_part
This works if you do HABTM, but not when you have the explicit join model.
A: Assuming you want or have to stick with fixtures, then if you switch from an HABTM to a has_many :through relationship, then you can no longer use the short inline lists. You must create a separate fixture file for the :through model.
A: Never, ever, use Rails fixtures for anything.
I'll repeat: Never, ever, use Rails fixtures for anything.
They are dangerous, cumbersome and make your tests leak state. They are unsuitable for writing proper tests. At best, you get tests that look as if they are properly written, but have hidden dependencies. The Rails team got this feature 100% wrong, and I wish they'd remove it from Rails so people wouldn't be tempted to use it.
Instead, install factory_girl_rails and use factories to create your testing records on demand:
Factory :assembly, :parts => [Factory(:part, :name => 'first'), Factory(:part, :name => 'second')]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Engine routes in Application Controller I have a before_filter hook in my main app's application controller that does something like: (It doesn't just put a link in the flash, there is a message, but it isn't relevant to the question, it just accesses the route in the method)
class ApplicationController < ActionController::Base
before_filter :set_link
def set_link
flash[:notice] = items_path
end
end
This works fine for the app, however when I go into the controllers for an engine I made I get the exception
No route matches {:controller=>"items", :action=>"index"}
I understand that when in the engine, the routes helpers are for the engine unless prefixed with main_app
So changing the method in the application controller to
def set_link
flash[:notice] = main_app.items_path
end
Gets rid of the exception but I really don't want to have to do that. Is there another solution to getting the engine to recognize the main_app routes?
EDIT:
This also happens if the application layout calls path helpers. So if the engine is designed to integrated into the main_app's layout then this issue will crop there up too.
A: I figured out how to do this. The problems lies within the isolated namespace. In order to integrate the engine with the app and share the same layout (which may have path helpers from the main app) I did this:
Firstly I removed config/routes.rb from the engine
Then I removed the isolate_namespace from the engine class
module MyEngine
class Engine < Rails::Engine
- isolate_namespace MyEngine
end
end
end
I added a file that was loaded in the engine:
module ActionDispatch::Routing
class Mapper
def mount_my_engine_at(mount_location)
scope mount_location do
#Declare all your routes here
end
end
end
end
Finally, in the main app's config/routes.rb instead of 'mount'ing the engine, you can call your method
mount_my_engine_at "mount_location"
This will basically 'mount' your engine as part of the main app instead of being isolated from it. It is similar to how Devise does it too.
A: You can keep the isolate_namespace.
In your engine routes.rb
MyEngine::Engine.routes.draw do
...
root to: "something#index"
end
Rails.application.routes.draw do
get "something", to: "my_engine/something#index"
end
And then in the main app routes.rb
Rails.application.routes.draw do
mount MyEngine::Engine => "/anything_you_want"
root to: "main#index"
end
This way you can choose what routes you want to expose (and which you do not)
A: Mountable engines are designed to work like this, that is isolate the main app routes and the engine routes.
If you want the two sets of routes to be merged, you can use a non-isolated engine. The first step is removing the isolated_namespace method call in your engine definition:
module MyEngine
class Engine < Rails::Engine
isolate_namespace MyEngine # remove this line
end
end
The second step is to convert your routes in my_engine/config/routes.rb, you should go from this:
MyEngine::Engine.routes.draw do
# stuff that routes things
end
to this:
Rails.application.routes.draw do
# stuff that routes things
end
and remove the mount method call in your application's routes:
App::Application.routes.draw do
mount MyEngine::Engine => "/engine" # remove this line
end
The main advantages of doing it this way would be:
*
*No need to monkey-patch rails. I know devise does this, but this could be a leftover from the days when engines didn't exist in rails.
*No need to mount the engine in the application routes. On the other hand, this could backfire if you'd like to control more precisely the insertion point as all you engine routes would be called after (or before, I don't have the answer to this question) your main routes.
If you're looking for documentation on engines, the rails docs for the Engine class are a pretty good starting point. I'd strongly recommend that you read them (in case you haven't yet) if you're interested in the subject.
A: You can keep the isolate_namespace, as strongly recommended by Rails Engine guide, and do this:
# inside your main_app's config/routes.rb
Rails.application.routes.draw do
root to: 'home#index'
mount MyEngine::Engine, at: "/"
end
# inside your engine's controller
module MyEngine
class SomeController << ::ApplicationController
# include main_app's route helpers
helper Rails.application.routes.url_helpers
end
end
And inside your gem, make sure all the url helpers are prefixed with the correct routing proxy method (e.g. my_engine.pages_path).
Your main_app's layout and engine's controller will route and link to those url helpers correctly to the main app. You don't have to add "main_app" prefix anywhere to the main app. The only downside is you're mounting your engine's routes at main_app's root path, which could collide with any routes by the same name. This is expected anyway if you were to do non-isolate_namespace.
A: The easiest way is to draw the routes in both the main app, and the engine, so that they are accessible to both:
[MyEngine::Engine, App::Application].each do |app|
app.routes.draw do
# Declare all your routes here
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Where to put model “utility” functions in Ruby on Rails, if it is also required in a rake task? This is a 2nd part to the following question:
Where to put model "utility" functions in Ruby on Rails
Problem is, I need access to these utility functions from a rake task as well. Using the accepted technique in in the other thread, I get an "undefined method" error when accessing my model from a rake task.
What is the best way to fix this?
Thanks
A: You probably need to define your rake task as dependent on the Rails environment:
task :my_task => :environment do
# Will load Rails stack before executing this block
MyModel.foo
end
The default behavior is to load almost nothing, so you won't have access to your models unless you ask for it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does this enumerate this way? For the following function
KEYS = {}
def get(kind):
"returns a new key of a particular kind"
global KEYS
try:
return KEYS[kind].pop(0)
except (KeyError, IndexError):
handmade_key = Key.from_path(kind, 1)
start, end = allocate_ids(handmade_key, 3)
id_range = range(start, end+1)
KEYS[kind] = [Key.from_path(kind, id) for id in id_range]
for key in KEYS[kind]:
print "within get() -> %s:%s"%(key, key.id())
return get(kind)
I have written the following unit test
def testget2000(self):
s = set()
for i in range(0, 7):
key = keyfactory.get("Model1")
print "from get() -> %s:%s"%(key, key.id())
s.add(key)
self.assertEqual(len(s), 7)
self.assertEqual(len([k.id for k in s]), 2000)
And get the following error
FAIL: testget2000 (keyfactory_test.ModelTest)
Traceback (most recent call last):
File "/home/vertegal/work/ei-sc/appengine/keyfactory_test.py",
line 36, in testget2000
self.assertEqual(len(s), 7)
AssertionError: AssertionError: 5 != 7
-------------------- >> begin captured stdout <<
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAgw:2
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAww:3
within get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAQw:1
within get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAgw:2
within get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAww:3
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAQw:1
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAgw:2
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYAww:3
within get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYBAw:4
within get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYBQw:5
within get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYBgw:6
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYBAw:4
from get() -> agpkZXZ-cXVpenJ5cgwLEgZNb2RlbDEYBQw:5
I really don't understand why it is that "from" is being printed before "within" the first time. Also, why is it that it allocates the same first few ids twice? Am I creating some weird closure? Is KEYS a different object in the exception handler than outside it? I am lost.
A: So it looks like when your captured output begins, the datastore is empty but KEYS[kind] has two values already populated. The datastore isn't allocating the same IDs twice, you just have leftover IDs that have never been allocated. Either track down what else is writing to KEYS, or just wipe it out at the beginning of your test.
Also, you seem to be passing the actual model class around for kind. Key.from_path expects a string, e.g. 'Model1' instead of Model1.
A: As Drew suggests, you might add
global KEYS
KEYS = {}
to the top of your test (or better, to a setUp method), but the root of your problem is in the design: Functions that use use lazily initialized, mutable global state are difficult to test. Making a KeyFactory class, with KEYS as an instance variable, might serve you better.
What is it that you're trying to achieve by doing this?
A: It looks like something is calling get(kind) before your unit test starts capturing, or KEYS is being filled somehow before things start.
Maybe just add a raise Exception or otherwise print the traceback in get(kind) and make sure the first time it runs is from within your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CakePHP Count syntax I am writing an app in CakePHP and need to get a count of posts for an image. its a one (image) to many (comments) link.
I have tried the following but it doesnt work as it cant find the table? I know I have managed to do this with just SQL queries in previous applications.
This is the code
$data = $this->Image->find('all', array(
'fields' => array('COUNT(Comment.comment_id) AS total', 'Image.*'),
'group' => array('Image.logo_id')
));
basically I want to output the image details and then a comment count which is associated to the image.
Hope someone can help.
Thanks.
A: counterCache seems to be the answer, thanks guys!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: bzr merge - reviewing another branches commit notes ('merge tips') before committing I have a developer who has made some changes, and has asked that I merge them in. In order to be safe, I haven't merged/committed his work outright, but instead made a copy of his branch so that I can do a 'bzr log --forward -n 0 -v | less' to see his commit notes, and to understand the files which were modified/added.
Since he has made several changes, I don't want to merge them all in one shot. Instead, I'd like to commit his changes to my branch one at a time after reviewing them.
Problem is, I don't see any revision IDs for each of the "merge tips" for his changes.
If for example, he's committed changes at r250, 251, 252, and I merge all these changes in to the working tree, how can commit his r250? Do I have to merge his changes in one at a time? or is there a way of doing this via the "merge tips"?
I'm not sure how useful merge tips are, if they only show you comments, and don't provide an ability to merge each tip in individually.
Of course I may be missing something which is common knowledge; if so, please enlighten me.
Thanks very much in advance.
A: Instead of working against merge, work with it. Merge is designed to pull multiple changes at once like this, while still maintaining the separate underlying commits. Check out his branch, and review each one of his commits, one at a time. Once you are satisfied with them all, merge the whole set in one go.
A: I'd merge someone else's changes into my working folder, then
bzr qlog
and see what each change was, then from
bzr qcommit
you can revert the files you don't want to include... and commit the rest.
I'm fairly new to bazaar though. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: NHibernate,Entity Model or LightSpeed which is preferable? Can any one tell which is best suited for performance oriented applications?
A: All of the above. Or none of the above. No way to tell without measuring performance and seeing which one does or does not work for you.
A: I would agree with the existing answers here: Understand what performance really means to your application before going off half-cocked on something (most of us have been there). If you're looking for something super-performant but that still has some "ORMish" behavior and takes some monkey coding out of the ADO.Net equation, take a look at the various .Net MicroOrms out there such as:
*
*Dapper (with extensions)
*Service Stack's ORM Lite
*Insight.Database
*Massive
There are several others out there, some of which are referenced from the dapper site.
If you really are stuck with those three choices, it definitely does depend on a lot of factors and how much time you spend tuning. That being said, I've used all three quite a bit, especially NHib 2-3 and EF 4-6. I think if you are doing just quick-and-dirty coding without spending a lot of time on optimizing, LightSpeed is a really good choice and I've personally found it to outperform the other two very handily when it comes to most basic CRUD operations and LINQ queries.
The big downside of LightSpeed is that you have to inherit from their base classes. This is somewhat mitigated by partial class support and you can also insert your own base classes in between, and there's also no true "CodeFirst" support, although you can handcode the classes and skip the designer if you like. They all work well if tuned properly. Just pick the right tool for the job.
Whichever you chose, use your SQL Profiler / Mini Profiler / NHProf / EFProf etc...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery validation: allowing form submission in spite of errors I am running into issues with the jquery form validation plugin. It is allowing the form to be submitted in IE, also, it is allowing form submission in Firefox if two previously invalid required fields are fixed (even if there are other invalid fields).
http://superuntitled.com/dev/index.html
The js is the most basic use of validate()
$("#emailform").validate();
The class names are correctly set (required, email).
Are there any none gotchas or bugs for this script?
I am using jQuery 1.6.2 and the jQuery Validation Plugin 1.8.1
A: You may be triggering JavaScript exceptions, which are causing your script to terminate. Once that happens, the default form is submitted, as that would be the normal HTML action without the JS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c++ Gregoraian and Julian calendar inheritance I have this dilemma where i need to choose between differant types of inheritance for the Gregorian and Julian calanders. I want to have one class named Date as a base class.
My question is as follows: Should I have a class for the Gregorian that inherits from the date class and Julian that does the same? Or should only the Gregorian class inherit from the Date and Julian inherit from the Gregorian, or vice versa? Or should I have a class beneath the Date that inherits from Date and have the Gregorian and Julian inherit from that class?
Date Date Date Date
Gregorian Julian Gregorian Julian New class
Julian Gregorian Gregorian Julian
I would personally choose the first alternative where the both inherit from Date, is this a good choice. Can i get som opinions about this?
A: I don't know the inner details of the calendar systems, but I'm sure it is hard not to underestimate their subtle complexities. That alone would make me absolutely not want to mix the implementation in a class hierarchy.
I'd go with
*
*separate classes (types)
*optional non-implicit conversions
*shared utilities from a policy/strategy class to avoid unwanted code duplication
PS. In the classical 'Liskov' sense, you could have an abstract base class Date that just 'names' concepts common to all (most?) calendar systems. However, I'm really doubting what the added value would be. I could see it lead to a lot of confusion (it invites code to mix subtypes of Date in any or all code and all code using your datetime classes must be prepared to handle the whole gamut always).
By the way, have a look at Noda Time and Joda Time. These well-respected libraries are generally thought to be especially well-designed.
A: Gregorian and Julian calendars are two types of calendar. It would be better for them to inherit from a common base class than inherit from each other.
An example can be found in Joda time, which has Gregorian and Julian chronologies as different subclases from a common base chronology.
A counter-example can be found in the standard Java library, in which the Gregorian and Julian calendars are supported by the same class.
A: A Calendar is not a Date so there is no need for either to inherit from Date.
At most, a Calendar should operate on Dates. Or perhaps a Date could convert itself from one kind to another.
What exactly are you trying to do and why isn't it already done in a 3rd party library already?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom UITableView Dynamic Cell Height I have search and searched through endless blogs and articles on how to determine a dynamic height for a custom UITableViewCell and its detailed text. I have really had a hard time finding any good documentation on this.
What I need to do is have the cell grow according to the the text inside but never go below a height of 70.
I have tried several of the answers for this type of question here on StackOverflow but none of them worked. My whole app is just about finished but I really need to get this accomplished before I release and its troublesome.
Here is what I am trying but I just get a slop of cells overlapping each other. From what I read I need to find the frame if the custom cell or textview in the cell as well but I am not sure how to do that or mix them all together to return one height.
Any Help would be greatly appreciated Thank you!
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath
*) indexPath
{
CGSize aSize;
aSize = [[(Tweet*)[tweets objectAtIndex:indexPath.row]tweet] sizeWithFont:[UIFont
systemFontOfSize:14]
constrainedToSize:CGSizeMake(300.0, 1000.0)
lineBreakMode:UILineBreakModeTailTruncation];
return aSize.height;
}
A: Hey there so you are going to need to store the list of strings in an NSArray and then you are going to need to calculate the height of the nsstring using sizeWithFont:constrainedToSize: the documentation is found here http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html
so your tableView method should look something like
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:"Helvetica" size:9] forKey: NSFontAttributeName];
CGSize cell_size = [string boundingRectWithSize:CGSizeMake(300,999)
options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
attributes:stringAttributes context:nil].size;
if (cell_size.height > 70)
{
return cell_size.height;
}
else
{
return 70;
}
}
EDIT : THIS has been updated for iOS 7
A: I had a similar issue a while back and this helped me tremendously.
#define PADDING 10.0f
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [self.items objectAtIndex:indexPath.row];
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];
return textSize.height + PADDING * 3;
}
A: I just wrote about this problem and how I finally decided to solve it. You can read about it here: Dynamic UITableView Cell Height Based on Contents
Basically, I created a UITableView subclass that automates the handling and calculation of dynamic cell height for both default and custom cells. It is not a silver bullet and probably needs to be extended and tweaked, but I have used it as is in several apps with good result.
You can grab the code here: https://github.com/danielsaidi/AutoSizeTableView
Hope it helps!
(...and if it didn't, I'd love to hear why not)
A: I tried many solutions, but the one that worked was this, suggested by a friend:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int height = [StringUtils findHeightForText:yourLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:17.0f]];
height += [StringUtils findHeightForText:yourOtherLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:14.0f]];
return height + CELL_SIZE_WITHOUT_LABELS; //important to know the size of your custom cell without the height of the variable labels
}
The StringUtils.h class:
#import <Foundation/Foundation.h>
@interface StringUtils : NSObject
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font;
@end
StringUtils.m class:
#import "StringUtils.h"
@implementation StringUtils
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGFloat result = font.pointSize+4;
if (text) {
CGSize size;
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
result = MAX(size.height, result); //At least one row
}
return result;
}
@end
It worked perfectly for me. I had a Custom Cell with 3 images with fixed sizes, 2 labels with fixed sizes and 2 variable labels. Worked like a charm. Hope it works for you too.
Best regards, Alexandre.
A: iOS 7
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
NSString *text = @"Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello HelloHello HelloHello HelloHello HelloHello HelloHello Hello";
CGRect rect = [text boundingRectWithSize:CGSizeMake(280.0f, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{
NSFontAttributeName: [UIFont fontWithName:@"Hellvetica" size:14.0f]
} context:nil];
return CGSizeMake(320.0f, ceil(rect.size.height) + 10.0f);
}
A: Use UITableViewDelegate method:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// here you need to get height of your textlabel in your custom cell.
MyCustomCell *myCell = (MyCustomCell *)[tableView cellForRowAtIndexPath:indexPath];
return myCell.myTextLabel.frame.size.height + 20;
}
Something like this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: ASP.net MVC - Should I use AutoMapper from ViewModel to Entity Framework entities? I am currently using AutoMapper to map my Entity Framework entities to my View Model:
public class ProductsController : Controller
{
private IProductRepository productRepository;
public ProductsController(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public ActionResult Details(int id)
{
var product = productRepository.GetProduct(id);
if( product == null )
return View("NotFound");
ProductDetailsViewModel model = Mapper.Map<Product, ProductDetailsViewModel>(product);
return View(model);
}
}
This works well. The question I have is when I need to go from my View Model to my entity in order to update the database. Should I be using AutoMapper for this? Is this a bad/dangerous practice?
It seems like AutoMapper is good for flattening a complex type to a simple (flat) type, but so far I'm struggling trying to go from a flat/simple to a more complex type like my entity with the various navigation properties.
If it is a bad idea to use AutoMapper to do this, then what would my code look like for a Create action?
public ActionResult Create(CreateProductViewModel model)
{
if( ModelState.IsValid )
{
// what do i do here to create my Product entity?
}
}
What about an Edit action?
public ActionResult Edit(int id, EditProductViewModel model)
{
Product product = productRepository.GetProduct(id);
// how do i convert my view model to my entity at this point???
}
A: I'm a of the mindset that updating your entities is a pretty big deal and that no automated tool should ever be used. Set the properties manually.
Yes its a very tiny amount of more code but automapper or running updatemodel on database entities can sometimes have unintended consequences. Better to make sure your writes are done correctly.
A: You could also try configuring AutoMapper to only map Scalar properties (instead of having to .Ignore() every single property you don't want it to (including inherited properties like .EntityKey and .EntityState).
AutoMapper.Mapper.CreateMap<EntityType, EntityType>()
.ForAllMembers(o => {
o.Condition(ctx =>
{
var members = ctx.Parent.SourceType.GetMember(ctx.MemberName); // get the MemberInfo that we are mapping
if (!members.Any())
return false;
return members.First().GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false).Any(); // determine if the Member has the EdmScalar attribute set
});
});
Some more info at http://www.prosoftnearshore.com/blog/post/2012/03/14/Using-AutoMapper-to-update-Entity-Framework-properties.aspx
A: Essentially automapping is bad, I wrote a blog post on this http://blog.gavryli.uk/2015/12/02/why-automapping-is-bad-for-you/
A: I use AutoMapper with a specialized mapping class that understands how to make a complex model from a simple one. AutoMapper is used to handle the one-to-one mapping and the custom logic in the class for doing the more complex things (like relationships, etc.). All of the AutoMapper configuration is done in the static constructor for the mapping class, which also validates the mapping configuration so that errors fail early.
public class ModelMapper
{
static ModelMapper()
{
Mapper.CreateMap<FooView,Foo>()
.ForMember( f => f.Bars, opt => opt.Ignore() );
Mapper.AssertConfigurationIsValid();
}
public Foo CreateFromModel( FooView model, IEnumerable<Bar> bars )
{
var foo = Mapper.Map<FooView,Foo>();
foreach (var barId in model.BarIds)
{
foo.Bars.Add( bars.Single( b => b.Id == barId ) );
}
return foo;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: How can I use the selected rows in GridView as a source for a GridView in another page? I am writing a web site in Visual Studio, something like an on-line library. I have a GridView on the first page that presents all of the books available from the data source and some other properties also contained in the data source. The GridView contains check boxes and the user can choose which books he wants to order by checking a box. My question is how can I use the data in the selected rows, the list of books with their properties and show that list on another page, so that the user is able to know which items he has selected?
I tried with a for loop on the FirstPage:
protected void Page_Load(object sender, EventArgs e)
{
List<int> ids = new List<int>();
if (!IsPostBack)
{
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int bookID = (int)GridView1.DataKeys[i][0];
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");
if (cb.Checked)
{
ids.Add(bookID);
}
}
Session["Ids"] = ids;
Response.Redirect("SecondPage.aspx");
}
}
and on the SecondPage:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtBooks = new DataTable("Books");
dtBooks.Columns.Add(new DataColumn("ID", typeof(int)));
if (!IsPostBack)
{
var list = (List<int>)Session["Ids"];
foreach (int id in list)
{
if (Request.QueryString["bookID" + id] != null)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = Request.QueryString["bookID" + id];
dtBooks.Rows.Add(row);
}
}
GridView1.DataSource = dtBooks;
GridView1.DataBind();
}
else
{
}
}
but I get no GridView table on the second page. I would be very grateful if anyone notices my mistake and points it out. Hope you can help me.
A: This is a common issue when setting session variables before a redirect. I think you can work around it by using the overloaded Response.Redirect method:
Response.Redirect("...", false); // false = don't stop execution
See here for more details:
Session variables lost after Response.Redirect
Another option is to store the IDs in a hidden field, and access them with Page.PreviousPage, like this:
HiddenField hidden = (HiddenField)Page.PreviousPage.FindControl("MyHiddenField");
string values = hidden.Value;
Lastly, depending on what the page is doing, you might want to use Server.Transfer here. There are drawbacks to this approach, but there are situations where it's applicable.
A: In your second page, you are checking for a query string variable before adding a row to dtBooks:
if (Request.QueryString["bookID" + id] != null)
However, you are not passing any query strings when you redirect:
Response.Redirect("SecondPage.aspx");
At a guess, I would think that you originally tried using the query string to pass the IDs, before changing to the session and you haven't updated all of your code.
I am somewhat concerned about your first page code, though. You do realize that you will redirect to the second page whenever a post back occurs? That means that no matter what buttons / controls you have on the first page, if they post back for any reason, you will redirect to the second page.
EDIT AFTER COMMENTS
If you aren't using the query string, then don't use the query string:
foreach (int id in list)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = id;
dtBooks.Rows.Add(row);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java cache mechanism I need to use cache solution in my project.
I've used jcs and looks pretty good, but I read that its library is based on jdk1.3 spec.
Ehcache looks another good choice too.
Which library should I use, apache jcs, ehcache or other?
A: I've used EhCache successfully in the past. Very easy to configure and use, provide good performance and easy ways to monitor the content of your cache.
Without telling us more about what exactly you want to cache, it's difficult to give more details.
You could also consider using some O/RM solution (Hibernate comes to mind) if you need caching between your Java domain objects and your database schema.
A: If you don't need a distributed cache, just a simple in-memory cache, Google Guava providers cache-semantics Map implementations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Similar pattern to promises/deferred's that support multiple results and cancellation Similar to the promises pattern I'm looking for an event pattern that avoids needing to pollute objects with addEventListener/etc methods, I want to be able to return an object, that can be cancelled as well as 'resolved' multiple times.
For example, I may write a method that returns an 'interval' object, something like this:
var ticker = createTicker(1000);
var subscription = ticker.then(function() { console.log('tick') });
... later on ...
subscription.cancel();
The key differences here being, similar to a promise the events are standardized, so that I can subscribe without needing to know the event name, however unlike a promise, the "completion" can happen multiple times, and may even be cancelled (this would be equiv of removeEventListener).
I'm interested to see if this is legal with promises, such that the progress handler could be used for multiple callbacks, and the complete handler never used, but more importantly, that there is a concept of unsubscribing from a promise.
If this isn't the case, and promises are specialized to this scenario, is there a standardized pattern for doing what I described?
A: The ability to cancel can be added to a promise implementation, without breaking the main paradigm of having single-fire success/failure callbacks.
In fact, jQuery already has cancellation for the promise instances that it returns from jQuery.ajax calls:
For backward compatibility with XMLHttpRequest, a jqXHR object will
expose the following properties and methods:
*
*readyState
*status
*statusText
*responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
*setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
*getAllResponseHeaders()
*getResponseHeader()
*abort()
You could write a setTimeout wrapper that exposes a promise interface along with an additional cancel method.
However, once you get into the multi-fire territory, I think that is not what promises are intended for. You would have to define a lot of rules and exceptions around how multiple firing will play out alongside regular promise functionality. It doesn't make a lot of sense to me to use promises that way.
Update (based on discussion in comments):
Here's a sample implementation of a promise "proxy" that allows aborting further relaying of the done/fail callbacks:
http://jsfiddle.net/atesgoral/qvtqu/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to use php set_error_handler for undefined indexes in arrays I want to make a single function for set_error_handler() to deal with undefined indexes in an array with a specific name. For instance, the array is called: $products.
If I have
$products = array(1 => 'a', 2 => 'b' // etc...
and later execute call:
$a = $products[0];
I get an error. I want to handle the error only for the array with the name $products and no other.
How can I make that?
Please don't give me alternatives to this method of solving the problem. I already had a discussion about that and it was decided that it really is better to use this method. I must also warn that this is a super simplification of the real thing.
I have already tried doing some research and nothing helped.
A: Setting up the error handler is easy enough - examples here - but filtering based on the code which actually triggered the error just isn't achievable without some very messy regex matching (or something similar) against the error message string.
You're probably going to have to look at some other form of solution if you really require this functionality. You could use isset() to check index validity beforehand, or create an array-style class (e.g. using ArrayAccess or ArrayObject from the SPL) with some index-checking logic built-in.
I know you didn't want different solutions, but I'd be interested to find out why/how you decided that the method you're proposing really is the best way?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588918",
"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.