text stringlengths 8 267k | meta dict |
|---|---|
Q: ECB context menu in Aquamacs ECB (Emacs Code Browser) has context menu to add file, delete file etc. The context menu is opened when clicking right mouse button.
The problem is Aquamacs intercepts that mouse button event. When we click right mouse button in Aquamacs, it opens its own context menu. (In the Emacs downloaded from emacsformacosx.com, the context menu is opened correctly.)
How to open ECB context menu in Aquamacs? Is there a way to disable Aquamacs default context menu? Or is there a way to tell ECB to use other way to open its context menu?
A: Answers from the mailing list of Aquamacs:
1.
Pretty much all key bindings in Aquamacs are bound in osx-key-mode-map (see Aquamacs FAQ). The mouse button bindings aren't any different.
Press C-h k, then the right mouse button (over an Aquamacs window). This should bring up a help screen that explains that this key is called `down-mouse-3', and that it is bound to a function described as this:
(osx-key-mode-down-mouse-3 EVENT &optional PREFIX)
Activate context menu, when osx-key-mode-mouse-3-behavior' is
set toaquamacs-popup-context-menu' or nil
Looking up the documentation for this customization variable doesn't bring up anything useful, but we can undo the key binding (see Aquamacs FAQ, probably) using define-key:
(define-key osx-key-mode-map [down-mouse-3] nil)
2.
There is a second approach in place to return mouse-3 to its vanilla Emacs behavior:
In the Aquamacs help/manual, section 4.3 "Customizing Aquamacs behavior", under "Want some GNU Emacs 23 behavior back?" there is a list of Aquamacs-specific settings that can be customized, including "OS X Key Mode Mouse-3 Behavior". Try customizing that setting as described in the help -- that may allow ECB to behave as in vanilla Emacs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to replace "[X]" in a string with a particular value for each X? string Sample=@"
Select * from Table1 where Id =[MY Id]
and Column2=[MY Column2 Value]
";
This is SqlCommand CommandText I will replace all string that start with [ and end with ]
before use command
How Can I find parameter name beetwen [ and ] ?
Do I have to use string.IndexOf (Sample,'[') ets. or Is there another void to make easy?
A: Don't do that - look into using SqlParameter instead to parametrize your queries, this is build in, i.e.:
using(SqlCommand cmd = new SqlCommand("Select * from Table1 where Id = @id and Column2=@columnTwo", myConnection))
{
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.BigInt)).Value = someId;
cmd.Parameters.Add(new SqlParameter("@columnTwo", SqlDbType.NVarChar)).Value = "You name it";
//..
}
A: No - you should String.Format method - see here: http://msdn.microsoft.com/en-us/library/system.string.format%28v=VS.100%29.aspx
A: In addition to the possibility of using SqlParameter, you can define
string Sample=@"
Select * from Table1 where Id =[{0}]
and Column2=[{1}]
";
and then obtain the command as
string cmd = String.Format(Sample, id1, id2);
where id1 and id2 are your parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to retrieve the ID of the Link in Jquery? i am having a situation here ... please consider the following scenario
1) value coming from the database eg: personName ( whos id in the database is 3 )
2) i am making a link of the " personName " through @Html.ActionLink
3) the link id is "lnkName"
i want to retrieve the id of the personName which is 3 when the lnkName is clicked. please help me ..
here is my code for the link..
@foreach (var item in Model)
{
<h3> @Html.ActionLink(item.personName, "Details", "Post", new { Id = item.personID } , new { @id = "lnkName" } ) </h3>
here is the Jquery code i have got so far...
$(document).ready(function () {
$('#lnkName').click(function () {
$.ajax({
url: @Url.Action("AddViews","Post")
data: // how can i retrieve the id of the clicked link which is 3
});
});
});
A: Generate the link the way it should be, directly containing the correct url in the href property. This way you don't need to worry about it:
@Html.ActionLink(
item.personName,
"AddViews", // <!-- modify the action so that it directly points to the correct one
"Post",
new { id = item.personID },
new { @class = "lnkName" } // <!-- Notice that I use a class here instead of an id because ids must be unique in the DOM and in your code you have multiple links with the same id resulting into invalid markup
)
and then in a separate javascript file you could unobtrusively AJAXify this anchor:
$(document).ready(function () {
$('.lnkName').click(function () {
$.ajax({
url: this.href,
success: function(result) {
}
});
// that's important in order to cancel the default action
// or the browser will simply redirect to the url and the AJAX
// call will never have time to execute
return false;
});
});
This way you could put your javascript in a completely separate js file, the way it should be. And benefit of course from minifying it, gzipping it, caching it and even serving it from a CDN. Always try to put javascript in separate files and avoid them depending on server side expressions such as @Url.Action. I have shown you a way to avoid such undesired dependency.
A: When the link is clicked, you can get it's id via the this variable:
$(document).ready(function () {
$('#lnkName').click(function () {
var id = this.id; // <=== you can fetch the id of the clicked link via "this"
$.ajax({
url: @Url.Action("AddViews","Post"),
data: id
});
return(false);
});
});
If it's not the CSS ID that you want here (I wasn't sure in your question), but some other piece of data like the personID, then you should put that other piece of data as a data attribute on the link tag and fetch that attribute with jQuery using $(this).data("xxx").
For example, if the link generated by your server-side code looked like this:
<a href="xxx" class="lnkName" data-personID="3">
Then, in your click handler, you can fetch that personID like this (and then you would have to put it into your ajax parameters however you want it to be sent):
$(document).ready(function () {
$('#lnkName').click(function () {
var personID = parseInt($(this).attr("data-personID"), 10); // <===
$.ajax({
url: @Url.Action("AddViews","Post"),
data: personID
});
return(false);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the fastest algorithm to find the minimum difference between pairs of numbers in an array?
Possible Duplicate:
Is it possible to find two numbers whose difference is minimum in O(n) time
For example, in [4, 2, 7, 11, 8], the algorithm should return abs(7-8) = 1.
The brute force way will be O(n2) and sorting will give O(nlogn). Is there more efficient way?
Thanks
A: I think sorting and comparing is going to be your best bet. Something like:
function minDiff( arr ) {
var min,
temp,
initDiff = false,
arr = arr.sort( function(a, b){return a-b} ),
last = arr.length - 1,
i;
for ( i = 0; i < last; i++ ) {
if ( !initDiff ) {
min = arr[i + 1] - arr[i];
initDiff = true;
} else {
temp = arr[i + 1] - arr[i];
if ( temp < min ) {
min = temp;
}
}
}
return min;
}
var myArr = [ 1, 8, 5, 96, 20, 47 ],
min = minDiff( myArr );
console.log( min ); // 3
A: A similar question here - Is it possible to find two numbers whose difference is minimum in O(n) time . It appears to be O(nlogn).
This page may give useful background info too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: flex input box doesnot work in fullscreen mode i have a problem in flex fullscreen mode...
that is my input box doesnot work in fullscreen mode.
I could'nt able to type anything. and no keydown events are working.
A: Unfortunately keyboard control in full screen is very limited.
From Adobe documentation:
Currently, Adobe Flash Player does not allow keyboard input when
displaying content in full-screen mode. Flash Player 10 changes this,
allowing for a limited number of keys to be usable in full-screen
mode. These include Tab, the Space bar, and the (up, down, left,
right) arrow keys.
This change affects all SWF files played in Flash Player 10 or later.
This includes SWF files published for earlier versions of Flash, so
long as they are played within Flash Player 10. This also affects
non-app content in AIR.
Note: App content in AIR can set the value of stage.displayState to
StageDisplayState.FULL_SCREEN_INTERACTIVE for full keyboard support in
full-screen mode.
Original article here.
For more details check this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Some questions on .vimrc and vim configuration Generally on a unix system, there is a global vimrc file in the directory /etc or /etc/vim. You can also have a .vimrc file in your home directory that can customize your vi session.
Is it possible to have a .vimrc elsewhere in your directory tree so you can use different vi properties in different directories? This would be convenient because the editor properties that help you edit Python most quickly are different from those for editing, say, HTML.
This sort of thing does not seem to work be default on my mac or linux lappies. Is there a way to make it happen?
A: Vim has built functionality for this:
:se exrc
Enables the reading of .vimrc, .exrc and .gvimrc in the current
directory. If you switch this option on you should also consider
setting the 'secure' option (see |initialization|). Using a local
.exrc, .vimrc or .gvimrc is a potential security leak, use with care!
also see |.vimrc| and |gui-init|.
See http://damien.lespiau.name/blog/2009/03/18/per-project-vimrc/
For proper project support, there are several plugins have similar features. (which I don't use, so I can't recommend any).
A: If this is really a question of having different settings for different filetypes (rather than different locations on disk), then the correct thing to do is to put these files in ~/.vim/ftplugin. For example, this is the contents of my ~/.vim/ftplugin/haskell.vim:
setlocal autoindent
setlocal noexpandtab
setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4
To find out the right name for the script, simply open the kind of file you want to edit and use the :set ft? command (short for :set filetype?). Much more information is available via :help ftplugin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to layout scrollview and image on Android I would like to have a screen where most of it is a ScrollView occupying 80% of the screen, and the lower 20% is an image. Within the ScrollView, I'd like to be able to stack a long text over buttons at the end of it. (Think of it as a survey application.)
I am unable to get the layout to properly position the Scrollview and image. When I use wrap_content or fill_parent, the ScrollView, which contains text much longer than the screen, always pushes the image out of the screen.
How can I properly force the image to stay on the screen and limit the ScrollView's size?
A: In order to get 2 or more views laid out in an arbitrarily proportional way, you must use LinearLayout's "weight" functionality. You do this be applying the layout_weight attribute to the child views in the LinearLayout. The layout_weight attribute distributes any left-over space to its children in a proportional manner, based on their relative weights.
In this case, the "left-over space" can be defined as the amount of space in the LinearLayout that would be left-over, in the absence of any layout_weight attributes on any of its children.
So, in order for the size of the views to be determined in a way that is completely proportional to the size of their parent (and thus to each other as well), you must also set their height (or width, for a horizontal LinearLayout) to 0. In this case, the left-over space is in fact the entire height (width) of the LinearLayout, which is then divvied up proportionally among the children based on their relative weights.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading file in python without linebreak I want to be able to read a file and add a string onto it line by line without having a line break in the middle.
text_file = open("read_it.txt", "r")
print text_file.readline() + "0123456789"
Outputs to
>>
text
0123456789
>>
I would like have it output to this format
>>
text0123456789
>>
A: Use the rstrip method:
text_file.readline().rstrip() + "0123456789"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Performance of a Asp.Net Webforms application using WCF Service for getting data from a CMS Which disadvantages / problems might occur, if all content from a ASP.Net WebForms application was received through a WCF service, rather than through a direct database call?
(Entity Framework 4.0 as provider, SQL Server 2008 R2 as database)
A scenario would be content from a CMS. Instead of using a library which calls the database directly, I'm thinking of a WCF service that wraps the calls to the library.
Has anyone any experience with this and can tell me something about the performance?
A: I have implemented several web applications where all the data is retrieved though WCF. There are no noticeable performance impacts as long as your service is implemented well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Stylesheet control for QComboBox tick? I have a nice stylesheet for a QComboBox but I can't find how to style the tick.
The tick is a graphic that appears next to the currently selected item. There are two problems: 1. When the mouse is on the currently selected item, the selection-background-color is applied to the item but not the tick. 2. When another item is highlighted the tick is drawn disabled with an ugly stipple effect.
I guess it's somewhere under QComboBox::on but I don't know what it is.
A: The important control appears to be QComboBox::checked. Make sure to set color and background-color. Background colour cannot be a gradient. If background colour is set to the same as the rule for QComboBox QAbstractItemView then the chess board effect (stippling) can be avoided.
A: If you set the general style using:
#include <QCleanlooksStyle>
QCleanlooksStyle cleanLook;
QComboBox * combo = new QComboBox;
combo->setStyle(&cleanLook);
then the check marks aren't shown at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mysql query for between operator with range i have sample records ranking table
SNO NAME TYPE RANK1-RANK2 DATE
2 sd sdf ds Weekly 4 - 8 20-Sep-2011 19:23:02
3 asd asd Weekly 1 - 6 21-Sep-2011 19:23:02
4 sdsdsfsd Weekly 1 - 1000 22-Sep-2011 19:23:02
in the above example one records i have 20 sept 2011 i have ranks 1 - 8 , from form i used to select rank1 and rank2 , that rank1 and rank2 should not be in this range if insert to be success, other wise it should not be insert. for that i need select sql query can u any one answer this select sql query..
test case for SNO 2 record
chosen from form
rank1 - rank2 insert
1 - 3 true
2 - 6 false
5 - 7 false
10 - 100 true
A: if i understood correctly;
when you get a value other than 0 from this query, you can insert the data.
select count(*) from table t
where
(t.rank1 not between 4 and 8)
and
(t.rank2 not between 4 and 8)
and
t.date = '2011-09-20'
A: You can use this query to see if there is a record that prevents you from inserting. If it returns 1, then the insert would be prohibited.
SELECT COUNT (*) FROM table
WHERE rank1 NOT BETWEEN MIN(incomingRank1, incomingRank2) - 1
AND MAX(incomingRank1, incomingRank2) + 1
AND rank2 NOT BETWEEN MIN(incomingRank1, incomingRank2) - 1
AND MAX(incomingRank1, incomingRank2) + 1
AND date = incomingDate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Large PHP session slowing down web application I have a web application where complex permissions determine whether or not a user has access to each of thousands of different files. A user can see all files, but there is an indicator to open files that they have access to. A user has access to a file if someone else in their organization has access to it, or if someone that they are in a collaboration with has shared access to that file.
Right now, I have a complex PHP function that generates a large PHP session by building arrays of the files a user has access to, either in their organization or their collaborations, and merging these access arrays. When these files are displayed to the user, PHP checks this array to see if they have access, and if they do, it adds the button to open the file. I am doing it this way because running the query to check for access for each individual file ended up taking way too long when displaying long file lists, and PHP's in_array() was substantially faster.
The problem is...
The php session has gotten so large that it seems to be slowing down simple website functions to a crawl, and I need to think of a new way to do this.
My question is...
What would be the best way to replace PHP sessions for storing file permissions and file locations for thousands of files a user has access to, so that when lists of files are being displayed, PHP can rapidly retrieve this information, without needing to run a query for each individual file?
A: Hm, without knowing the full scope of the problem, I'd suggest adding a Sessions table in your database and include a FilePermissions field and a UserId field.
This field would store a json representation of your permissions structure. This would only require one call to the database and the majority of the processing would take place while parsing the json data server-side (which shouldn't be much overhead at all).
This is a standard way to reduce the size of client-side session information. A good rule of thumb is putting anything in the Sessions table that exposes the logic of your application.
Update
I would only store the files that they do have access to in the json field. Non-existence can be assumed as prohibiting them from accessing the files. This would again reduce the performance footprint.
This would only work if there isn't a complex permissions structure (like each file has permissions for read and write). If it doesn't, I'd say you're in the clear.
A: I'm not sure there is much you can do. Perhaps memcached can help, but I haven't used it (although, from what I heard, that's what it's used for).
You could persist the array in a file, although, as far as I know, that's exactly what sessions do.
You could also try using shared memory to persist user data in-memory between script launches.
Do you really need the entire list of user's permissions in one single array? That is, do you always display thousands of files to the user? If so, why? Would it be possible to redesign the system using AJAX to lazily fetch only a portion of files?
UPDATE: Another idea.
You could also precalculate permissions of the user for each file and store that in the database. Table could be called FilesPermittedPerUser and have two-column primary key userID / fileID. This will create an index that is sorted first by userID, then by fileID. A two-column key would also enforce uniqueness of entries.
Since it would then be indexed by user, you can simply ORDER BY userID and LIMIT 10, 10 to list only files 10-20. Fetching only parts of the list via AJAX would mean you'd never cause the terrible memory load that your scripts currently cause.
It would only require that whenever permissions of the file are updated (for example, file is created, file is deleted, group permissions are changed, group membership of user is changed, group membership of file is changed...) you would have to update the table. I suspect this should not be too difficult. Just make sure you do cache update in a transaction, to preserve operation atomicity.
You may also want to organize the filesystem in folders. It makes very little sense to just throw tons of files at users and have to maintain them at all times. Try throwing 10.000 files at Explorer/Finder/Nautilus and see what happens when you open that folder. Nothing nice, and they get to keep the memory around - and with PHP you don't.
Final idea (although you probably don't have to go to these extremes): rewrite filesystem APIs in something that isn't PHP and can keep the permission data around. Use PHP only to forward requests to this custom server that runs on a different.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Facebook API : Make profile picture for page - help needed It is possible to select a picture from an album and put it as profile picture for my fan pages with the facebook graph api ?
A: No it's not possible. Here is the official Page object document to check what can be done.
A: No. You can't even upload to the users profile picture album.
You can upload to a specific user's album by calling photos.getAlbums.
However, you cannot upload to a user's profile picture album.
https://developers.facebook.com/docs/reference/rest/photos.upload/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Locking with ConcurrencyMode.Multiple and InstanceContextMode.PerCall Do I need to implement my own locking in a WCF service that uses ConcurrencyMode.Multiple and InstanceContextMode.PerCall or InstanceContextMode.PerSession? Since a new ServiceContext object is created at every call or new session I should think that I would not, but I'm far from sure.
Example:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession,
IncludeExceptionDetailInFaults = false, MaxItemsInObjectGraph = Int32.MaxValue)]
public class ExampleService : IExample
A: If you use a PerCall instantiation, you don't need to worry about the concurrent mode, because only one request can use the instance, so you won't have lock issues.
For PerCall, if your client uses sessions and is able to send multiple requests at the same time (say, using the same proxy from numerous threads) then yes, you will need to lock objects which are not thread-safe. I guess you're using PerSession because you want to preserve state, so you'll need to lock your state changing methods/code.
A: No you don't have to add locking. Each call will get a fresh instance.
However, if you need state from a particular caller, that will have to be handled manually.
See this thread for more information
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: c++ win32 dynamic menu - which menu item was selected i have a win32 application (c++) that has a context menu bind to the right click on the notify icon. The menu/submenu items are dynamicly created and changed during runtime.
InsertMenu(hSettings, 0, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hDevices, L"Setting 1");
InsertMenu(hSettings, 1, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hChannels, L"Setting 2");
InsertMenu(hMainMenu, 0, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hSettings, L"Settings");
InsertMenu(hMainMenu, 1, MF_BYPOSITION | MF_STRING, IDM_EXIT, L"Exit");
In the code above hDevices and hChannels are dynamicly generated sub menus.
The dynamic menus are generated like this:
InsertMenu(hDevices, i, style, IDM_DEVICE, L"Test 1");
InsertMenu(hDevices, i, style, IDM_DEVICE, L"Test 2");
InsertMenu(hDevices, i, style, IDM_DEVICE, L"Test 3");
Is there any way of knowing which item was clicked without having to define each submenu item it's own ID (IDM_DEVICE in the code above)? In would like to detect that user clicked on submenu IDM_DEVICE and that he clicked on the first item (Test 1) in this submenu.
I would like to achive something like this:
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_DEVICE: // user clicked on Test 1 or Test 2 or Test 3
UINT index = getClickedMenuItem(); // get the index number of the clicked item (if you clicked on Test 1 it would be 0,..)
// change the style of the menu item with that index
break;
}
A: Try the following:
MENUINFO mi;
memset(&mi, 0, sizeof(mi));
mi.cbSize = sizeof(mi);
mi.fMask = MIM_STYLE;
mi.dwStyle = MNS_NOTIFYBYPOS;
SetMenuInfo(hDevices, &mi);
Now you'll get the WM_MENUCOMMAND instead of WM_COMMAND. The menu index will be in wParam and the menu handle in lParam. Take care to eat up messages only for known menus and past the rest to DefWindowProc. The code will be similar to this:
case WM_MENUCOMMAND:
HMENU menu = (HMENU)lParam;
int idx = wParam;
if (menu == hDevices)
{
//Do useful things with device #idx
}
else
break; //Ensure that after that there is a DefWindowProc call
A: One can also use TrackPopupMenuEx() with the flags TPM_RETURNCMD | TPM_NONOTIFY and get the id of the selected menu item without having to go thru WM_MENUCOMMAND.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to Change Jquery Menu Background Color? I have a Jquery menu and I would like to change background of it how can I do it ?
This is the website;
http://tinyurl.com/3g58vhb
Instead of Grey I would like to make it #4466DD
A: Go to common.css, line 849. Where it says "background-color:rgba(0,0,0,0.8)", replace it with your color. I won't pretend to understand that CSS, but that works (If you were looking to understand that just ignore this answer)...
Also, if you want to find these things out, you can use Google chrome>inspect element>go to the element you want to change>expiriment.
Hope this helps!
A: <p style="padding:0;margin:0;text-align:right;white-space:pre;color:#4466DD;">
Change the right value for color. ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Grails validate() overwrites rejects I'm aware that it's a bug, but calling validate() on a domain class overwrites any rejects that are put in before:
def save = {
def assignment = new Assignment(params)
assignment.errors.reject("assignment.error")
// Save
if (assignment.validate()) {
//rejected error is gone
assignment.save()
redirect action: "list"
}
else {
//render errors
render view: "create", model: [instance: assignment]
}
}
So, until this issue is fixed (it's been around since grails 1.0 and it's almost 2.0 now), is there any smart workaround to preserve rejects and use the if validate() then save() paradigm at once?
A: It's not a bug, it's by design. By calling validate() you're asking for the validation process to start over again. If you want manual reject() calls to be included in the errors, put them after the call to validate().
A: @Burt is right, sadly. It's by design, though that design is sketchy.
The problem is that grails validates on its own behind the scenes in certain cases, wiping custom errors where they should not be wiped.
So not only do you have to avoid calling validate(), you have to avoid the platform silently erasing your errors at various points as well.
Sometimes you can get around this by using Domain.read(params.id) instead of Domain.get(params.id).
Grails read() Docs
The resulting relationship between manually adding errors and grails automatic behavior is rather non-intuitive in my opinion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Table name as parameter using PDO/MySQL prepared statement Is this possible? e.g.
SELECT * FROM :database WHERE id = :id
If not, should I just do this:
SELECT * FROM ' . $database . ' WHERE id = :id
Or is there some other trick I need to learn?
A: Table and Column names cannot be replaced by parameters in PDO.
see Can PHP PDO Statements accept the table or column name as parameter?
A: It is quite dangerous to pass dynamically built table names in a query. But if it is so much needed by your application, you have to sanitize the data. Since PDO cannot help with this, you have to call mysql_real_escape_string on the table name yourself. Also you will have to enclose the table name with backticks as `table_name`. So prepare the query as:
'SELECT * FROM `' . mysql_real_escape_string($database) . '` WHERE id = :id
One note: mysql_real_escape_string needs an already established connection to the DB.
EDIT: But when I think about it, probably is best to match the $database variable against your existing tables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Emacs project management for Scala I would like to ask if any of you have any experience {and,or} could point me to a project management extension for Emacs that works well with {Scala,Ensime,SBT}. It would also be amazing if it didn't require too much hacking. I did some scheme in the past but I have little experience with the Emacs platform.
Basically, by project management I mean mainly the ability to 'tie files into project' and then search among them (and only among them).
Thanks for taking the time to read this and answer!
A:
I really hate that you can't setup projects out of the box, though.
Just set up the project with sbt or maven and import it with ensime.
Essentially, what i would want is to be able to flex-find files in the project
"flex-find" is not English, so I don't really know what you mean. But what is wrong with find (the command line tool)?
A: With ensime you can load your project and then search for a type or method by name. The key sequence is C-c C-v v. This allows you to, for example, jump directly to a class definition.
A: The package projectile has a bunch of generic project-level features, such as running commands in the project root folder, grepping, creating TAGS files etc.
I'm a relatively new user of it, so I can't say exactly how big a difference it makes, but it seems like a worthwhile addition to your tool belt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: C# string.Replace problem I have a string like this:
string query = "INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, @address, @address2)"
then I replace @address with 'Elm Street' using
query = query.Replace("@address", "'" + "Elm Street" + "'");
and the result become:
INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, 'Elm Street', 'Elm Street'2)
how to get the result:
INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, 'Elm Street', @address2) ?
A: If this is a SQL query you going about it wrong - you should use SqlParameter to parametrize your query, no need for string replacement:
string query = "INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, @address, @address2)";
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
cmd.Parameters.Add(new SqlParameter("@address", SqlDbType.NVarChar)).Value = "Elm Street";
//add other parameters
cmd.ExecuteNonQuery();
}
A: Well, first I should mention that normally you shouldn't be doing this at all. You should put the values in parameter objects that you use in the command.
If you really need to do that for some weird reason, you can use a regular expression to match all parameters, and replace one of them:
query = Regex.Replace(query, @"@\w+", m => {
if (m.Value == "@address") {
return "'Elm Street'";
} else {
return m.Value;
}
});
A: How about:
string query = "INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, @address1, @address2)";
query = query.Replace("@address1", "'Elm Street'");
Sometimes the simplest solution is the right one. Not in this case. You should really use the SqlCommand approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS table default padding or margin Today it's my first time I'm playing around with tables
and I have noticing that the table and tr and td tags have a little space between them,
like 1 px or so.
So here is my problem :
There is my code :
<table id="upload_box_container">
<tr>
<td class="border_bottom_1px">hi1</td>
<td class="border_bottom_1px">hi2</td>
</tr>
</table>
(upload_box_container - it's just background color and border color)
(border_bottom_1px - as it's name it only gives bottom border with 1px size)
and there is a picture of how it displays:
http://postimage.org/image/16wz2ao78/
My question is
*
*why there is a space between the two bottom borders
*and why there is a space in the sides of the table (like padding) and the borders don't touch the table border
thanks.
A: You need to reset the default styles applied by the browser.
Try at the top of your css file:
table, table tr, table td { padding:none;border:none;border-spacing:0;}
And check into some popular CSS resets out there:
http://meyerweb.com/eric/tools/css/reset/
http://developer.yahoo.com/yui/reset/
A: Define
table { border-spacing:0; }
and it should render in the way you want.
A: I prefer to use this approach:
table { table-layout:fixed; border-collapse:collapse; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Dynamically added table rows not appearing I have seen many posts regarding dynamically adding table rows, but I am not sure what I'm missing.
When I execute the following, nothing is displayed (aside from application title bar).
My Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/table_view_test_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ScrollView
android:id="@+id/tvt_scroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
>
<RelativeLayout
android:id="@+id/tvt_scroll_relative"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:id="@+id/tvt_tableview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</TableLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table_view);
TableLayout tableLayout = (TableLayout) findViewById(R.id.tvt_tableview);
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView column1 = new TextView(this);
column1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
column1.setBackgroundColor(Color.YELLOW);
column1.setTextColor(Color.BLUE);
column1.setText("Col1 Value");
tableRow.addView(column1);
TextView column2 = new TextView(this);
column2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
column2.setBackgroundColor(Color.RED);
column2.setTextColor(Color.GREEN);
column2.setText("Col2 Value");
tableRow.addView(column2);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
//tl.refreshDrawableState();
//findViewById(R.id.tvt_scroll_relative).refreshDrawableState();
}
A: Change the two references
ViewGroup.LayoutParams
to
TableRow.LayoutParams
and it should work.
Adding layout params to a widget requires that the LayoutParams are a inner class of the surrounding layout container.
A: I think this has something to do with you setting the layout params to the TextViews. If you remove those definitions the info appears. Also if you take a look at the official documentation for TableRow you can see:
The children of a TableRow do not need to specify the layout_width and layout_height attributes in the XML file. TableRow always enforces those values to be respectively MATCH_PARENT and WRAP_CONTENT.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I show a Balloon Tip over a textbox? I have a C# WPF application using XAML and MVVM. My question is: How can I show a balloon tooltip above a text box for some invalid data entered by the user?
I want to use Microsoft's native balloon control for this. How would I implement this into my application?
A: This BalloonDecorator Project is one that I am using on a current project to show help hints and error notifications. I know you could modify your error template to show this decorator, just like you could show an icon instead of the red borders. The benefit of using a decorator is you can make it look however you'd like, and won't have to depend on WinForms.
BalloonDecorator.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace MyNamespace
{
public class BalloonDecorator : Decorator
{
private static double _thickness = 0;
private static int OpeningGap = 10;
public static readonly DependencyProperty BackgroundProperty =
DependencyProperty.Register("Background", typeof (Brush), typeof (BalloonDecorator));
public static readonly DependencyProperty BorderBrushProperty =
DependencyProperty.Register("BorderBrush", typeof (Brush), typeof (BalloonDecorator));
public static readonly DependencyProperty PointerLengthProperty =
DependencyProperty.Register("PointerLength", typeof (double), typeof (BalloonDecorator),
new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof (double), typeof (BalloonDecorator),
new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure));
public Brush Background
{
get { return (Brush) GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
public Brush BorderBrush
{
get { return (Brush) GetValue(BorderBrushProperty); }
set { SetValue(BorderBrushProperty, value); }
}
public double PointerLength
{
get { return (double) GetValue(PointerLengthProperty); }
set { SetValue(PointerLengthProperty, value); }
}
public double CornerRadius
{
get { return (double) GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
protected override Size ArrangeOverride(Size arrangeSize)
{
UIElement child = Child;
if (child != null)
{
double pLength = PointerLength;
Rect innerRect =
Rect.Inflate(new Rect(pLength, 0, Math.Max(0, arrangeSize.Width - pLength), arrangeSize.Height),
-1 * _thickness, -1 * _thickness);
child.Arrange(innerRect);
}
return arrangeSize;
}
protected override Size MeasureOverride(Size constraint)
{
UIElement child = Child;
Size size = new Size();
if (child != null)
{
Size innerSize = new Size(Math.Max(0, constraint.Width - PointerLength), constraint.Height);
child.Measure(innerSize);
size.Width += child.DesiredSize.Width;
size.Height += child.DesiredSize.Height;
}
Size borderSize = new Size(2 * _thickness, 2 * _thickness);
size.Width += borderSize.Width + PointerLength;
size.Height += borderSize.Height;
return size;
}
protected override void OnRender(DrawingContext dc)
{
Rect rect = new Rect(0, 0, RenderSize.Width, RenderSize.Height);
dc.PushClip(new RectangleGeometry(rect));
dc.DrawGeometry(Background, new Pen(BorderBrush, _thickness), CreateBalloonGeometry(rect));
dc.Pop();
}
private StreamGeometry CreateBalloonGeometry(Rect rect)
{
double radius = Math.Min(CornerRadius, rect.Height / 2);
double pointerLength = PointerLength;
// All the points on the path
Point[] points =
{
new Point(pointerLength + radius, 0), new Point(rect.Width - radius, 0), // Top
new Point(rect.Width, radius), new Point(rect.Width, rect.Height - radius), // Right
new Point(rect.Width - radius, rect.Height), // Bottom
new Point(pointerLength + radius, rect.Height), // Bottom
new Point(pointerLength, rect.Height - radius), // Left
new Point(pointerLength, radius) // Left
};
StreamGeometry geometry = new StreamGeometry();
geometry.FillRule = FillRule.Nonzero;
using (StreamGeometryContext ctx = geometry.Open())
{
ctx.BeginFigure(points[0], true, true);
ctx.LineTo(points[1], true, false);
ctx.ArcTo(points[2], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
ctx.LineTo(points[3], true, false);
ctx.ArcTo(points[4], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
ctx.LineTo(points[5], true, false);
ctx.ArcTo(points[6], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
// Pointer
if (pointerLength > 0)
{
ctx.LineTo(rect.BottomLeft, true, false);
ctx.LineTo(new Point(pointerLength, rect.Height - radius - OpeningGap), true, false);
}
ctx.LineTo(points[7], true, false);
ctx.ArcTo(points[0], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
}
return geometry;
}
}
}
Just make sure that this class's namespace is loaded into the XAML imports (I use a namespace called "Framework"), and it is simple to use:
<Framework:BalloonDecorator Background="#FFFF6600" PointerLength="50"
CornerRadius="5" Opacity=".9" Margin="200,120,0,0"
HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="{Binding UnitPriceChangedBalloonVisibility}">
<Border CornerRadius="2">
<Border CornerRadius="2">
<Button Height="Auto" Command="{Binding CloseUnitPriceChangedBalloonCommand}" Background="Transparent" BorderBrush="{x:Null}">
<TextBlock Text="Please review the price. The Units have changed."
HorizontalAlignment="Left"
VerticalAlignment="Top"
FontStyle="Italic"
TextWrapping="Wrap"
Margin="10"
/>
</Button>
</Border>
</Border>
</Framework:BalloonDecorator>
Obviously, I tie the visibility to a binding, but you could just set it to true and put this inside your Validation.ErrorTemplate.
Hope this helps!
A: I've been searching for a better solution than the BalloonDecorator, and ran across the http://www.hardcodet.net/projects/wpf-notifyicon project. It is using the WinAPI at the lowest level, which might give you a head start on building your own solution. It appears that at first glance it could potentially solve it, but I haven't had enough time to verify that the BalloonTip can be made to behave as you've described.
Good luck on your project!
A: Just add a reference to System.Windows.Forms and C:\Program Files\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\WindowsFormsIntegration.dll
and then:
WindowsFormsHost host =new WindowsFormsHost();
var toolTip1 = new System.Windows.Forms.ToolTip();
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
toolTip1.ShowAlways = true;
toolTip1.IsBalloon = true;
toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
toolTip1.ToolTipTitle = "Title:";
System.Windows.Forms.TextBox tb = new System.Windows.Forms.TextBox();
tb.Text="Go!";
toolTip1.SetToolTip(tb, "My Info!");
host.Child = tb;
grid1.Children.Add(host); //a container for windowsForm textBox
and this is a sample for WinForm ToolTip Ballon in WPF:
Hope this help!
A: Maybe you can host a Windows Forms control in WPF using the WindowsFormsHost type.
There is a walkthrough available on MSDN on how to do this:
Hosting a Windows Forms Composite Control in WPF
Using this technique you could perhaps use the System.Windows.Forms.ToolTip control. If you set this control's IsBalloon property to true it will display as a balloon window.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Using a JavaScript method from Facebook I found this code from Facebook. I would like to use a structure in this way. How can I use this method?
for (;;);{"__ar":1,"payload":null,"css":["wOyD6","Dk+z9","uUZcv"],"js":["TNp9j","12BHN"],"onload":["(function(){var k=Arbiter.subscribe(\"xhpc\\\/construct\\\/\"+this.id,function(_,c){(function(){Arbiter.unsubscribe(k);}).defer();c.mutate({\"xhpc\":\"u598502_6\",\"endpoint\":\"\\\/ajax\\\/questions\\\/save.php\",\"formType\":1,\"inputHidden\":true,\"placeholder\":\"Bir \\u015fey sor...\",\"buttonLabel\":\"Payla\\u015f\",\"blurb\":\"\\u003ca class=\\\"addPollOptionsLink\\\" rel=\\\"async\\\" ajaxify=\\\"\\\/ajax\\\/questions\\\/show_poll_composer.php?xhpc_ismeta=true\\\">Anket \\u015e\\u0131klar\\u0131 Ekle\\u003c\\\/a>\",\"content\":\"\\u003cdiv class=\\\"webComposerQuestion\\\">\\u003cinput type=\\\"hidden\\\" autocomplete=\\\"off\\\" name=\\\"source\\\" value=\\\"composer\\\" \\\/>\\u003cdiv class=\\\"mas\\\">\\u003ctextarea class=\\\"DOMControl_placeholder uiTextareaNoResize uiTextareaAutogrow questionInput fluidInput\\\" title=\\\"Bir \\u015fey sor...\\\" spellcheck=\\\"true\\\" name=\\\"question\\\" maxlength=\\\"500\\\" placeholder=\\\"Bir \\u015fey sor...\\\" id=\\\"u614163_1\\\" onfocus=\\\"return wait_for_load(this, event, function() {if (!this._has_control) { new TextAreaControl(this).setAutogrow(true); this._has_control = true; } });\\\">Bir \\u015fey sor...\\u003c\\\/textarea>\\u003c\\\/div>\\u003c\\\/div>\",\"hideTopicTagger\":true});c.subscribe(\"init\", new Function(\"onloadRegister(function (){Input.enableAutoCapitalize($(\\\"u614163_1\\\"), \\\"\\\");});\\n\"));});;}).apply(DOM.find(this.getRelativeTo(),\"^div.uiComposer\"))"],"bootloadable":{"maxlength-form-listener":["LayX0","nO1QQ","12BHN"]},"resource_map":{"wOyD6":{"type":"css","src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/yC\/r\/Zg0ARUxUS6N.css"},"Dk+z9":{"type":"css","src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/yw\/r\/q4nJ2ZkJtyT.css"},"uUZcv":{"type":"css","permanent":1,"src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/yO\/r\/4okS7_KFNGX.css"},"TNp9j":{"type":"js","src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/yo\/r\/8rrAXwg5z80.js"},"12BHN":{"type":"js","src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/yg\/r\/jkR6Xtb9PGX.js"},"LayX0":{"type":"js","src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/yn\/r\/HT0e0kw4zvt.js"},"nO1QQ":{"type":"js","src":"https:\/\/s-static.ak.facebook.com\/rsrc.php\/v1\/y8\/r\/Cu4Eol99gUR.js"}}}
A: It's not clear what exactly you are asking. You can't "run" this code, it's a JSON string. If you want to access the data, you'll need to parse it some way, for example parseJSON in jquery.
I suspect you may be getting tripped up by the leading for (;;); string. This is a protective device put there to keep people from simply using eval() to process the data. Using eval() is an old quick-and-dirty way to parse JSON directly into javascript variables, but it's an unsafe practice. To prevent it Facebook adds the for-loop code to the front of the string, so that if you try to eval it you just get an infinite loop and a hung browser. You could of course strip that part off of the string and then use eval anyway, but you're much better off parsing it properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: didSelectViewController for subclass of UITabBarController not working So I've created MainViewController which is a subclass of UITabBarController:
@interface MainViewController: UITabBarController {
}
I initialized this from the app delegate and then set delegate to self:
MainViewController * main = [[MainViewController alloc] init];
main.delegate = self
then I had:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
}
but this was never called.. why is this? Is this because this was a subclass?
A: Just to clarify: do you have
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
in MainViewController, or in your app delegate?
That method should be defined in whichever class you choose to be your UITabBarControllerDelegate. For example, in my app I have:
*
*A regular UITabBarController (there's no need to subclass UITabBarController unless you're doing something fancy)
*My app delegate implements UITabBarControllerDelegate - specifically, tabBarController:shouldSelectViewController:
*I set tabBarController.delegate to be the app delegate
That should be everything you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why HTML5 Geolocation? Why does HTML5 geolocation let you share your location? What is main purpose of using geolocation, as you can get the location with IP address as well. Is there any difference between these two methods?
I'm asking because geolocation requires the user's permission and also doesn't work on all browsers.
A: Geolocation is a lot more precise than IP address, though both can be faked.
IP address just gives you country and general region.
Geolocation gives you:
*
*Geographic coordinates (latitude and longitude)
*Speed (assuming you're on a device that can measure this; most tablets and smartphones can)
*Altitude (this is also dependent on the device)
*Degrees clockwise from north (again, assuming the device supports this)
http://diveintohtml5.ep.io/geolocation.html has some good info on geolocation and the HTML5 geolocation API. Here's the W3C Candidate Recommendation.
A: The major difference that you will see is the accuracy. IP addresses only give you a very general idea of where someone might be... Geolocation will tell you exactly where they are. To read more on geolocation go here, and a demo of how accurate it can be can be is found here
A: Obtaining a user's location through the IP-address is by far not as accurate. The IP-address' location is mostly based on the location of the actual server, which can be requested. Often this is far away from the actual user's location, so it only provides the basic region.
HTML5 geolocation on the other hand is more precise, but the user's information is used to determine the location and often also speed along with some other things. This is based on the device's GPS if available, and otherwise on information entered by the user. Clearly this is way more accurate. Both methods can be faked though.
A: Getting location by IP address only gives a vague location (it is rarely any more accurate than to town, and often much less accurate than that, depending on your location and ISP).
It is also sometimes completely inaccurate: if I use a VPN to connect to my company network, I will show up as being at their office because I will have an IP address from the office, but I could actually be connecting from anywhere in the world.
HTML5 geolocation can be much more accurate -- if you have a GPS receiver in your device, then it is completely accurate, but even without that, in heavily populated areas it can get your position with an accuracy of 20 meters or less by mapping the local wireless network signals. And it doesn't matter how you've connected, it will always be accurate.
Because HTML5 geolocation is so accurate, it is considered a privacy risk, so the spec states that you must give permission before a site can use your gelocation data. Also, not all browsers or machines may be capable of providing the gelocation data. The website therefore must be able to cope with users who do not provide it, and cannot rely on it being provided.
IP address location doesn't have this kind of restriction because the location mapping is done by the server using publically available IP location mapping data. The end user cannot avoid giving out their IP address, so they cannot prevent the website mapping them using it.
So the two are completely different.
A: HTML5 GeoLocation tends to be much more accurate than IP-based GeoLocation.
IP-based GeoLocation depends on databases associated with ISPs to figure out where you are. This doesn't work well when your ISP services a very large area and gives out dynamic IP addresses. The address in one town today might be 100 miles away tomorrow. Furthermore, those databases are usually not updated frequently. If your ISP sells off blocks of IPs or moves them to a new town, the database may still incorrectly think you're somewhere else.
HTML5 location uses services provided by your browser to figure out where you are. If your computer has GPS built-in (such as on many mobile devices and some laptops), it will know exactly where you are. This makes it much more useful for webapps that have a navigation or location component. For devices without GPS, it can often provide a very good approximation based on nearby known wireless signals and other factors, such as tracing what routers your computer goes through when connecting to the internet. The exact implementation depends on the computer, what hardware it has available, and how the browser chooses to do things.
For example, when I check an IP-based location service, it says that I'm in a particular large city in the same general area that I live in, but it's actually about 50 miles away.
When I use an HTML5 location based service to figure out where I am, it's only off by about 20 blocks.
If you're developing a webapp which needs location data, try using HTML5 GeoLocation if at all possible. Set up a fallback, so that if HTML5 location fails, you can use an GeoIP solution instead. This way, you will get optimal accuracy on supported browsers and devices, but will still have a solution in place when the HTML5 data are not available.
If you used the geolocation-javascript project from Google Code, you could use the following code:
//determine if device has geo location capabilities
if(geo_position_js.init()){
geo_position_js.getCurrentPosition(success_callback,error_callback);
}
else{
// use an AJAX request to look up the location based on IP address
}
A: HTML5 geolocation gives the client (browser) the possibility to provide the location information of the machine. This is potentially orders of magnitude more accurate than IP location. For example, the client could have actual GPS hardware installed, or be able to triangulate the location by GSM or WiFi spots. Location by IP on the other hand is very rough and somewhere between not always accurate and misleading.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How to create div with 100% height with jquery mobile? How to create div with id=test with 100% height?
<div data-role="page" id="device1">
<div data-role="header">
<h1>Title</h1>
</div><!-- /header -->
<div data-role="content">
<div data-role="fieldcontain">
<input type="range" name="slider1" id="slider1" value="0" min="0" max="255" />
</div>
<div id=test height=100%>
</div>
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
</div><!-- /footer -->
</div><!-- /page -->
A: OK, here is what I have for you. Keep in mind though, if the content of the page is tall at all this might not be very usable. The swipe area is everything below the content. So as the content area gets bigger the swipe area gets smaller.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Swipe</title>
<link href="jquery-mobile/jquery.mobile-1.0b3.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0b3.min.js" type="text/javascript"></script>
<script src="phonegap.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
// Set the initial window (assuming it will always be #1
window.now = 1;
//get an Array of all of the pages and count
windowMax = $('div[data-role="page"]').length;
$('.swipeArea').bind('swipeleft', turnPage);
$('.swipeArea').bind('swiperight', turnPageBack);
});
// Named handlers for binding page turn controls
function turnPage(){
// Check to see if we are already at the highest numbers page
if (window.now < windowMax) {
window.now++
$.mobile.changePage("#device"+window.now, "slide", false, true);
}
}
function turnPageBack(){
// Check to see if we are already at the lowest numbered page
if (window.now != 1) {
window.now--;
$.mobile.changePage("#device"+window.now, "slide", true, true);
}
}
</script>
<style>
body, div[data-role="page"], div[data-role="content"], .swipeArea {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div data-role="page" id="device1"">
<div data-role="header">
<h1>Page One</h1>
</div>
<div data-role="content">
Content
<div class=swipeArea></div>
</div>
<div data-role="footer" data-position="fixed">
<h4>Page Footer</h4>
</div>
</div>
<div data-role="page" id="device2" style="height: 100%">
<div data-role="header">
<h1>Content 2</h1>
</div>
<div data-role="content" style="height: 100%">
Content
<div data-role="fieldcontain">
<label for="slider">Input slider:</label>
<input type="range" name="slider" id="slider" value="0" min="0" max="100" />
</div>
<div class=swipeArea></div>
</div>
<div data-role="footer" data-position="fixed">
<h4>Page Footer</h4>
</div>
</div>
<div data-role="page" id="device3" style="height: 100%">
<div data-role="header">
<h1>Content 3</h1>
</div>
<div data-role="content" style="height: 100%">
Content
<div class=swipeArea></div>
</div>
<div data-role="footer" data-position="fixed">
<h4>Page Footer</h4>
</div>
</div>
<div data-role="page" id="device4" style="height: 100%">
<div data-role="header">
<h1>Content 4</h1>
</div>
<div data-role="content" style="height: 100%">
Content
<div class=swipeArea></div>
</div>
<div data-role="footer" data-position="fixed">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using Ribbon control with PRISM I want to create a composite wpf application with ribbon control using Prism,
and I have some thoughts about commanding:
The ribbon tab is in different view, so i guess it will have specific view model. but the command should be in another view model, because when I click on button in the ribbon, I want to do some action in the view below, so how can I bind it? should I use Event Aggregator to communicate between the view models? maybe Composite command? any other approch?
Thanks.
A: Because it's a different Views/ViewsModels - EventAggregator is a way to go. You use command on a View with ribbon that executes Method on RibbonViewModel which will Publish that event. Other views subscribe to that event.
If you use Ribbon as a menu - then maybe you should use PRISM's Navigation to open other views (in different region)
A: This is the typical scenario for composite commands
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JGraphT cannot be cast to org.jgrapht.graph.DefaultWeightedEdge I'm new Java and am using jGraphT to create a SimpleDirectedWeightedGraph. I'm getting this error when trying to set weights on my edges after creating and adding them to the graph:
Exception in thread "main" java.lang.ClassCastException: ObservationsDAG$ObservationsDAGEdge cannot be cast to org.jgrapht.graph.DefaultWeightedEdge
at org.jgrapht.graph.AbstractBaseGraph.setEdgeWeight(Unknown Source)
I am assuming I need to do something in my ObservationsDAGEdge class here, but from looking at the JGraphT docs, I am stuck as to what that is. Does my edge class need weight instance variable and do I need to provide getEdgeWeight() and setEdgeWeight()?
A: So, I figured this out. I first tried extending DefaultDirectedEdge, but then getEdgeTarget() stopped working - probably because I need to implement start/end vertices.
After reading the code, I tried subclassing SimpleDirectedWeightedGraph and overrode setEdgeWeight and getEdgeWeight and gave my edge class a weight instance variable.
That finally worked as sexpected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Modify DOM with JQuery after any AJAX Call over which I don't have control I'm working with SharePoint 2010, one of the aspx pages contains a Note Board web part which provides simple functionality to leave a comment on a given page.
When the page is loaded the comments are retrieved by that web part using AJAX, I DO NOT have control over when that AJAX call is complete.
I'm trying to insert a link or some text within each of the table data tags that the web part uses for the comments i.e.
<td class="socialcomment">Comment 1</td>
<td class="socialcomment">Comment 2</td>
<td class="socialcomment">Comment 3</td>
to
<td class="socialcomment">Comment 1 <a href="#">Report inappropiate</a></td>
<td class="socialcomment">Comment 2 <a href="#">Report inappropiate</a></td>
<td class="socialcomment">Comment 3 <a href="#">Report inappropiate</a></td>
using JQuery like this
$('td.socialcomment').append(' <a href="#">Report inappropiate</a>');
I haven't been able to use the live() function of JQuery in the above scenario (worked for other scenarios I have), but I think that is because it was designed for events.
I have also tried the .ajaxComplete() but it hasn't worked out at all I believe because I don't have control of the Ajax call or the Ajax call that SharePoint performs is not registered with JQuery.
Any help or insight is much appreciated.
Thanks in advance!
A: I'd definitely like to learn of a better way than this - you could use setInterval to periodically check for elements in the DOM that match your selector and which you haven't already 'processed' and add your link to them and mark them as 'processed'. I wouldn't be very optimistic about the performance though.
Something like:
setInterval(processComments, 250);
//...
function processComments() {
$('td.socialcomment:not(.processed)').append(' <a href="#">Report inappropiate</a>').addClass('processed');
}
Here's a fiddle.
Update
According to this jQuery forum thread, the liveQuery plugin apparently can let you specify functions that will be executed when new elements are added to the DOM (using jQuery's DOM manipulation methods, if I understand correctly).
A: If the ajax calls in Sharepoint are made using jQuery's ajax framework, then you can register a global ajaxComplete handler that will get called when any ajax call is completed. This only works for ajax calls made using jQuery though.
A: I was facing the same problem and i was able to make use of the live function like this
$(window).load(function() {
$('span.socialcomment-username').find("a").live({
click: function() {
alert("asd");
},
mouseover: function() {
$(this).removeAttr('href');
$(this).removeAttr('onclick');
},
mouseout: function() {
$(this).removeClass("over");
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: list access in webform markup my datasource is a list of customers in a webforms project
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { FirstName = "John", PhoneNumber = "999.999.9999" });
customers.Add(new Customer() { FirstName = "Jane", PhoneNumber = "999.999.9999" });
}
is there a way to iterate that in an aspx page of a web forms project. (this is easy in mvc using the model)?
A: Use the Repeater control for this. Here is an example:
Markup:
<asp:Repeater ID="CustomerRepeater" runat="server">
<ItemTemplate>
<span>Name:</span> <%# Eval("FirstName") %>
<span>Phone:</span> <%# Eval("PhoneNumber ") %>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { FirstName = "John", PhoneNumber = "999.999.9999" });
customers.Add(new Customer() { FirstName = "Jane", PhoneNumber = "999.999.9999" });
CustomerRepeater.DataSource = customers;
CustomerRepeater.DataBind();
}
A: Use `DataSource' of server control: (in example DropDownList)
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.ddlCustomers.DataSource = this.GetCustomers();
this.ddlCustomers.DataBind();
}
}
public List<Customer> GetCustomers()
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { FirstName = "John", PhoneNumber = "999.999.9999" });
customers.Add(new Customer() { FirstName = "Jane", PhoneNumber = "999.999.9999" });
return customers;
}
Default.aspx
<asp:DropDownList ID="ddlCustomers" runat="server" DataTextField="FirstName" DataValueField="FirstName"></asp:DropDownList>
Or if you needed you can use 'MVC-style' in aspx:
<% foreach(WebApplication1.Customer customer in this.GetCustomers()) { %>
<span><%= customer.FirstName %></span>
<% } %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to get the String from StringBuilder fast? I have a feeling that using the: StringBuilder.toString() is slow and very resource-consuming..
So I'm thinking about something like this:
public static void doSomething(String data){ ... }
public static void main(String[] args)
{
StringBuilder s = new StringBuilder();
doSomething(""+s);
}
But I want to know if there is an other "better and fast" way than this, because doSomething(""+s) in a loop will make a new instance of String because of the empty quotes "" I think, and it's not a good idea to put this inside a loop.
A: doSomething(""+s); gets translated to the following code by the JVM
doSomething( new StringBuilder().append("").append(s.toString() ).toString() );
So now, instead of having 1 string builder you have 2, and called StringBuilder.toString() twice.
The better and faster way is to use just StringBuilder, without concatenating string manually.
I just checked the bytecode generated with java 1.6.0_26 and the compiler is intelligent and calls toString() only once, but it still creates 2 instances of StringBuilder. Here's the byte code
0 new java.lang.StringBuilder [16]
3 dup
4 invokespecial java.lang.StringBuilder() [18]
7 astore_1 [s]
8 new java.lang.StringBuilder [16]
11 dup
12 invokespecial java.lang.StringBuilder() [18]
15 aload_1 [s]
16 invokevirtual java.lang.StringBuilder.append(java.lang.Object) : java.lang.StringBuilder [19]
19 invokevirtual java.lang.StringBuilder.toString() : java.lang.String [23]
22 invokestatic my.test.Main.doSomething(java.lang.String) : void [27]
25 return
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using custom annotations to generate biolerplate code Folks,
I am about to write a ton of J2EE/JAX-RS code where practically all public methods will do the following:
*
*Look for the presence of a security token in the request header.
*Call a utility to make sure the token is valid.
*If not valid, return an error response (or inject a null token)
*If valid, do some stuff, which might involve introspecting the token
*In most cases, return an updated token in response headers.
I'd love to be able to use annotations to abstract out this piece. I am imagining something like the following on the method:
@RequireToken( returnRenewed=true )
@POST
@Path( "/some/path" )
public Result myMethod( ... )
{
@InjectedToken
final Token securityToken;
...
}
Any pointers on how to proceed?
A: Have you considered using spring security for those actions? You might implement your own authentication filters.
If not spring security, maybe AOP and "before" or "around advice"s ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can MVC route resolution mechanism be re-configured? I have implemented custom VirtualPathProvider to serve customizable Views from a DB and when i put a breakpoint on the FileExists method I noticed that the framework does ton of unnecessary (for my project) requests. For example when I make a request for non-existing action (e.g. http://localhost/Example/Action) the framework looks for:
*
*"~/Example/Action/5"
*"~/Example/Action/5.cshtml"
*"~/Example/Action/5.vbhtml"
*"~/Example/Action.cshtml"
*"~/Example/Action.vbhtml"
*"~/Example.cshtml"
*"~/Example.vbhtml"
*"~/Example/Action/5/default.cshtml"
*"~/Example/Action/5/default.vbhtml"
*"~/Example/Action/5/index.cshtml"
*"~/Example/Action/5/index.vbhtml"
*"~/favicon.ico"
*"~/favicon.ico.cshtml"
*"~/favicon.ico.vbhtml"
*"~/favicon.ico/default.cshtml"
*"~/favicon.ico/default.vbhtml"
*"~/favicon.ico/index.cshtml"
*"~/favicon.ico/index.vbhtml"
When I make a request that matches an added route (e.g http://localhost/Test) the framework looks for:
*
*"~/Test"
*"~/Test.cshtml"
*"~/Test.vbhtml"
*"~/Test/default.cshtml"
*"~/Test/default.vbhtml"
*"~/Test/index.cshtml"
*"~/Test/index.vbhtml"
before even initialising the controller. After the controller is initialised the framework looks for the view as defined in the custom RazorViewEngine that I have implemented.
This is my ViewEngine
AreaViewLocationFormats = new string[] { };
AreaMasterLocationFormats = new string[] { };
AreaPartialViewLocationFormats = new string[] { };
MasterLocationFormats = new string[] { };
ViewLocationFormats = new string[] {
"~/Views/Dynamic/{1}/{0}.cshtml",
"~/Views/Dynamic/Shared/{0}.cshtml",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml"
};
PartialViewLocationFormats = new string[] {
"~/Views/Dynamic/{1}/Partial/{0}.cshtml",
"~/Views/Dynamic/Shared/Partial/{0}.cshtml",
"~/Views/{1}/Partial/{0}.cshtml",
"~/Views/Shared/Partial/{0}.cshtml"
};
FileExtensions = new string[] { "cshtml" };
So the question is can these default routes be removed and how?
A: Could they be related to the RouteCollection.RouteExistingFiles property? I doesn't make sense for it to check for lots of files rather than just one that matches, but it might be worth turning off to see if it makes any difference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Allow only alphanumeric characters for a UITextField How would I go about allowing inputting only alphanumeric characters in an iOS UITextField?
A: The RegEx way in Swift:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.isEmpty {
return true
}
let alphaNumericRegEx = "[a-zA-Z0-9]"
let predicate = NSPredicate(format:"SELF MATCHES %@", alphaNumericRegEx)
return predicate.evaluate(with: string)
}
A: Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString: with an NSCharacterSet containing the inverse of the characters you want to allow. For example:
// in -init, -initWithNibName:bundle:, or similar
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
// in -dealloc
[blockedCharacters release];
Note that you’ll need to declare that your class implements the protocol (i.e. @interface MyClass : SomeSuperclass <UITextFieldDelegate>) and set the text field’s delegate to the instance of your class.
A: Swift 3 version
Currently accepted answer approach:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Get invalid characters
let invalidChars = NSCharacterSet.alphanumerics.inverted
// Attempt to find the range of invalid characters in the input string. This returns an optional.
let range = string.rangeOfCharacter(from: invalidChars)
if range != nil {
// We have found an invalid character, don't allow the change
return false
} else {
// No invalid character, allow the change
return true
}
}
Another equally functional approach:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Get invalid characters
let invalidChars = NSCharacterSet.alphanumerics.inverted
// Make new string with invalid characters trimmed
let newString = string.trimmingCharacters(in: invalidChars)
if newString.characters.count < string.characters.count {
// If there are less characters than we started with after trimming
// this means there was an invalid character in the input.
// Don't let the change go through
return false
} else {
// Otherwise let the change go through
return true
}
}
A: This is how I do it:
// Define some constants:
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC @"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
// Make sure you are the text fields 'delegate', then this will get called before text gets changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// This will be the character set of characters I do not want in my text field. Then if the replacement string contains any of the characters, return NO so that the text does not change.
NSCharacterSet *unacceptedInput = nil;
// I have 4 types of textFields in my view, each one needs to deny a specific set of characters:
if (textField == emailField) {
// Validating an email address doesnt work 100% yet, but I am working on it.... The rest work great!
if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
} else {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
}
} else if (textField == phoneField) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
} else if (textField == fNameField || textField == lNameField) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
} else {
unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
}
// If there are any characters that I do not want in the text field, return NO.
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
Check out the UITextFieldDelegate Reference too.
A: I found a simple and working answer and want to share:
connect your UITextField for the event EditingChanged to following IBAction
-(IBAction) editingChanged:(UITextField*)sender
{
if (sender == yourTextField)
{
// allow only alphanumeric chars
NSString* newStr = [sender.text stringByTrimmingCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
if ([newStr length] < [sender.text length])
{
sender.text = newStr;
}
}
}
A: For Swift:
Connect your UITextField for the event EditingChanged to following IBAction:
@IBAction func ActionChangeTextPassport(sender:UITextField){
if sender == txtPassportNum{
let newStr = sender.text?.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
if newStr?.characters.count < sender.text?.characters.count{
sender.text = newStr
}
}
}
A: You will have to use the textField delegate methods, and use methods textFieldDidBeginEditing, shouldChangeCharactersInRange and textFieldDidEndEditing to check for the characters.
Please refer to this link for the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How to show a component by the controller? I need to register an user and after that I would like to call a <rich:popupPanel> for example to show the error or successful message with an icon.
<rich:popupPanel id="popup" modal="false" autosized="true" resizeable="false">
<f:facet name="header">
<h:outputText value="Simple popup panel" />
</f:facet>
<f:facet name="controls">
<h:outputLink value="#"
onclick="#{rich:component('popup')}.hide(); return false;">
X
</h:outputLink>
</f:facet>
<p>Any content might be inside this panel.</p>
</rich:popupPanel>
How do I do that after the validation of the register process in my controller ?
I could call a <h:message>, but I think a popupPanel with some icon and the status message would be more appropriate to the user.
A: In general, you'd just set some (boolean) toggle or a specific object property in the bean's action method which is then used in the rendered attribute of the containing component in question. Here's an example with a simple boolean:
private boolean success;
public void submit() {
// ...
success = true;
}
public boolean isSuccess() {
return success;
}
with
<rich:popupPanel rendered="#{bean.success}">
...
</rich:popupPanel>
You can also set some object property and then check if it is not empty or null. E.g. when the User is successfully saved after registration and thus got an ID from the DB:
<rich:popupPanel rendered="#{not empty bean.user.id}">
...
</rich:popupPanel>
Note: in the particular case of your <rich:popupPanel>, you can also use the show attribute instead of rendered attribute.
<rich:popupPanel show="#{bean.success}">
...
</rich:popupPanel>
The only difference is that when show is false, the component is still rendered, but then with CSS display:none; so that it is visually hidden in the HTML DOM tree, so that you can redisplay it with just JavaScript.
See also:
*
*Conditionally displaying JSF components
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I make any C++ library I make thread safe? First of all, I'm fairly experienced with C++ and understand the basics of threading and thread synchronization. I also want to write a custom memory allocator as a pet project of mine and have read that they should be thread-safe.
I understand what the term "thread-safe" means, but I have no idea on how to make C++ code thread-safe.
Are there any practical examples or tutorials on how to make code thread-safe?
In a memory allocator scenario, is it essentially ensuring that all mutating functions are marked as critical sections? Or is there something more to it?
A: Same as all threading issues: make sure that when one thread is changing something, no other thread is accessing it. For a memory allocation system, I would imagine you would need a way of making sure you don't allocate the same block of memory to 2 threads at the same time. Whether that is by wrapping the entire search, or by allowing multiple searches but locking when the allocation table is to be updated (which could then cause the result of the search to become invalid, necessitating another search) would be up to you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Variable radius Gaussian blur, approximating the kernel I'm writing a Gaussian blur with variable radius (standard deviation), i.e. each pixel of the image is convolved using a different kernel. The standard techniques to compute Gaussian blur don't work here: FFT, axis-separation, repeated box-blur—they all assume that the kernel is the same for the whole image.
Now, I'm trying to approximate it using the following scheme:
Approximate the Gaussian kernel K(x,y) with a piecewise constant function f(x,y) defined by a set N of axis-aligned rectangles Rk and coefficients αk as:
f(x,y) = ∑k=1N αk·χRk(x,y)
Let g(x,y) be our image, then
∬ℝ2 K(x,y)·g(x,y) dxdy ≈
∬ℝ2 f(x,y)·g(x,y) dxdy = ∑k=1N αk·∬Rkg(x,y) dxdy
The integral on the RHS is a simple integral over a rectangle, and as such can be computed in constant time by precomputing the partial sums for the whole image.
The resulting algorithm runs in O(W·H·N) where W and H are the dimensions of the image and N is (AFAIK) inverse proportional to the error of the the approximation.
The remaining part is to find a good approximation function f(x,y). How to find the optimal approximation to the Gaussian when given either the number of rectangles N (minimizing the error) or given the error (minimizing the number of rectangles)?
A: Given the locations and size of the rectangles, it should be fairly easy to work out your coefficients, so the real problem is working out where to put the rectangles.
Since you are approximating a Gaussian, it seems at least reasonable to restrict our attention to rectangles whose centre coincides with the centre of the Gaussian, so we actually have only a 1-dimensional problem - working out the sizes of a nested set of rectangles which I presume are either squares or are similar to the Gaussian if you have an aspect ratio other than unity.
This can be solved via dynamic programming. Suppose that you work from the outside into the middle. At stage N you have worked out an n x k table that gives you the best possible approximation error coming from 1,2...N rings of outer pixels for up 1,2,..k different rectangles, and the size of the innermost rectangle responsible for that best error. To work out stage N+1 you consider every possible size for what will be an innermost rectangle so far, contributing x rings of pixels to the outer area. You work out the alpha for that rectangle that gives the best fit for the pixels in the new ring and the rings outside it not left to outer rectangles. Using the values in the table already calculated you know the best possible error you will get when you leave up to k outer rectangles to cover those areas, so you can work out the best total error contributed from what is now N+1 rings of pixels. This allows you to fill in the table entries for N+1 outer pixels. When you have worked your way into the middle of the area you will be able to work out the optimal solution for the whole area.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I use the GTGE library? Java 2D games I downloaded from the official site a zip containing a jar and a "docs" folder, inside there is a "com" folder and a "resources" folder. I want to be able to use this libray in my java IDE (eclipse) but when i type : import com.golden.*; it does not recognise the command.
How do I add this library so that I can actually use it with programming? Please be as specific as possible, as I seem to have a natural talent in failing to follow instructions.
A: *
*Right click on your project
*Select properties
*Select the Java build path from the list to left side
*Click libraries on the right side
*Click on "Add external JARS"
*Select your file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to apply javascript formatting to .json files? The Ctrl + Shift + F hotkey in Eclipse can format a file. It doesn't work for .json files. How to make it work?
A: There are two options I figured out using Eclipse Luna (4.4.0).
Use a JSON Editor Plugin and define shortcuts
*
*Download and install the JSON Editor Plugin from sourceforge manually or use the Eclipse marketplace (Help -> Eclipse marketplace) to find and install the plugin
*Go to Window -> Preferences -> General -> Keys and filter for "format text".
*Choose "Format Text" and set the "When:" value to "Editing Text" (sadly there is no explicit condition for JSON editing, but the format event for the JSON Editor is different to the other editors, so "Editing Text" will work aswell)
*Set the "Binding:" to Ctrl + Shift + F
Use the Javascript Development Plugin with an ugly and anoying workaround
*
*Get the plugin using Help -> Install New Software -> Work with: "http://download.eclipse.org/releases/luna" -> Programming Languages -> JavaScript Development Tools
*Associate *.json files with the JavaScript Editor (Window -> Preferences -> General -> Editors -> File Associations)
*You can now create files with "json" extension and edit them in Eclipse using the JavaScript Editor, but formatting with Ctrl + Shift + F will not work directly with the following unformatted example:
{"addressbook": {"name": "John Doe",
"address": {
"street": "5 Main Street", "city": "San Diego, CA", "zip": 91912
},
"phoneNumbers": [
"619 555-3452",
"664 555-4667"
]
}
}
*
*The hack is to create a valid JavaScript variable from the object description like this:
var obj = {"addressbook": {"name": "John Doe",
"address": {
"street": "5 Main Street", "city": "San Diego, CA", "zip": 91912
},
"phoneNumbers": [
"619 555-3452",
"664 555-4667"
]
}
}
*
*Using Ctrl + Shift + F will now work
*In the end you will have to remove the "var obj =" hack to make the JSON file valid again
A: You could use the JavaScript editor that ships with Eclipse.
A: You'll want to get the JSON Editor plugin if you don't already have it. You can find it here
The JSON Editor is a simple plugin for the Eclipse IDE that provides: - Color text highlighting - An Outline Tree view - JSON validation - Text formatting - Text folding for the JSON data format.
If the hot keys still don't work. Take a look under the menu as shown in the picture from their site here
Also, I see that there has been at least one issue with what looks to be the current versions formatting feature in the past.
From their discussion site:
rlespinola
2010-07-15 00:18:05 UTC
Using version 0.9.4, I do not see the option to "Format Text". Also, when I open a .json file, the outline view says "An outline is not available".
jdschulteis
2010-12-27 16:59:24 UTC
Using 0.9.4 on Helios, I also had "An outline is not available". I went to Window->Preferences->General->Editors->File Associations, selected '*.json' in the 'File types:' list, selected 'Json Editor' in the 'Associated editors:' list, and clicked 'Default'. I now get an outline, though it can be somewhat slow (6K line file).
Edit:
There are several ways to add a plugin. Eclipse recommends using the update manager.
Try help > software updates > find and install
You can look here for some alternative methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Hard-coding URLs vs Nested Set vs Combo in Content System I've been putting together a database to handle content produced for a site, however, thinking about the long-term, I'm unsure if I have the best system.
At present I'm using the routing method of passing everything via index.php which .htaccess routes as follows index.php?route=example/url (user sees http://www.domain.com/example/url)
At present the database is setup like below:
uid | title | content | category
--------------------------------------------------
/ | Home | aaa | 1
/example | Example | bbb | 2
/example/url | Example: URL | ccc | 2
Though I am not sure if this is the best approach, especially if I wanted to rename example to something - I'd have to rename each URL...
So I've also thought about the Nested Set method (such as http://www.phpclasses.org/package/2547-PHP-Manipulate-database-records-in-hierarchical-trees.html) though this would just show lots of different numbers in the database where I could access everything by it's node. Example below;
node | left | right | name
--------------------------
1 | 1 | 6 | Home
2 | 2 | 5 | Example
3 | 3 | 4 | URL
Then I could use the node as the uid? But I'm unsure how I could translate http://www.domain.com/example/url to the uid equalling 3...
I already do have a category column in my database at the moment, to categorise the content, though I could potentially alter this.
I'm basically looking for suggestions about how to proceed, because as the site gets more content it will be harder to change the setup - so I want to ideally get this right from day one.
*
*Which of the two is better for scalability?
*If the second, how to translate the URL to the node?
*Could I somehow combine both so that the original database stores the uid as the node number, then do a join of some sort to make the uid be a url (as in 1) - then ]
^ I think I'd prefer this (the third), but unsure how to do in MySQL exactly, with some other benefits:
*
*I could replace my category system with the parent node - which may be better
*I could also then in theory store the node ID within a stats system, rather than a URL
If anyone can give some help/suggestions - I'd be grateful!
A: Well, if you use index.php?route=example/url, you could always do something like this:
$args = explode( '/', $_GET['route'] );
$args = filter_var_array( $_GET['route'], FILTER_SANITIZE_STRING );
Then your values of $args would be:
0 -> example
1 -> url
etc. You could then use these values to determine what template to load, and what content to grab from the database, or whatever else you're doing already.
HTH.
A: The nested set model probably is a good choice here. That'd result in a table layout like (id,left,right are the fields required by the nested set model, the others contain the respective content):
| id | left | right | uid | title | content | category |
More details on how to perform a particular query can be found here.
However I would not perform the look up on the database but a simple array cache:
new array('/' => array('content' => 'aaa', 'category' => 'bbbb'),
'/example/' => array(),
.....
);
This cache can be build up very easy (though expensive) and queried very easy.
On a side note: i suspect you're trying to model page content here. Maybe you should refactor you database structure then as this table would have two responsibilities (url->content mapping and content).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Serve Django project on local WiFi Network I used
python manage runserver 0.0.0.0:8000
to start the server so that I can access the project from other computers on my wifi network, but when i browse to internet-ipaddress:8000 on an another computer, the project doesn't load. Am I missing a setting?
A: What do you mean by internet-ipaddress? That sounds like you're using the external IP of your router. You should be using the IP of the particular machine you're serving from, which will be an internal address like 192.168.0.2.
A: You should bind it to your local IP address. For example
python manage.py runserver 192.168.1.100:8000
A: You should check out solutions like Pagekite or Show Off as they're generally trivially easy to set up and offer a great deal of flexibility (and mobility) and provide a stable domain name to your localhost server.
A:
Note: 192.168.2.5 is my ip. So, give your own
Open settings.py and add this to ALLOWED_HOSTS
ALLOWED_HOSTS = ['192.168.2.5']
Then run command
python manage.py runserver 192.168.2.5:8000
Allow access in the firewall's warning appeared.
Now access your host from the systems on same network.
A: Assuming all the machines can see eachother ...
get the IP address of the machine you are running runserver on. For example run ifconfig at the console.
ifconfig
eth0 Link encap:Ethernet HWaddr 10:1e:72:b8:2a:4b
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
...
check if you are running a firewall. For example
sudo ufw status
if active, you need to open port 8000 so, again at the console, run
sudo ufw allow 8000/tcp
then start the runserver (or runserver_plus if using django-extensions)
python manage.py runserver_plus 192.168.1.2:8000
open a browser on another machine
http://192.168.1.2:8000/admin
A: add 192.168.0.8 (or whatever your router ip is) as a string to ALLOWED_HOSTS list in settings then run server using python manage.py runserver 192.168.0.8:8000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java Spring Web Service Client Fault Handling I have written a web service client (using Java Spring and JAXB Marshaller) that works with the UPS web service. When I send a valid request everything works well. When I send an invalid request (weight > 150 lbs) then the UPS web service responds with a SOAP Fault. The client application just fails with a
org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling
exception; nested exception is javax.xml.bind.UnmarshalException:
unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault").
Obviously my program isn't able to decipher the SOAP fault returned by the web service. I wrote a custom FaultMessageResolver, but it doesn't get invoked. Here's the code:
public class UpsRateClient extends WebServiceGatewaySupport {
public UpsRateClient(WebServiceMessageFactory messageFactory) {
super(messageFactory);
getWebServiceTemplate().setFaultMessageResolver(new UpsFaultMessageResolver());
}
public RateResponse getRate(RateRequest rateRequest) {
return (RateResponse) getWebServiceTemplate().marshalSendAndReceive(rateRequest, new UpsRequestWSMC());
}
private class UpsFaultMessageResolver implements FaultMessageResolver {
public void resolveFault(WebServiceMessage message) throws IOException{
System.out.println("Inside UpsFaultMessageResolver");
}
}
}
Thanks for your time!
A: I had the same problem (SOAP error with HTTP 200OK) and I solved it setting the CheckConnectionForFault property to false. See.
A: Take a wireshark trace.My thought is that perhaps the web service sends the SOAP fault using (erroneously) a HTTP 200OK instead of a 500 Internal Server error and your client tries to handle it as a valid response.
If this is the case this is then the problem lies in the web service which does not addere to SOAP standard(my emphasis):
From SOAP RFC
In case of a SOAP error while processing the request, the SOAP HTTP
server MUST issue an HTTP 500 "Internal Server Error" response and
include a SOAP message in the response containing a SOAP Fault element
(see section 4.4) indicating the SOAP processing error.
If you do not own the web service, they should fix this.
To be honest I am not sure what the work arround would be in Spring-WS.
If I really needed a work arround in Jax-Ws I would replace the stub call with a Dispatcher to handle the raw xml myself and avoid the automatic marshal/demarhal.
Look into Spring-Ws if you can do the same, but this is a bug of the web service, not your client
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to dynamically display output in android? I am developing a small application that executes shell commands and displays the output say for example ping command. The application has an edittext which takes the hostname or IP as input from user and a button to execute the command. For the time being I have used an ArrayList which stores the output generated after the execution of the command. But it is not a proper way to display the output, I would rather prefer to display the output dynamically like a standalone command line display which displays the output line by line on runtime. Is there any specific way to display the output during runtime.
The following is code
protected void executePingCommand() {
List<String> output=new ArrayList<String>();
output.clear();
try
{
Process pr=Runtime.getRuntime().exec(new String[]{"su","-c","ping -c 5 "+ipadd});
BufferedReader br=new BufferedReader(new InputStreamReader(pr.getInputStream()));
String var=null;
String temp=br.readLine();
while((var=br.readLine())!=null)
{
output.add(var);
display(output);
}
}
catch(Exception e)
{
}
}
protected void display(List<String> output2) {
// TODO Auto-generated method stub
pingOutput.setAdapter(new ArrayAdapter<String>(this, R.layout.custom_list_view, output2 ));
return;
}
A: Sounds like you need to setup a runnable that would execute with an onclicklistener. IE user types in the IP address, clicks button. It then refreshes your view to show the new item.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: JQuery Mobile Redirect Help This site is not redirecting to the .mobi site. Is that because the redirect script is not at the top of the "head" and is conflicting with the other scripts that are being called first? Any suggestions? Other people seem to say it just needs to be in the head area. That is not working though.
The hosting company entered the code, but put it at the bottom. Do you think that this is why it's not redirecting? I asked them to put it there and I guess they forgot. Before I ask them to do it again, I wanted some input on whether this could be causing the problem?
<head>
<!-- SW3 -->
<title>Rosenhouse Group, PC, a professional tax and accounting firm in Dallas, Texas</title>
<script type="text/javascript" language="javascript" src="/menu.js"></script>
<script type="text/javascript">
adroll_adv_id = "7LYERGMOVZEPTB3B62NLZD";
adroll_pix_id = "KN5CT4JO5NEKLEGKBSHDQF";
(function () {
var oldonload = window.onload;
window.onload = function(){
__adroll_loaded=true;
var scr = document.createElement("script");
var host = (("https:" == document.location.protocol) ? "https://c.adroll.com" : "http://c.adroll.com");
scr.setAttribute('async', 'true');
scr.type = "text/javascript";
scr.src = host + "/j/roundtrip.js";
document.documentElement.firstChild.appendChild(scr);
if(oldonload){oldonload()}};
}());
</script>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="icon" type="image/ico" href="favicon.ico"/>
<script src="js/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$.noConflict();
</script>
<meta name="keywords" content="Rosenhouse Group, PC, L. Minton Rosenhouse, CPA, Dallas, Texas, 75252-5897, , , , , , , , , , , , , , , , , , , , , , , , , ">
<meta name="author" content="Emochila Website Design for CPAs Lawyers and Dentists">
<meta name="description" content="">
<link rel="stylesheet" href="sb/cssfile.jsp?decider=mrosenhouse&content=1500" type="text/css">
<script type="text/javascript">// <![CDATA[
var mobile =
(/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.user
Agent.toLowerCase()));
if (mobile) {
document.location = "http://www.cpadallas.mobi";
}
// ]]></script>
<meta name="google-site-verification" content="Fl04TuB3stq95hUqds8jcKHuWRjxeCjO8orCnSn1SyY" />
</head>
A: Looking at the source code of http://www.cpadallas.com your main issue is that the regex is across multiple lines.
Can you change it to be
<script type="text/javascript">
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
document.location = "http://www.cpadallas.mobi";
}
</script>
I would encourage you to look at a more robust redirection strategy in the future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to search for comments ("") using Jsoup? I would like to remove those tags with their content from source HTML.
A: When searching you basically use Elements.select(selector) where selector is defined by this API. However comments are not elements technically, so you may be confused here, still they are nodes identified by the node name #comment.
Let's see how that might work:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
public class RemoveComments {
public static void main(String... args) {
String h = "<html><head></head><body>" +
"<div><!-- foo --><p>bar<!-- baz --></div><!--qux--></body></html>";
Document doc = Jsoup.parse(h);
removeComments(doc);
doc.html(System.out);
}
private static void removeComments(Node node) {
for (int i = 0; i < node.childNodeSize();) {
Node child = node.childNode(i);
if (child.nodeName().equals("#comment"))
child.remove();
else {
removeComments(child);
i++;
}
}
}
}
A: With JSoup 1.11+ (possibly older version) you can apply a filter:
private void removeComments(Element article) {
article.filter(new NodeFilter() {
@Override
public FilterResult tail(Node node, int depth) {
if (node instanceof Comment) {
return FilterResult.REMOVE;
}
return FilterResult.CONTINUE;
}
@Override
public FilterResult head(Node node, int depth) {
if (node instanceof Comment) {
return FilterResult.REMOVE;
}
return FilterResult.CONTINUE;
}
});
}
A: reference @dlamblin https://stackoverflow.com/a/7541875/4712855 this code get comment html
public static void getHtmlComments(Node node) {
for (int i = 0; i < node.childNodeSize();i++) {
Node child = node.childNode(i);
if (child.nodeName().equals("#comment")) {
Comment comment = (Comment) child;
child.after(comment.getData());
child.remove();
}
else {
getHtmlComments(child);
}
}
}
A: This is a variation of the first example using a functional programming approach. The easiest way to find all comments, which are immediate children of the current node is to use .filter() on a stream of .childNodes()
public void removeComments(Element e) {
e.childNodes().stream()
.filter(n -> n.nodeName().equals("#comment")).collect(Collectors.toList())
.forEach(n -> n.remove());
e.children().forEach(elem -> removeComments(elem));
}
Full example:
package demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.stream.Collectors;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class Demo {
public static void removeComments(Element e) {
e.childNodes().stream()
.filter(n -> n.nodeName().equals("#comment")).collect(Collectors.toList())
.forEach(n -> n.remove());
e.children().forEach(elem -> removeComments(elem));
}
public static void main(String[] args) throws MalformedURLException, IOException {
Document doc = Jsoup.parse(new URL("https://en.wikipedia.org/"), 500);
// do not try this with JDK < 8
String userHome = System.getProperty("user.home");
PrintStream out = new PrintStream(new FileOutputStream(userHome + File.separator + "before.html"));
out.print(doc.outerHtml());
out.close();
removeComments(doc);
out = new PrintStream(new FileOutputStream(userHome + File.separator + "after.html"));
out.print(doc.outerHtml());
out.close();
}
}
A: Based on the answer from @dlamblin a Java 8 functional approach (sorry but this seems to be a littler simpler and cleaner than the aswer from @Feuerrabe)
private void removeComments(Node node) {
node.childNodes().stream().filter(n -> "#comment".equals(n.nodeName())).forEach(Node::remove);
node.childNodes().forEach(this::removeComments);
}
Document doc = Jsoup.parse(html);
removeComments(doc);
// ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: PHP - Why does including a function from another file fail? I am trying to include a function from one PHP file into another and use the function with a parameter and get a return value. All is good until I run the function, where PHP dies. How can I fix this?
timestamp_reader.php:
<?php
function get_time($timestamp){
$year = substr($timestamp, 0, 4);
$month = substr($timestamp, 4, 2);
if(substr($month, 0, 1) == "0")
$month = substr($month, 1, 1);
$day = substr($timestamp, 6, 2);
if(substr($day, 0, 1) == "0")
$day = substr($day, 1, 1);
$hour = substr($timestamp, 8, 2);
if(substr($hour, 0, 1) == "0")
$hour = substr($hour, 1, 1);
$hour = intval($hour);
if($hour > 12){
$hour = $hour - 12;
$pm = true;
}else $pm = false;
$minute = substr($timestamp, 10, 2);
if(substr($day, 0, 1) == "0")
$day = substr($day, 1, 1);
if($pm) $minute .= " PM";
else $minute .= " AM";
return $month . "/" . $day . "/" . $year . " " . $hour . ":" . $minute;
}
?>
And the file that I want access to this function (note, it is in a different directory):
...some PHP code before this...
include "/project/includes/timestamp_reader.php";
while($row=mysql_fetch_array($result)){
$msg = $row['message'];
$timestamp = $row['timestamp'];
$time = get_time($timestamp);
echo "<p><center>" . $time . " " . $msg . "</center></p>";
}
I'd like to figure this out and use it for a variety of functions so I don't have to type them in every time if possible. Also, I need something similar for creating project-wide variables.
Anyway, thanks for any and all help!
A: How about you avoid reinventing a wheel ? .. especially so misshapen one :
*
*http://www.php.net/manual/en/function.date.php
*http://www.php.net/manual/en/datetime.format.php
A: try with require(), it fails if the path is wrong, which I bet is the case.
A: Why not use the date() function within PHP?
For example,
$timestamp = "1316922240";
echo date("m-j-Y", $timestamp);
Will print out 09-24-2011 based on that time stamp for right now - if the timestamp was from yesterday, the date echo-ed will be yesterday.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wildcards in Generics: "? super T" works while "? extends T" does not? My question is about generics in Java 7. Suppose we have such class hierarchy:
interface Animal {}
class Lion implements Animal {}
class Butterfly implements Animal {}
Just like in Java Generics Tutorial
Also we have a class
class Cage<T> {
private List<T> arr = new ArrayList<>();
public void add(T t) {
arr.add(t);
}
public T get() {
return arr.get(0);
}
}
And here is the code which uses that classes:
public static void main(String[] args) {
Cage<? extends Animal> cage = new Cage<>();
Animal a = cage.get(); //OK
cage.add(new Lion()); //Compile-time error
cage.add(new Butterfly()); //Compile-time error
}
Question #1:
I have read here about these issues but there was simply like Cage<?>. But I tell the compiler <? extends Animal> so type T in Cage<T> will be any of subtypes of Animal type. So why it still gives a compile time error?
Question #2:
If I specify Cage<? super Animal> cage = ... instead of Cage<? extends Animal> cage = ... everything works fine and compiler doesn't say anything bad. Why in this case it works fine while in the example above it fails?
A: The cage must be able to hold both types of animals. "super" says that - it says that the Cage must be able to hold all types of animals - and maybe some other things, too, because ? super Animal might be a superclass of Animal. "extends" says that it can hold some kinds of animals - maybe just Lions, for instance, as in:
Cage<? extends Animal> cage = new Cage<Lion>();
which would be a valid statement, but obviously the lion cage won't hold butterflies, so
cage.add(new Butterfly());
wouldn't compile. The statement
cage.add(new Lion());
wouldn't compile either, because Java here is looking at the declaration of the cage - Cage<? extends Animal> - not the object that's assigned to it right now (Cage<Lion>).
The best description of generics I know of is in O'Reilly's Java in a Nutshell. The chapter is free online - part 1 and part 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Exception in "AWT-EventQueue-0" I appologise in advance for this question possibly being hard to interpret, but I'm trying to include the minimum information necessary (I doubt you want to be reading through 10 different classes looking for the error)
I have been making a simple(ish) application in java, using swing for the GUI. Currently I have a JTable, JList and a JButton. When a row is double clicked in the table, it is added to the list. When the button is clicked, a customised fileVisitor walks through a (currently hard-coded) directory and populates the table with the files it was finding. The list does nothing so far. This all worked as expected.
However, when the button is clicked, the whole application locks up for the ~15s it takes the fileVisitor to run. This is fine if a bit irritating. When the file tree walk ends, the application responds again (and the table updates all rows at once).
So I decided to put the Files.walkFileTree call in its own thread. At first this appeared to be effective, as each file was added to the table model it was reflected in the table (that was set to call revalidate on a model change). However, if I double clicked an item while the file tree walk was in progess, it would hang with the message: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "AWT-EventQueue-0"
After reading up on swing a bit, I assumed it was due to my editing the table model from a thread that was not the AWT dispatch thread, and promptly put the lines that edit the table model in a SwingUtilities.invokeLater(Runnable) block. However, this did not fix the issue. Weirdly (or possibly not, it seems weird to me), sometimes a double-click works, and it's only after 2 or 3 attempts that I cause the crash.
My question is: what can be causing this? I can't see anything else obviously wrong, and all my googling points to Swings lack of thread-safety, and using the AWT dispatch thread (which I thought was what invokeLater does). Anyone know what's wrong?
P.S. sorry again if anything's unclear, and that it's so long :P
A: There were two problems it turns out:
1) I was using a thread for my file tree walk rather than a swing worker doInBackground;
2) my double click code was actually producing a null pointer, but only if you got the timing right while the table was updating, I've fixed that now too. Thanks for looking.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Image Button only responds when clicking on the image and not the area around inside the button I'm using the following button style which takes away the borders and makes a transparent background to make my image buttons:
<Style x:Key="EmptyButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Background" Value="#00000000"/>
<Setter Property="BorderBrush" Value="#00000000"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The Style is from the following answer:
WPF button with image of a circle
The problem now is that the clickable area is confined to the image regardless of how big the actual button is:
My button code:
<Button Name="n02" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Style="{DynamicResource EmptyButtonStyle}" Canvas.Left="308" Canvas.Top="157" Height="106" Width="120">
<Image Source="boto_face_off.PNG" Height="61" Width="59" />
</Button>
Question: how do I make the whole button area react to the click? I want to keep it transparent and without border as it is now.
A: Just adding some info to the answer above after investigating the issue for hours.
If you are defining your own template as in the example above you are changing the visual tree of the element. In the above example applying the Style="{DynamicResource EmptyButtonStyle}" it becomes:
Button
|
ContentPresenter
But if you look at the visual tree of a standard button(you can do this in Visual Studio) it looks like this:
Button
|
ButtonChrome
|
ContentPresenter
So in the styled button there is nothing around the ContentPresenter to be clicked on, and if the Content is in the "middle" the surrounding area will be left totally empty. We have to add an element to take this place:
You can do it with a <Border>(I think this is best because Border is a lightweight element I suppose) or some other element, I tried <Grid> and <DockPanel> and both worked.
The only thing I don't understand is why you need to explicitly set the background to something transparent, just leaving it out will not produce a clickable area.
Edit: Last point answered in the comments here Image Button only responds when clicking on the image and not the area around inside the button
A: You could wrap the presenter in a Border with a bound Background.
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<!-- ContentPresenter here -->
</Border>
</ControlTemplate>
The style sets the Background to something transparent but it was never even used in the Template, this way the Border will make the whole area hit-test.
A: I have Button where content is Grid containing Image and TextBlock
I fixed clickable area by adding Transparent Background to grid
Background="#00000000"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: A list of predefined groovy variables I'm new to groovy and I'm wondering where can I find a full list of predefined
groovy variables like it and delegate?
The particular thing that I'm interested in is if there are predefined keyword for
the reference to the object from where the current method was invoked, for example:
5.times { print 5 - it}
with the use of such keyword it should be something like:
5.times { print *keyword* - it }
so the question is what's the keyword should be used there?
P.S.: another example:
MyObject myObject = new myObject();
myObject.getField(); // MyObject has method named getField
myObject.doJob ({
...
((MyObject)*keyword*).getField(); // instead of myObject.getField();
...
})
A: For a good list of all actual keywords (which are fewer than you'd think) and object-level properties that are like keywords, this article is really good: http://marxsoftware.blogspot.com/2011/09/groovys-special-words.html
If you have control over the doJob method in your example, then you should set the delegate of the closure:
def doJob(Closure closure) {
closure.delegate = this
closure.resolveStrategy = Closure.DELEGATE_FIRST
// loop or whatever
closure()
}
Now, in your closure, you can reference any properties on the parent object directly, like so:
myObject.doJob ({
...
getField()
...
})
Groovy Closures - Implicit Variables.
A: Are you asking for this?
int number = 5
number.times { print number - it }
Hope this will help you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python equivalent of find2perl Perl has a lovely little utility called find2perl that will translate (quite faithfully) a command line for the Unix find utility into a Perl script to do the same.
If you have a find command like this:
find /usr -xdev -type d -name '*share'
^^^^^^^^^^^^ => name with shell expansion of '*share'
^^^^ => Directory (not a file)
^^^ => Do not go to external file systems
^^^ => the /usr directory (could be multiple directories
It finds all the directories ending in share below /usr
Now run find2perl /usr -xdev -type d -name '*share' and it will emit a Perl script to do the same. You can then modify the script to your use.
Python has os.walk() which certainly has the needed functionality, recursive directory listing, but there are big differences.
Take the simple case of find . -type f -print to find and print all files under the current directory. A naïve implementation using os.walk() would be:
for path, dirs, files in os.walk(root):
if files:
for file in files:
print os.path.join(path,file)
However, this will produce different results than typing find . -type f -print in the shell.
I have also been testing various os.walk() loops against:
# create pipe to 'find' with the commands with arg of 'root'
find_cmd='find %s -type f' % root
args=shlex.split(find_cmd)
p=subprocess.Popen(args,stdout=subprocess.PIPE)
out,err=p.communicate()
out=out.rstrip() # remove terminating \n
for line in out.splitlines()
print line
The difference is that os.walk() counts links as files; find skips these.
So a correct implementation that is the same as file . -type f -print becomes:
for path, dirs, files in os.walk(root):
if files:
for file in files:
p=os.path.join(path,file)
if os.path.isfile(p) and not os.path.islink(p):
print(p)
Since there are hundreds of permutations of find primaries and different side effects, this becomes time consuming to test every variant. Since find is the gold standard in the POSIX world on how to count files in a tree, doing it the same way in Python is important to me.
So is there an equivalent of find2perl that can be used for Python? So far I have just been using find2perl and then manually translating the Perl code. This is hard because the Perl file test operators are different than the Python file tests in os.path at times.
A: If you're trying to reimplement all of find, then yes, your code is going to get hairy. find is pretty hairy all by itself.
In most cases, though, you're not trying to replicate the complete behavior of find; you're performing a much simpler task (e.g., "find all files that end in .txt"). If you really need all of find, just run find and read the output. As you say, it's the gold standard; you might as well just use it.
I often write code that reads paths on stdin just so I can do this:
find ...a bunch of filters... | my_python_code.py
A: There are a couple of observations and several pieces of code to help you on your way.
First, Python can execute code in this form just like Perl:
cat code.py | python | the rest of the pipe story...
find2perl is a clever code template that emits a Perl function based on a template of find. Therefor, replicate this template and you will not have the "hundreds of permutations" that you are perceiving.
Second, the results from find2perl are not perfect just as there are potentially differences between versions of find, such as GNU or BSD.
Third, by default, os.walk is bottom up; find is top down. This makes for different results if your underlying directory tree is changing while you recurse it.
There are two projects in Python that may help you: twander and dupfinder. Each strives to be os independent and each recurses the file system like find.
If you template a general find like function in Python, set os.walk to recurse top down, use glob to replicate shell expansion, and use some of the code that you find in those two projects, you can replicate find2perl without too much difficulty.
Sorry I could not point to something ready to go for your needs...
A: I think glob could help in your implementation of this.
A: I wrote a Python script to use os.walk() to search-and-replace; it might be a useful thing to look at before writing something like this.
Replace strings in files by Python
And any Python replacement for find(1) is going to rely heavily on os.stat() to check various properties of the file. For example, there are flags to find(1) that check the size of the file or the last modified timestamp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Sorted output of a joined MySQL result in PHP Doing an allnighter on a project and my mind is blank atm... Simple question really:
I have two MySQL tables, product and category. Each product belongs to exactly one category. Every category has several products.
SELECT
p.uid as product_uid, p.name_NL as product_name, p.price as product_price,
c.uid as category_uid, c.name_NL as category_name
FROM
product p, category c
WHERE
p.category_uid = c.uid
This gives me a nice overview of all products in their respective category. My question is about outputting this data on the page. I'm aiming for this:
<h1>Category name</h1>
<p>Product in this category</p>
<p>Other product in this category</p>
<h1>Next category</h1>
<p>Product in next category</p>
My mind is completely blank right now. How would one go about doing this?
I would like to avoid doing subqueries (if possible).
Kind regards,
M
A: What about adding ORDER BY category_uid so that the products are ordered by category in your SQL query. Then using PHP, loop through each product (row) and when you encounter a new category, add a new header.
Example:
<?php
// ...
$previous_category_uid = null;
// Loop through each row.
while ( $row = $result->fetch_assoc() )
{
// If the category UID is not the same as the one from the previous row, add a header.
if ( $previous_category_uid != $row['category_uid'] )
{
echo '<h1>' . $row['category_name'] . '</h1>';
$previous_category_uid = $row['category_uid'];
}
}
The benefit of this method is that you don't have to nest queries. A single query will suffice.
A: Don't you just need to use a GROUP BY category_uid ?
A: Assuming you're looking for alphabetical ordering for category names and products within each category:
SELECT
p.uid as product_uid, p.name_NL as product_name, p.price as product_price,
c.uid as category_uid, c.name_NL as category_name
FROM product p INNER JOIN category c ON p.category_uid = c.uid
ORDER BY category_name, product_name
This also converts your query's Cartesian product and WHERE to an inner join.
To output with the headers you want, just loop over the returned rows, and keep track of the category you're in. Whenever the category of the current row is different from the previous one, you print a new h1 for the new category and update the stored "current" category.
A: Generally speaking you have two options:
*
*Get all the data at once (like you are doing currently) then use PHP to either pre-sort the data by category. Then do your output looping over this array. So 1 query, 2 + n loops (where n is the number of categories).
*Get all your categories and then loop over those for output. In each iteration you will need to query all products for that loop. So 1 + n queries, 1 + n loops (where, again, n is the number of categories).
Option 2 might be more straightforward, but clearly there are more queries. In the end, it's your call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML cache version You know how if you use
<script type="text/javascript" src="urlhere.js?version=1.0.0"></script>
the browser caches the javascript file and updates it when you give it a new version?
Is there a way to do that with the HTML code?
Because I want the browser to cache the HTML, but then update when the code is changed.
Is that possible?
A: The best way to handle caching would be at the server level, specifying two tags:
*
*Expires
When the date specified has past, it tells the browser the content is no longer valid and it must be refreshed.
*Cache-Control
Without involving the date, it lets the browser know how it should handling caching for the page.
Note: The browser should already take care of this as it (in the background) already looks at the last modified date of the file. However, the above methods are valid ways of overriding (extending) this kind of detection in places where the last modified date may not necessarily reflect change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create variadic function? (Can take any number of arguments) I was wondering if there is a similar way to do this (C# definition) in Objective-C:
public void MyWorkingMethod (string Argument1, params int numbers)
It can be called like MyWorkingMethod("a") or MyWorkingMethod("b", 1, 2, 3).
I'm trying to implement the string.Format as C# does in Objective-c.
A: Note that there is already a stringWithFormat method that is very similar to string.Format found in the .NET Framework. That said, you can definitely have a variable number of arguments in an Objective-C method. See this link for details.
A: What exactly string.Format does? If you need a function, declare and define it as you'd do in C (including variadic cases):
void MyWorkingMethod (NSString *string, int numbers)
If it's related to formatting a string, have you checked NSString's stringWithFormat:? What about libc sprintf?
A: It should be something like
- (void) MyWorkingMethod : ( NSString * ) Argument1 secondInput:(NSArray *) numbers {
}
And you will call the function with
[self MyWorkingMethod:@"Hello World" secondInput:numbers];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ Swap string I am trying to create a non-recursive method to swap a c-style string. It throws an exception in the Swap method. Could not figure out the problem.
void Swap(char *a, char* b)
{
char temp;
temp = *a;
*a = *b;
*b = temp;
}
void Reverse_String(char * str, int length)
{
for(int i=0 ; i <= length/2; i++) //do till the middle
{
Swap(str+i, str+length - i);
}
}
EDIT: I know there are fancier ways to do this. But since I'm learning, would like to know the problem with the code.
A:
It throws an exception in the Swap method. Could not figure out the problem.
No it doesn't. Creating a temporary character and assigning characters can not possibly throw an exception. You might have an access violation, though, if your pointers don't point to blocks of memory you own.
The Reverse_String() function looks OK, assuming str points to at least length bytes of writable memory. There's not enough context in your question to extrapolate past that. I suspect you are passing invalid parameters. You'll need to show how you call Reverse_String() for us to determine if the call is valid or not.
If you are writing something like this:
char * str = "Foo";
Reverse_String(str, 3);
printf("Reversed: '%s'.\n", str);
Then you will definitely get an access violation, because str points to read-only memory. Try the following syntax instead:
char str[] = "Foo";
Reverse_String(str, 3);
printf("Reversed: '%s'.\n", str);
This will actually make a copy of the "Foo" string into a local buffer you can overwrite.
A: This answer refers to the comment by @user963018 made under @André Caron's answer (it's too long to be a comment).
char *str = "Foo";
The above declares a pointer to the first element of an array of char. The array is 4 characters long, 3 for F, o & o and 1 for a terminating NULL character. The array itself is stored in memory marked as read-only; which is why you were getting the access violation. In fact, in C++, your declaration is deprecated (it is allowed for backward compatibility to C) and your compiler should be warning you as such. If it isn't, try turning up the warning level. You should be using the following declaration:
const char *str = "Foo";
Now, the declaration indicates that str should not be used to modify whatever it is pointing to, and the compiler will complain if you attempt to do so.
char str[] = "Foo";
This declaration states that str is a array of 4 characters (including the NULL character). The difference here is that str is of type char[N] (where N == 4), not char *. However, str can decay to a pointer type if the context demands it, so you can pass it to the Swap function which expects a char *. Also, the memory containing Foo is no longer marked read-only, so you can modify it.
std::string str( "Foo" );
This declares an object of type std::string that contains the string "Foo". The memory that contains the string is dynamically allocated by the string object as required (some implementations may contain a small private buffer for small string optimization, but forget that for now). If you have string whose size may vary, or whose size you do not know at compile time, it is best to use std::string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL performance and optimization with multiple queries on a profile page, can they be reduced? I am working on social networking site, which has a profile page for each user.
The profile page contains:
*
*info about the user, avatar, hobbies & etc
*their videos and photos
*their friends
*their bookmarks
*videos they watched
At the moment i execute 14 different queries each time profile page is loaded, some of them listed below:
*
*check if the viewer is allowed to view the profile page
*get profile info
*get profile videos
*get profile photos
*get friend list
*get bookmark list
*get videos they watched
I would like to know best way to improve the performance and optimize my site, or can i reduce the number of queries i run.
Can MySQL handle this much load?
if it helps i am using innodb engine i needed faster updating speed as well realtionships.
thanks :)
A: If it ever does become a performance issue, here are a couple of easy things that will help:
*
*Cache the queries on the db server
*Cache the results of the queries in the web app
*Cache the entire profile page, or parts of it which change infrequently.
If you need to get more serious, you can create a new table in the database that stores the results of some of your queries all in one row, and regenerate it periodically. Then have your page select from that (then you have everything you need in one query).
But most importantly: what @Jason said. Chances are if performance does become an issue (because you turn into the next twitter or something), it'll be cheaper to throw hardware at the problem than to rewrite.
A: As long as they are short-running queries it's okay. Doing anything to optimize speed might give you, at best, some additional milliseconds. If it still bothers, you could do some caching.
Lookup also memcache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Exception-Raising Win32 API Wrapper? I've seen many wrappers for the Windows API (MFC, ATL, WTL, etc.) but none of them seem to use exception-handling -- you still have to check the error codes for most functions, which is easy to forget (or to omit due to laziness).
Is there any wrapper out there that actually throws exceptions instead of returning error codes?
A: The VCL raises exceptions when it encounters errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Positioning of DDL items? i have a dropDownList which gets its data from a database. Now after the data has bound, i programmatically add another listItem to the ddl, like so:
protected void ddlEffects_DataBound(object sender, EventArgs e)
{
DropDownList ddl = dwNewItem.FindControl("ddlEffects") as DropDownList;
ddl.Items.Add(new ListItem("","0")); //Adds an empty item so the user can select it and the item doesnt provide an effect
}
It all works, but the problem is that the newly added listItem appears at the bottom of the DDL. I want it to be the first item. I tried making the value 0, but its still at the bottom. Is there any way to put it at the top?
Thanks!
A: Check into the ddl.Items.Insert method that will allow you to insert items at a specific location.
Like this for example:
using (Entities db = new Entities())
{
ddlDocumentTypes.DataSource = (from q in db.zDocumentTypes where (q.Active == true) select q);
ddlDocumentTypes.DataValueField = "Code";
ddlDocumentTypes.DataTextField = "Description";
ddlDocumentTypes.DataBind();
ddlDocumentTypes.Items.Insert(0, "--Select--");
ddlDocumentTypes.Items[0].Value = "0";
}
Which using EF loads the DDL with items for the database, and then inserts at position zero a new item.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How make fancybox auto close when youtube video id done? How i can make fancybox auto close when youtube video ended?
A: This isn't as simple as it sounds:
*
*First determine if you are going to use the embed or iframe player.
*Follow the embed player API or iframe player API examples to initialize the API.
*Use the "onComplete" fancybox callback functon to set up the player once the popup is open.
*In the callback, make sure you add an onStateChange event listener so you can determine when the video has completed (the value of zero means the video has ended)
*Once you find that the video has ended, then use the $.fancybox.close method to close the popup
or, you could just let the user close the popup.
A: this is the full script with Fancybox-Youtube-Cookie-Autoclose-Autopopup just download the images that required in css put them in /fancybox folder in your root and replace with your video id. Really works fully tested...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/helpers/jquery.fancybox-media.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script type="text/javascript">
// detect mobile devices features
var isTouchSupported = 'ontouchstart' in window,
isTouchSupportedIE10 = navigator.userAgent.match(/Touch/i) != null;
function onPlayerReady(event) {
if (!(isTouchSupported || isTouchSupportedIE10)) {
// this is NOT a mobile device so autoplay
event.target.playVideo();
}
}
function onPlayerStateChange(event) {
if (event.data === 0) {
$.fancybox.close();
}
}
function onYouTubePlayerAPIReady() {
$(function() {
if ($.cookie('welcome_video')) {
// it hasn't been three days yet
} else {
// set cookie to expire in 3 days
$.cookie('welcome_video', 'true', { expires: 3});
$(document).ready(function () {
$.fancybox.open({
href: "https://www.youtube.com/embed/qm1RjPM9E-g", /*YOUR VIDEO ID*/
helpers: {
media: {
youtube: {
params: {
autoplay: 1,
rel: 0,
// controls: 0,
showinfo: 0,
autohide: 1,
}
}
},
buttons: {}
},
beforeShow: function () {
var id = $.fancybox.inner.find('iframe').attr('id');
var player = new YT.Player(id, {
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
}); // fancybox
}); // ready
} // cookie else ready
}); // function for cookie
} // youtube API ready
</script>
A: After looking around without any luck here is a solution I came up with
See what we do, watch a video here
<div style="display: none;">
<div id="player"></div>
</div>
<script src="http://www.youtube.com/player_api"></script>
<script>
$(document).ready(function () {
$("a.video_button").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 's19V_6Ay4No',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
$(document).ready(function () { parent.$.fancybox.close();});
}
}
</script>
A: Yes this is the right way to handle to fancybox or colorbox. Youtube Video API provides different states to handle this like unstarted=-1, ended=0, playing=1, paused=2, buffering=3, video cued=5
Getting or traping this state in fancybox jquery code block one can achieve this easily. Just visit this article with proper demo also.Visit here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: C++ Builder Flow Diagram Component? We want to draw large control flow diagrams in a C++ builder XE application being developed.
These diagrams will be generated programaticaly and displayed to the user in an interactive fashion (the user can scroll around the large flow diagram, select nodes and so on). The nodes must be capable of displaying a custom component (Like a TCanvas). Speed in displaying very large diagrams is important and extras like anti-aliasing are a good bonus.
Ideally we would like a native c++ builder/delphi VCL component for this but may fall back to an ActiveX controll or similar if we have to. We would require a source license to any component if its a commercial component/library but will happily consider free/open source components too.
Currently the following 2 components were found but are activex controls:
*
*MindFusion FlowChartX - http://www.mindfusion.eu/download.html - Currently this is the best I have found.
*Lassalle AddFlow ActiveX - http://www.lassalle.com/features.htm - This component is outdated (last version around 2007) and not as polished as the above option.
Can anybody recommend any suitable solutions for programatically creating and drawing interactive flow diagrams?
Many thanks in advance.
A: TMS Software Diagram Studio is native VCL and might do what you need. It can be found here for about € 95:
TMS Diagram Studio
Further more there is ExpressFlowChart from DevExpress for around: $ 90, it is also native VCL and can be found here:
ExpressFlowChart
I don't have any experience with either of these components, but have used components from both vendors before, and have generally liked the quality they have provided. DevExpress seems really professional in my opinion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Access Key from Entity that's instantiated but not stored [objectify] [@prepersist] I have written a @PrePersist method that's called before my User object is persisted. The purpose of the method is to make a kind of reservation for the User, so no one else can take his email address. So, when the User is about to be persisted, I say, "create an EmailReservation for user #xyz."
My trouble is in getting the #xyz when the User has not been persisted before. The id is null, but I cannot use DatastoreService.allocateIds because the Entity that will represent my User has already been made. I do have access to that Entity, but getKey() returns a key with a null id - it hasn't yet decided what its id will be.
So, I'm hoping one of the following is possible:
*
*Figure out the id that an Entity will have when it's persisted
*Give an Entity that's already been created a specific id before it's persisted.
Any ideas?
A: There's no way to know what ID an entity will have when it's persisted; the only way to do so is to use allocateIds.
You will have to either generate an ID before creating the User object, passing it in, or do your work after the entity has been written to the datastore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Deserialize xml to an array of objects? I am tryind to deserialize a xml file into an object[] - the object is a rectangle with the following fields
public class Rectangle : IXmlSerializable
{
public string Id { get; set; }
public Point TopLeft { get; set; }
public Point BottomRight { get; set; }
public RgbColor Color { get; set; }
}
I created several rectangles, saved them into an array and managed to serialize them into the xml i get the following syntax:
<?xml version="1.0" encoding="utf-8" ?>
- <Rectangles>
- <Rectangle>
<ID>First one</ID>
- <TopLeft>
<X>0.06</X>
<Y>0.4</Y>
</TopLeft>
- <BottomRight>
<X>0.12</X>
<Y>0.13</Y>
</BottomRight>
- <RGB_Color>
<Blue>5</Blue>
<Red>205</Red>
<Green>60</Green>
</RGB_Color>
</Rectangle>
-
Now i want to deserialize the rectangle objects back into a new rectangle[]
how should i do it?
XmlSerializer mySerializer = new XmlSerializer(typeof(Rectangle));
FileStream myFileStream = new FileStream("rectangle.xml", FileMode.Open);
Rectangle[] r = new Rectangle[] {};
Rectangle rec;
for (int i = 0; i < 3; i++)
{
r[i] = (Rectangle) mySerializer.Deserialize(myFileStream);
}
i get a InvalidOperationException - {"There is an error in XML document (1, 40)."}
what am i doing wrong?
Thank you
A: If your XML document is valid, you should be able to use this codes to deserialize it:
XmlSerializer mySerializer = new XmlSerializer( typeof( Rectangle[] ), new XmlRootAttribute( "Rectangles" ) );
using ( FileStream myFileStream = new FileStream( "rectangle.xml", FileMode.Open ) )
{
Rectangle[] r;
r = ( Rectangle[] ) mySerializer.Deserialize( myFileStream );
}
A: Your XML is missing a closing </Rectangles> element. That might be the problem!
A: The problem is about root element name.
However, Deserialize( ) only knows how to look for an element named Rectangles.
But in your case element named "Rectangle". that is all the InvalidOperationException is telling you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Smarty Error: media_player.php is not readable I copied a website from rareculture.net to my local machine so that I can work with it. The site uses CS Cart, which uses Smarty, and I am getting the following error:
( ! ) Warning: Smarty error: http://localhost/cscart/skins/projection/customer/media_player.php is not readable in C:\wamp\www\cscart\lib\templater\Smarty.class.php on line 1095
Call Stack
# Time Memory Function Location
1 0.0006 676392 {main}( ) ..\index.php:0
2 0.1292 14141136 fn_dispatch( ) ..\index.php:28
3 0.1890 16676848 Templater->display( ) ..\fn.control.php:505
4 0.1891 16677472 Smarty->display( ) ..\class.templater.php:122
5 0.1891 16677616 Smarty->fetch( ) ..\Smarty.class.php:1108
6 0.1920 17133376 include( 'C:\wamp\www\cscart\var\compiled\customer\%%45^45E^45E480CD%%index.tpl.php' ) ..\Smarty.class.php:1258
7 0.2102 17289304 Templater->_smarty_include( ) ..\%%45^45E^45E480CD%%index.tpl.php:394
8 0.2115 17454696 include( 'C:\wamp\www\cscart\var\compiled\customer\%%72^72D^72DAF6E8%%main.tpl.php' ) ..\class.templater.php:88
9 0.2378 17828056 smarty_core_smarty_include_php( ) ..\%%72^72D^72DAF6E8%%main.tpl.php:141
10 0.2384 17852528 smarty_core_get_php_resource( ) ..\core.smarty_include_php.php:25
11 0.2397 17874168 Smarty->trigger_error( ) ..\core.get_php_resource.php:66
12 0.2397 17874432 trigger_error ( ) ..\Smarty.class.php:1095
At first, the path was not right to media_player.php for my local server, and it was giving me 3 errors. After changing the path to main.tpl here:
<div id="homepage-meida">
{include_php file='http://localhost/cscart/skins/projection/customer/media_player.php}
</div><!-- #homepage-media -->
I got just the one error. I tried changing the permissions in Windows 7, giving Everyone full access to both the file and the containing folder, and it didn't change anything.
Can anyone point me in the right direction? Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find account GUID, and Select it back using Object GUID
I am trying to select a unique identifiers for accounts from Active Directory. I found that "objectguid" attribute do identify a user uniquely, but my problem is that I don't know how to convert the retrieved value into a readable format. And then be able to select a user back using this value.
I am using spring ldap libraries, right now the "objectguid" return a char[] (15 element)
So, Does any one knows any thing that can help?
(Note, I can't use SAM Name attribute)
Thanks,
A: See here. It appears there are two string formats: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, which you can get via new BigInteger(0, (byte[])attr.get()).toString(16), and XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, which is the same thing plus punctuation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why aren't the arguments to File.new symbols instead of strings? I was wondering why the people who wrote the File library decided to make the arguments that determine what mode the file is opened in strings instead of symbols.
For example, this is how it is now:
f = File.new('file', 'rw')
But wouldn't it be a better design to do
f = File.new('file', :rw)
or even
f = File.new(:file, :rw)
for example? This seems to be the perfect place to use them since the argument definitely doesn't need to be mutable.
I am interested in knowing why it came out this way.
Update: I just got done reading a related question about symbols vs. strings, and I think the consensus was that symbols are just not as well known as strings, and everyone is used to using strings to index hash tables anyway. However, I don't think it would be valid for the designers of Ruby's standard library to plead ignorance on the subject of symbols, so I don't think that's the reason.
A: I'm no expert in the history of ruby, but you really have three options when you want parameters to a method: strings, symbols, and static classes.
For example, exception handling. Each exception is actually a type of class Exception.
ArgumentError.is_a? Class
=> True
So you could have each permission for the stream be it's own class. But that would require even more classes to be generated for the system.
The thing about symbols is they are never deleted. Every symbol you generate is preserved indefinitely; it's why using the method '.to_sym' lightly is discouraged. It leads to memory leaks.
Strings are just easier to manipulate. If you got the input mode from the user, you would need a '.to_sym' somewhere in your code, or at the very least, a large switch statement. With a string, you can just pass the user input directly to the method (if you were so trusting, of course).
Also, in C, you pass a character to the file i/o method. There are no Chars in ruby, just strings. Seeing as how ruby is built on C, that could be where it comes from.
A: It is simply a relic from previous languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Invoke Java from C++ I am trying to invoke the Java Virtual machine from C++ following the example found here:
Basically I have a small Java program:
public class TestJNIInvoke
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}
Then I have a C++ program that I want to create a JVM and call the TestJNIInvoke class:
#include <jni.h>
#include <cstdlib>
#define PATH_SEPARATOR ';' /* define it to be ':' on Solaris */
#define USER_CLASSPATH "." /* where Prog.class is */
using namespace std;
int main() {
JNIEnv *env;
JavaVM *jvm;
jint res;
jclass cls;
jmethodID mid;
jstring jstr;
jclass stringClass;
jobjectArray args;
#ifdef JNI_VERSION_1_2
JavaVMInitArgs vm_args;
JavaVMOption options[1];
options[0].optionString =
"-Djava.class.path=" USER_CLASSPATH;
vm_args.version = 0x00010002;
vm_args.options = options;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
#else
JDK1_1InitArgs vm_args;
char classpath[1024];
vm_args.version = 0x00010001;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
/* Append USER_CLASSPATH to the default system class path */
sprintf(classpath, "%s%c%s",
vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH);
vm_args.classpath = classpath;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, &env, &vm_args);
#endif /* JNI_VERSION_1_2 */
if (res < 0) {
fprintf(stderr, "Can't create Java VM\n");
exit(1);
}
cls = (*env)->FindClass(env, "TestJNIInvoke");
if (cls == NULL) {
goto destroy;
}
mid = (*env)->GetStaticMethodID(env, cls, "main",
"([Ljava/lang/String;)V");
if (mid == NULL) {
goto destroy;
}
jstr = (*env)->NewStringUTF(env, " from CPP!");
if (jstr == NULL) {
goto destroy;
}
stringClass = (*env)->FindClass(env, "java/lang/String");
args = (*env)->NewObjectArray(env, 1, stringClass, jstr);
if (args == NULL) {
goto destroy;
}
(*env)->CallStaticVoidMethod(env, cls, mid, args);
destroy:
if ((*env)->ExceptionOccurred(env)) {
(*env)->ExceptionDescribe(env);
}
(*jvm)->DestroyJavaVM(jvm);
}
But When I try to compile the C++ program I get this error:
c:\java\JNI> g++ -I"c:\Program Files\Java\jdk1.7.0\include"-I"c:\ProgramFiles\Java\jdk1.7.0\include\win32" -c TestJNIInvoke.cpp
TestJNIInvoke.cpp: In function 'int main()':
TestJNIInvoke.cpp:20:31: warning: deprecated conversion from string constant to
'char*'
TestJNIInvoke.cpp:44:18: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:49:18: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:54:19: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:58:26: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:59:19: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:63:12: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:66:16: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:67:16: error: base operand of '->' has non-pointer type 'JNIEn
v'
TestJNIInvoke.cpp:69:12: error: base operand of '->' has non-pointer type 'JavaVM'
Any ideas?
Thanks
A: Even though you include the same header file, the Java Native Interface uses two different interfaces for C and C++.
In C++, it's:
jclass cls = env->FindClass("java/lang/String");
instead of (for C):
jclass cls = (*env)->FindClass(env, "java/lang/String");
So the C function call that requires env in two places becomes a convenient member function call in C++.
This is mentioned in the Native Method Arguments section of the Java Native Interface 6.0 Specification.
A: My guess would be that you're attempting to compile against the win32 headers given the command line you're using. Have you tried -I"c:\ProgramFiles\Java\jdk1.7.0\include\solaris instead (assuming that's your platform based on the comment higher up in the source).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Can the ARM version of Windows 8 only run Metro (WinRt) style apps? See also: Is there any way to write a WinRt (Metro) app that will also work on Windows 7 and Vista?
I am trying to understand how to target both Windows 8 on Arm and Windows 7, given that Windows 7 cannot run WinRT apps. And as I understand it, apps can only be installed on ARM version of Windows 8 from the App Store.
So can Windows 8 on the Arm run none WinRT apps?
A: The definitive answer is out now. There will be a desktop, but you will not be able to install desktop apps. "WOA does not support running, emulating, or porting existing x86/64 desktop apps." All apps will come from the store and will have to abide by the Metro style app guidelines.
The only desktop apps appear to be Office (which seems to ship with the OS) and built-in apps like the control panel, Explorer, IE, etc. Everything else will be a new Metro-style app written against the Windows Runtime.
See this Building Windows 8 blog post for details.
A: "No legacy apps" is not the same as "no Desktop apps" though.
Nothing I've seen suggests that there won't be a regular Win32 with COM, IE, MSHTA, etc. on ARM along with an Explorer Desktop.
You may simply need to recompile C++ or .Net after some tweaking or "retargeting." Things like HTAs may even port with close to zero effort as long as they don't use any custom COM libraries. I'm surprised anyone ever expected any x86 code to run on ARM, even under some sort of WOW emulation. Microsoft has been pretty clear about that.
Whether it makes any sense to do much of this (desktop apps on ARM) is another matter, even if you can. The ARM-based devices are likely to be quite resource-constrained, which is the purpose in having them in the first place: cheap and portable.
A: Microsoft has made no statement about whether or not desktop apps will be supported on Arm processors. They have shown Microsoft Office running, but have not said whether that will be supported on the final platform.
For now the only statements have been about Metro style apps and those will be supported written in any language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Android: Adjusting EditText font size to fit text to one line I am making an app that has two EditText views, txtOne which is used for input, and txtTwo which is used for output. txtOne is editable, and txtTwo is not.
I am looking for a simple way to scale the font size of the text in these two views so that it always fits within the view without wrapping to a new line.
I have found a few implementations of this using custom views extending TextView, but they aren't fit for an EditText view, or use android.graphics.Paint, which is not what I am looking for.
Is there any way to check to see when text in an EditText view is wrapping? If so, then it would be easy enough to do something like:
if(txtOne.isWrappingText()) {
txtOne.setTextSize(txtOne.getTextSize() - 2);
}
Does anyone know of any way to detect this or an alternative solution?
A: I deleted my post
Basically the suggested code contained a TextWatcher for the EditText, this helped to answer the question. But the code itself was just wrong (I tested it meanwhile).
I suggest to read this question and answers because they adress the very same issue...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Self hosted WCF Service not working when i type url in browser? I'm new to WCF. I have made a simple self hosted service and added app.config but when I type address in the browser it is not showing me the service page that we get when we create our service http://localhost:8067/WCFService it is not displaying the service as it shows when we run service.
But when I try to add base service in public static void main instead of app.config it works fine m not getting yy?? Can anyone please help me?
Following is the app.config file manually added:
<configuration>
<system.serviceModel>
<services>
<service name="SelfHostedWCFService.WCFService">
<endpoint
address="http://localhost:8067/WCFService"
binding="wsHttpBinding"
contract="SelfHostedWCFService.IWCFService">
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
Following is the Program.cs:
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(SelfHostedWCFService.WCFService));
host.Open();
Console.WriteLine("Server is Running...............");
Console.ReadLine();
}
Following is the interface file manually added:
namespace SelfHostedWCFService
{
[ServiceContract]
interface IWCFService
{
[OperationContract]
int Add(int a, int b);
[OperationContract]
int Sub(int a, int b);
[OperationContract]
int Mul(int a, int b);
}
}
Following is the service.cs file manually added:
namespace SelfHostedWCFService
{
class WCFService:IWCFService
{
public int Add(int a, int b) { return (a + b); }
public int Sub(int a, int b) { return (a - b); }
public int Mul(int a, int b) { return (a * b); }
}
}
Is something wrong with my app.config or some other concept??
A: Everything seems ok at first glance - are you sure the service isn't running??
Without any metadata being published, you cannot test the service using the WCF Test Client, nor can you generate a client-side proxy for it....
So I would recommend adding service metadata publishing to your service, and doing so, I was able to test that code of yours and it works just flawlessly.
To add metadata, change your config to:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Metadata">
<serviceMetadata />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="SelfHostedWCFService.WCFService" behaviorConfiguration="Metadata">
<endpoint
address="http://localhost:8067/WCFService"
binding="wsHttpBinding"
contract="SelfHostedWCFService.IWCFService" />
<endpoint address="http://localhost:8067/WCFService/mex"
binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</configuration>
Even with this config, you won't see any service page when navigation to the URL - but the service is up and running - just use the WCF Test Client and see for yourself!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How is rate_limit enforced in Celery? I'm running a Django website where I use Celery to implement preventive caching - that is, I calculate and cache results even before they are requested by the user.
However, one of my Celery tasks could, in some situation, be called a lot (I'd say sightly quicker than it completes on average, actually). I'd like to rate_limit it so that it doesn't consume a lot of resources when it's actually not that useful.
However, I'd like first to understand how Celery's celery.task.base.Task.rate_limit attribute is enforced. Are tasks refused? Are they delayed and executed later?
Thanks in advance!
A: Rate limited tasks are never dropped, they are queued internally in the worker so that they execute as soon as they are allowed to run.
The token bucket algorithm does not specify anything about dropping packets (it is an option, but Celery does not do that).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how to get the first and last days of a given month I wish to rewrite a mysql query which use month() and year() functions to display all the posts from a certain month which goes to my function as a 'Y-m-d' parameter format, but I don't know how can I get the last day of the given month date.
$query_date = '2010-02-04';
list($y, $m, $d) = explode('-', $query_date);
$first_day = $y . '-' . $m . '-01';
A: cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.
A: // First date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));
echo '<br />';
// Last date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m')+1, 0, date('Y')));
A: $month = 10; // october
$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');
A: I know this question has a good answer with 't', but thought I would add another solution.
$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));
A: Try this , if you are using PHP 5.3+, in php
$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');
For finding next month last date, modify as follows,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
and so on..
A: Basically:
$lastDate = date("Y-m-t", strtotime($query_d));
Date t parameter return days number in current month.
A: You might want to look at the strtotime and date functions.
<?php
$query_date = '2010-02-04';
// First day of the month.
echo date('Y-m-01', strtotime($query_date));
// Last day of the month.
echo date('Y-m-t', strtotime($query_date));
A: Print only current month week:
function my_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
$start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
if($currentWeek==1)
{$start_date = date('Y-m-01', strtotime($date));}
else if($currentWeek==5)
{$end_date = date('Y-m-t', strtotime($date));}
else
{}
return array($start_date, $end_date );
}
$date_range=list($start_date, $end_date) = my_week_range($new_fdate);
A: ## Get Current Month's First Date And Last Date
echo "Today Date: ". $query_date = date('d-m-Y');
echo "<br> First day of the month: ". date('01-m-Y', strtotime($query_date));
echo "<br> Last day of the month: ". date('t-m-Y', strtotime($query_date));
A: In case of name of month this code will work
echo $first = date("Y-m-01", strtotime("January"));
echo $last = date("Y-m-t", strtotime("January"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "80"
} |
Q: Increase numbers in python until max I want to have python spit out a bunch of numbers for me.
example:
>>>date = 1940
>>>date += 1
>>>print str(date)
1941
>>>
but i want to loop that and output all numbers from 1940-2004
A: Use the range function.
for i in range(1940,2005):
print i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Eliminate redundant letters in string? (e.g. gooooooooood -> good) I'm trying to set up some sample data for a Naive Bayesian Classifier for Twitter.
One of the post-processing of the tweets I'd like to do is to remove unnecessary repeat characters.
For example, one of the tweets reads: Twizzlers. mmmmm goooooooooooood!
I'd like to reduce the number of w's down to just two. Why two? That's what the article I'm following did. Any individual word that is less than 2 characters is discarded (see mmmmm above). And as far as gooooooood, I would imagine double letters are the most common to be uber repeated.
So, that said, what's the fastest way (in terms of execution time) to reduce words such as gooooooooood to simply good?
[Edit]
I'll be processing 800,000 tweets in this app, hence the requirement for fastest execution
[/Edit]
[Edit2]
I just ran some simple benchmarking based on elapsed time to iterate through 1000 records & save to a text file. I repeated this iteration 100 times on each method. The average results are here:
Method 1: 386 ms [LINQ - answer was deleted]
Method 2: 407 ms [Regex]
Method 3: 303 ms [StringBuilder]
Method 4: 301 ms [StringBuilder part 2]
Method 1: LINQ (answer was apparently deleted)
static string doIt(string a)
{
var l = a.Select((p, i) => new { ch = p, index = i }).
Where(p => (p.index < a.Length - 2) && (a[p.index + 1] == p.ch) && (a[p.index + 2] == p.ch))
.Select(p => p.index).ToList();
l.Sort();
l.Reverse();
l.ForEach(i => a = a.Remove(i, 1));
return a;
}
METHOD 2:
Regex.Replace(tweet,@"(\S)\1{2,}","$1$1");
Method 3:
static string StringB(string s)
{
string input = s;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (i < 2 || input[i] != input[i - 1] || input[i] != input[i - 2])
sb.Append(input[i]);
}
string output = sb.ToString();
return output;
}
Method 4:
static string sb2(string s)
{
string input = s;
var sb = new StringBuilder(input);
char p2 = '\0';
char p1 = '\0';
int pos = 0, len = sb.Length;
while (pos < len)
{
if (p2 == p1) for (; pos < len && (sb[pos] == p2); len--)
sb.Remove(pos, 1);
if (pos < len)
{
p2 = p1;
p1 = sb[pos];
pos++;
}
}
return sb.ToString();
}
A: This is also (easily) doable via a regular expression:
var re = @"((.)\2)\2*";
Regex.Replace("god", re, "$1") // god
Regex.Replace("good", re, "$1") // good
Regex.Replace("gooood", re, "$1") // good
Is it faster than the other approaches? Well, that's for the benchmarks ;-) Regular expressions can be quite efficient in non-degenerate backtracking situations. The above may need to be altered (this will also match spaces for instance), but it's a small example.
Happy coding.
A: Regexen look to be the simplest. Simple proof of concept in the REPL:
using System.Text.RegularExpressions;
var regex = new Regex(@"(\S)\1{2,}"); // or @"([aeiouy])\1{2,}" etc?
regex.Replace("mmmmm gooood griieeeeefff", "$1$1");
-->
"mm good griieeff"
For raw performance, use something more like this: see it live on https://ideone.com/uWG68
using System;
using System.Text;
class Program
{
public static void Main(string[] args)
{
string input = "mmmm gooood griiiiiiiiiieeeeeeefffff";
var sb = new StringBuilder(input);
char p2 = '\0';
char p1 = '\0';
int pos = 0, len=sb.Length;
while (pos < len)
{
if (p2==p1) for (; pos<len && (sb[pos]==p2); len--)
sb.Remove(pos, 1);
if (pos<len)
{
p2=p1;
p1=sb[pos];
pos++;
}
}
Console.WriteLine(sb);
}
}
A: I agree with the comments that this will not work in the general case, especially in "Twitter speak". Having said that the rules you mentioned are simple - eliminate every character that is the same as the previous two characters:
string input = "goooooooooooood";
StringBuilder sb = new StringBuilder(input.Length);
sb.Append(input.Substring(0, 2));
for (int i = 2; i < input.Length; i++)
{
if (input[i] != input[i - 1] || input[i] != input[i - 2])
sb.Append(input[i]);
}
string output = sb.ToString();
A: I would recommend looking into NLP solutions rather than C#/regex. In that world, python is preferred. See NLTK. I would recommend Nodebox Linguistics which gives you spelling corrections. You can even stem words and even go down to the infinitive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to check if a directory exists in Objective-C I guess this is a beginner's problem, but I was trying to check if a directory exists in my Documents folder on the iPhone. I read the documentation and came up with this code which unfortunately crashed with EXC_BAD_ACCESS in the BOOL fileExists line:
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:YES];
if (fileExists)
{
NSLog(@"Folder already exists...");
}
}
I don't understand what I've done wrong? It looks all perfect to me and it certainly complies with the docs, not? Any revelations as to where I went wrong would be highly appreciated! Thanks.
UPDATED:
Still not working...
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL isDir;
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
if (fileExists)
{
if (isDir) {
NSLog(@"Folder already exists...");
}
}
}
A: Take a look in the documentation for this method signature:
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory
You need a pointer to a BOOL var as argument, not a BOOL itself. NSFileManager will record if the file is a directory or not in that variable. For example:
BOOL isDir;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDir];
if (exists) {
/* file exists */
if (isDir) {
/* file is a directory */
}
}
A: I have a Utility singleton class that I use for things like this. Since I can’t update my database if it remains in Documents, I copy my .sqlite files from Documents to /Library/Private Documents using this code. The first method finds the Library. The second creates the Private Documents folder if it doesn’t exist and returns the location as a string. The second method uses the same file manager method that @wzboson used.
+ (NSString *)applicationLibraryDirectory {
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
}
+ (NSString *)applicationLibraryPrivateDocumentsDirectory {
NSError *error;
NSString *PrivateDocumentsDirectory = [[self applicationLibraryDirectory] stringByAppendingPathComponent:@"Private Documents"];
BOOL isDir;
if (! [[NSFileManager defaultManager] fileExistsAtPath:PrivateDocumentsDirectory isDirectory:&isDir]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:PrivateDocumentsDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error]) {
NSLog(@"Create directory error: %@", error);
}
}
return PrivateDocumentsDirectory;
}
I use it like this in my persistent store coordinator initialization. The same principal applies to any files though.
NSString *libraryDirectory = [Utilities applicationLibraryPrivateDocumentsDirectory];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:sqliteName];
NSString *destinationPath = [libraryDirectory stringByAppendingPathComponent:sqliteName];
A: Just in case somebody needs a getter, that creates a folder in Documents, if it doesn't exist:
- (NSString *)folderPath
{
if (! _folderPath) {
NSString *folderName = @"YourFolderName";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [documentPaths objectAtIndex:0];
_folderPath = [documentsDirectoryPath stringByAppendingPathComponent:folderName];
// if folder doesn't exist, create it
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
if (! [fileManager fileExistsAtPath:_folderPath isDirectory:&isDir]) {
BOOL success = [fileManager createDirectoryAtPath:_folderPath withIntermediateDirectories:NO attributes:nil error:&error];
if (!success || error) {
NSLog(@"Error: %@", [error localizedDescription]);
}
NSAssert(success, @"Failed to create folder at path:%@", _folderPath);
}
}
return _folderPath;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Calling a class's constant in another class's variable I was wondering if there is any possibility in PHP to do following;
<?php
class boo {
static public $myVariable;
public function __construct ($variable) {
self::$myVariable = $variable;
}
}
class foo {
public $firstVar;
public $secondVar;
public $anotherClass;
public function __construct($configArray) {
$this->firstVar = $configArray['firstVal'];
$this->secondVar= $configArray['secondVar'];
$this->anotherClass= new boo($configArray['thirdVal']);
}
}
$classFoo = new foo (array('firstVal'=>'1st Value', 'secondVar'=>'2nd Value', 'thirdVal'=>'Hello World',));
echo $classFoo->anotherClass::$myVariable;
?>
Expected OUTPUT : Hello World
I am getting following error; Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
I Googled and it is related to colon (double dots) in $classFoo->anotherClass::$myVariable
I wouldn't like to go all the trouble to change my other classes. Is there anyway around this problem?
Thank you for your help in advance.
P.S. I just didn't want to lose few hours on this to find a way around. I already spent yesterday 2.5 hours to change almost whole Jquery because customer wanted a change and today in the morning I was asked to take the changes back because they didn't want to use it (they changed their mind). I am just trying to avoid big changes right now.
A: You need to do:
$anotherClass = $classFoo->anotherClass;
echo $anotherClass::$myVariable;
Expanding expressions to class names/objects for static calls/constants is not supported (but expanding variables, as shown above, is).
A: If you do not care about memory and execution speed, this is correct.
It seems that reference would be better:
$classRef = &$classFoo->anotherClass;
echo $classRef;
Works for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: recording dll APIs and then mimicking it Is there some tool that can record APIs in some c++ dll , and then playback them .
At our costumer site we have a machine with some vendor software that exposes it's functionality .
We wanted to record that dll and then mimic it back at the office .
Any idea how We can do that ?
Thanks for help.
A: You can start with Detours or its open-source equivalent EasyHook. Your hook function can log the activity, and then back at the office you can write a replacement DLL that replays the activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Value of type cannot be converted to I am sure i am doing something terribly wrong, but i should better ask the experts.
At the third line i get the error Value of type <anonymous type> cannot be converted to <anonymous type>
Dim Query = (From c In Db.web Select New With {.AA = c.AA}).ToList
Dim v = New With {.Amount = 108}
Query.Add(v)
What am i missing here?
A: Because you have named your fields differently (and maybe it has different type as well, I don't know, cause I don't know what type c.AA is), compiler has created different type for v, so you have 2 anonymous classes, with different fields (even if they have same type, but their name differs) and they are not compatible with each other.
I don't know VB.Net well, but something like this:
Dim Query = (From c In Db.web Select New With {.Amount = CInt(c.AA)}).ToList
Dim v = New With {.Amount = 108}
Query.Add(v)
Should solve the problem, at least works in C#.
A: Anonymous type identity is based not just on the types of the members, but on their names as well. So these two objects are of different types, even though to human eyes they have the 'same' structure:
Dim a = New With { .Name = "Bob" }
Dim b = New With { .Moniker = "Robert" }
So even if c.AA is an Integer, that's not enough for Query and v to be type-compatible.
Obviously your code is distilled from your real problem, so I can't say exactly what you should be doing instead, but perhaps using a named rather than an anonymous type will solve your problem.
This is documented in the VB.NET Spec (from eg version 9.0 here), section 11.10.4 "Anonymous Object-Creation Expressions" (my emphases) :
If two anonymous class creation expressions occur within the same
method and yield the same resulting shape—if the property order,
property names, and property types all match—they will both refer to
the same anonymous class.
Annotation
It is possible that a compiler may choose to unify anonymous types further, such as at the assembly level, but this cannot be relied upon at this time.
By contrast to the annotation, I believe that for C#, the compiler does guarantee anonymous type identity across an assembly when everything matches.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mod_rewrite directory requests I am trying to do this:
example.com/directory/song.mp3 -> Unchanged
example.com/directory/ -> example.com/?dir=directory%2F
example.com/ -> Unchanged
example.com/index.php -> Unchanged
Basically, if a user requests any directory other than root, I need it rewritten, not redirected, to index.php?dir=< path with slashes changed to %2F>
I want the user to still see example.com/path/to/stuff in their browser, but the request to be rewritten serverside.
example.com/songs/stuff -> example.com/?dir=songs%2Fstuff%2F
I hope I am clear about what I am looking for.
A: try this:
RewriteRule ([^/]+/.*) /index.php?dir=$1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find/remove input in form by value? How to find/remove input element in form by value ?
A: You can use filter to cover all the bases:
var matches = $('input').filter(function() { return this.value == 'what you want' });
matches.remove(); // If you want to remove them of course.
An attribute selector only sees things that have the value attribute set in the DOM so that won't see an <input> that has been updated with a val(x) call, using a filter will see things that have been updated with .val(x).
For example: http://jsfiddle.net/ambiguous/RVWu6/
A: Making an initial guess at what you're trying to accomplish, you should probably take a look at this question:
How can I select a hidden field by value?
The suggestion there is $('input[value="Whatever"]')
From there you can use the jQuery remove function: http://api.jquery.com/remove/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I test database transaction logic? I often find error handling is one of the hardest things to test. Thankfully with dependency injection and mocking frameworks it's getting much easier.
However, I'm still having trouble testing data access objects, especially the error handling and rollback aspects. Suppose I have a two queries in a DAO method like so:
INSERT INTO A(AID, AVAL)
VALUES (1, 'TEST');
INSERT INTO B(AID, BVAL)
VALUES (1, 'TEST');
And I want transaction logic, implemented in Spring's transaction management, such that if the insert into B fails the insert into A is rolled back.
How can I test this?
A: Have two DAOs (both interface based, of course):
public interface GenericDao<T, K extends Serializable> {
public T find(K key);
public List<T> find();
public K save(T value);
public void update(T value);
public void delete(T value);
}
The GenericDao<B> is mocked to throw a RuntimeException from its save method. You should see the Spring transaction manager roll back the transaction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Managing Form's code in VB.net Whats the best way to organize code responsible for Form's content.
In my case, there is a DataGridView and list, next to it, with a few options available (projects, managers, employees, etc...). Choosing any list's element fills DataGrid with proper data from database.
Now, GridFill functions + handling of all add/delete/edit buttons of each list element gives quite a code in the Form's source, which bothers me a bit.
How to split it then to avoid problems in the future? While googling, I've seen some advices to use partial classes, modules or just classes. Moving all functions relating the Projects, Managers, ... , to own separate class sounds like a nice idea but then comes the question how to pass all necessary data to the class functions. Is passing the reference of the whole form a good idea?
A: If you're using Winforms, take a look at the MVP (Model, View, Presenter) pattern, which helps separate code related to data, business logic and user interface.
This question could also help as the answers provide quite a few interesting links on the subject.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: fnmatch how exactly do you implement the match any chars in seq pattern so i have a os.walk code
search = self.search.get_text()
top = '/home/bludiescript/tv-shows'
for dirpath, dirnames, filenames in os.walk(top):
for filename in filenames:
if fnmatch.fnmatch(filename, search)
print os.path.join([dirpath, filename])
on python docs it shows you can match any seq of chars with [seq] pattern but no matter how i try to implement that it give so kind of error or no results at all.
so what would be the correct implementation to match the seq of cars in search so it will print out the file or files that match
implementations i tried
if fnmatch.fnmatch(filename, [search]) error i got was typeerror unhasable type : 'list'
if fnmatch.fnmatch[filename, search] error i got was typeerror fnmatch function is not subscriptable
if fnmatch.fnmatch([filename, search]) error typeerror fnmatch takes two arguments 1 given
if fnmatch.fnmatch([filename], search) error typeerror expected string or buffer
if fnmatch.fnmatch([search], filename) error typeerror expected string or buffer
if fnmatch.fnmatch(filename, search, [seq]) error nameerror global name seq not defined
if fnmatch.fnmatch(filename, '[search]')
no errors but did not produce any results
search values
hello, mkv, merry 1, 2, 3, 4, 5, 6, 7, etc...
A: fnmatch implements the Unix shell wildcard syntax. So whatever you can type in an ls command (for example) will work:
>>> fnmatch.fnmatch("qxx", "[a-z]xx")
True
>>> fnmatch.fnmatch("abc", "a??")
True
>>> fnmatch.fnmatch("abcdef", "a*f")
True
>>> fnmatch.fnmatch("abcdef", "a*[f-k]")
True
Keep in mind, fnmatch is purely a string matching operation. If you find it more convenient to use a different pattern style, for example, regexes, then simply use regex operations to match your filenames.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to check if a UID exists in an ACL in Linux? I need to write a program, part of which involves checking if the userid of the person executing the program exists in the ACL file of a file which the program uses. That is, this program writes into the file and only users whose ID and privileges are entered in the ACL are allowed to do so. How can the program check this? I know that I need to use the getresid function to get the RUID of the executing process, but how do I check this value against all the values stored in the ACL? Please help me!
A: Traditionally, linux programs don't do interpretive access control very much. There are two cases.
Case 1, the simple case. A file has an acl (or just modes). Some user runs a program under his user/group set, and the kernel either allows or denies based on the modes/acl. All done.
Case 2, the hard case. A program runs as root, but wishes to operate on behalf of some other user. So, it calls setuid/setgid to 'become' that user, then performs the operation (like opening a file), and then calls to restore itself to root-itude afterwards.
However, based on your comments to chown's answer, I think that you are just in case 1. The user foo runs the program, so the kernel does all the work for you.
A: If I misunderstood the question I apologize, but hopefully you will find this helpful:
Exceprt from some acl documentation:
The following functions retrieve and manipulate ACL entries:
acl_copy_entry()
acl_create_entry()
acl_delete_entry()
acl_first_entry()
acl_get_entry()
The following functions retrieve and manipulate fields in an ACL entry:
acl_add_perm()
acl_clear_perm()
alc_delete_perm()
acl_get_permset()
acl_get_qualifier()
acl_get_tag_type()
acl_set_permset()
acl_set_qualifier()
acl_set_tag_type()
...
ACL Entries
An ACL entry consists of the following fields:
Tag type (defined in the acl.h header file):
ACL_USER_OBJ - The owning user entry.
ACL_GROUP_OBJ - The owning group entry.
ACL_USER - An entry for other users.
ACL_GROUP - An entry for other groups.
ACL_OTHER_OBJ - The entry for all users and groups that are not included in another entry.
Tag qualifier - The qualifier value for a ACL_USER entry is a user ID.
The qualifier value for a ACL_GROUP entry is a group ID.
The qualifier value for any of the *_OBJ entries is NULL.
From acl_update.c:
/*
Find the the ACL entry in 'acl' corresponding to the tag type and
qualifier in 'tag' and 'id'. Return the matching entry, or NULL
if no entry was found. */
static acl_entry_t
findEntry(acl_t acl, acl_tag_t tag, id_t qaul)
{
acl_entry_t entry;
acl_tag_t entryTag;
uid_t *uidp;
gid_t *gidp;
int ent, s;
for (ent = ACL_FIRST_ENTRY; ; ent = ACL_NEXT_ENTRY) {
s = acl_get_entry(acl, ent, &entry);
if (s == -1)
errExit("acl_get_entry");
if (s == 0)
return NULL;
if (acl_get_tag_type(entry, &entryTag) == -1)
errExit("acl_get_tag_type");
if (tag == entryTag) {
if (tag == ACL_USER) {
uidp = acl_get_qualifier(entry);
if (uidp == NULL)
errExit("acl_get_qualifier");
if (qaul == *uidp) {
if (acl_free(uidp) == -1)
errExit("acl_free");
return entry;
} else {
if (acl_free(uidp) == -1)
errExit("acl_free");
}
} else if (tag == ACL_GROUP) {
gidp = acl_get_qualifier(entry);
if (gidp == NULL)
errExit("acl_get_qualifier");
if (qaul == *gidp) {
if (acl_free(gidp) == -1)
errExit("acl_free");
return entry;
} else {
if (acl_free(gidp) == -1)
errExit("acl_free");
}
} else {
return entry;
}
}
}
}
I dont think u need to check the ACL of a specific file, but if I am wrong, here is some info to do so:
$ getfacl myFile
# file: myFile
# owner: jon
# group: people
user::rwx
user:foo:rwx
group::rwx
mask::rwx
other::---
then to get a uid from the name (untested but should be close):
$ grep /etc/passwd `getfacl myFile | grep owner | split -d":" -f2` | egrep -o "[0-9]+"
Some more resources:
acl/facl examples and reference
man acl
POSIX Access Control Lists
statacl
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook + UserBundle authentication with symfony2 I'm trying to authenticate my users via facebook or userbundle on symfony2
Here's what I did so far (and it works, although not as I want):
firewalls:
main:
pattern: .*
fos_facebook:
app_url: "http://apps.facebook.com/appName/"
server_url: "http://localhost/facebookApp/"
login_path: /fblogin
check_path: /fblogin_check
default_target_path: /
provider: my_fos_facebook_provider
form_login:
check_path: /login_check
anonymous: true
logout:
handlers: ["fos_facebook.logout_handler"]
The problem with that config is that when the user is not logged in, he's redirected to /login (form_login), while I'd like him to be redirected to Facebook authentication by default
I already tried simply removing the form_login, but then if I access /login (which is how I want users to login outside facebook), it doesn't know the /login_check route to submit the login form
Maybe chain_provider would be a solution? I didn't get it working either
A: An easy and mabye more usable option would be to show all the login options in the login page (including facebook, twitter, open id, or whatever you'd like to use)
A: Chain providers is indeed the solution to this problem. Here is what you security.yml config shoud look like:
providers:
my_project.chain_provider:
chain:
providers: [fos_userbundle, my_project.facebook_provider]
fos_userbundle:
id: fos_user.user_provider.username_email
my_project.facebook_provider:
id: my_project.user_provider.facebook
And, of course, you need to define your own facebook provider as stated here
A: You should add the fos_userbundle provider for the form_login (and keep the rest of the configuration):
form_login:
provider: fos_userbundle
I didn't dig too much, but I think Symfony2 is automatically creating a chained provider in this case.
A: Also you can write your event listener where you will be looking whether a user goes to /login form directly or by redirecting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: Help with solving D&D maze using Java I been reading some of the other questions that have been posted on stackoverflow and I am a little overwhelmed by the number of search algorithms there are. I'm not looking for code and more of a page that goes over background of the algorithm and maybe some sudo code. I know there are algorithms like A* but due to lack of time I don't know if I would be able to complete the program with this algorithm. The maze is generated using a server program and the solver connects to the server in order to send commands to more the player piece. I do not have access to the methods within the server program. I have to solve a maze that has been created to be like a D&D maze. Here is a basic overview of the game:
A classical D&D computer game consists of a dungeon (maze), where the
purpose of the game is to make one's way through the dungeon, entering
at the "entrance" of the maze and exiting at its "exit". To make
things more challenging, the layout of the dungeon is not known a
priori and there are obstacles (zombies, tar-pits, and doors) that
must be overcome by using objects (fares,ladders, and keys) that are
found along the way.
I have notice that many of the other post do not have to worry about obstructions to completing the maze, would this be a major problem to adapt the algorithm to compensate for the obstructions? I was wondering if something like the right hand rule would be fine to solve the maze and if not what would be a algorithm that is as simple as possible to solve the maze(Due to the fact that I have to complete the program soon). Any other links would be great as I know that I have to complete this program again in Objective-C and I would like to implement something more powerful then the right hand rule when this happens. Thanks for any help.
A: well for simple mazes, you basically "walk" along a path until you get to an intersection. At that point you record all of your options. Then you choose one (using whatever heuristic you like, for you right-hand technique, you'd always "go right"). Once you've recorded the options, you stuff that on to a stack. You then continue forward.
When you read a dead end, you either "walk back", or if possible, simply pop the stack, choose another option and continue from there. To walk back, you simply record each move on the stack as well, and start unwinding the stack until you've reached the last intersection.
You can simply continue to do this, noting monsters and such as either something you can get through, or it you're missing an item, as a "dead end". You can then record these passable dead ends at the intersections so that if you ever come back to the intersection still looking for an exit, you can check your inventory for the "key" or "sword" or whatever you need to pass it. When you've come back, check the options for unexplored paths, and for paths blocked by things you can defeat. If you have the item that can defeat the monster, you can retake that route, defeat the monster and continue on.
I don't recall if this technique will work with mazes that have cycles. It should, since you should always be able to tell if you've visited a spot before, leave a trail of "breadcrumbs" behind you or recording locations you've seen.
It certainly won't tell you the optimal path, or the best scoring path, it will just get you to the exit whenever you bumble upon it.
You can also represent the dungeon as a connected graph in memory as you discover the intersections, with each node in the graph being an intersection, and with the path lengths (the number of steps) it takes between each node being the transitions in the graph. You can also represent obstacles in this graph as nodes.
So if you encounter a Vampire, it'll be a node with no exits at the end of a hall. Later, when you get the crucifix and wooden stake, you'll "know" where the Vampire is, and be able to traverse the graph back to the Vampire (assuming it's not moving, of course).
The trick is really building up this graph as you go and using stock graph traversal algorithms (of which there are many, and they're not that difficult) to navigate from one node to another.
But for traversing a simple maze, the stack technique works very well.
Addenda:
For simple mazes, a single stack should be sufficient. I don't know how your map is laid out or how you navigate it, etc.
But what you can do is every time you move, simply place the move on the stack. Then when you want to backtrack, you start popping the stack and go in the opposite direction of the move until you get back to an intersection, then go from there.
This is simply a "depth first" search of a tree that you don't know the layout of yet. But it's also important that you also keep track of where you been in some other way. For example, if you maze is represented as a large array of floor and wall pieces, you can capture the coordinates of each floor piece you entered on a simple list.
The reason for this is so that if there are cycles in the maze, you don't want to "walk forward" on to spaces that you've already walked on. Obviously you need to do that when backtracking. But when exploring, you need to know what you have and have not seen. How you track that is dependent on how the data structure of your map.
Consider this trivial maze:
# ########
# ########
# # # #
# # #### #
# #a b#
# # #### #
# # #
##### ####
# c #
# ########
You can see that you'll need to push on to the stack only at location a, b, and c. If you're able to mark the floor where you've been, your map might look like this at the first intersection:
#.########
#.########
#.# # #
#.# #### #
#.#a b#
#.#.#### #
#. .# #
##### ####
# c #
# ########
And you stack would look like:
{d,d,d,d,d,d,d,l,u}
For 7 downs, one left, and one up.
If you can't mark the map, you could track the coordinates instead. It all depends.
A: I personally would try using recursion to find the path. You could have if statements to handle the traps and what not along with return statements to tell you the path.
public static int recursion(int x, int y) {
if (location == end) {
return 0; //found the end
}
if (deadEnd) {
//backtrack
}
if (trapName) {
//put whatever you need to do to get around it
}
if (x+1 <= edge) {
recursion(x+1,y); //Moves right
}
}
This is more or less pseudo code. Hope it helps though!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .Net - ado.net importing rows vs adding rows? The DataTable has a method called ImportRow(), There is also a method unders the rows called Add(). So what's the difference between these methods?
dataTable.Rows.Add(newRow);
vs
dataTable.ImportRow(newRow);
A: *
*ImportRow preserves any setting of the row: DataRowState,values etc.
*Add calls NewRow that initialize a row using default values.
ImportRow is useful if you're importing a row from another table and you need to preserve all because you're planning to use a DataAdapter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to ignore files in Git that are like _ReSharper I want to ingore any file/folder that has:
_ReSharper
in the file or folder in my .gitignore file, is this possible?
I tried:
ReSharper
but that doesn't work.
A: Just add the exact name you want to the .gitignore, in this case add
_ReSharper
_ is not a special character in .gitignore.
A: I read your question as asking whether you can ignore all files and directories that contain _ReSharper as a substring of their name, in which case you can add the following line to your .gitignore:
*_ReSharper*
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where to put sql queries? Code style. Java. JDBC I am working with JDBC driver and my problem is storing SQL queries in a good place. The point is that it will be making a large number of queries.
Statement s = conn.createStatement ();
s.executeUpdate ("DROP TABLE IF EXISTS animal");
s.executeUpdate (
"CREATE TABLE animal ("
+ "id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))");`
Change to this...
Statement s = conn.createStatement ();
s.executeUpdate (StaticVariables.getDropTableAnimalQuery());
s.executeUpdate (StaticVariables.getCreateTableAnimalQuery());`
... and create special class with static variables
public class StaticVariables {
private static String dropTableAnimalQuery = "DROP TABLE IF EXISTS animal";
private static String createTableAnimalQuery = "CREATE TABLE animal ("
+ "id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))";
public static String getDropTableAnimalQuery() {
return dropTableAnimalQuery;
}
public static String getCreateTableAnimalQuery() {
return createTableAnimalQuery;
}
}
Maybe someone has a better way to solve this
A: I hate that idiom of putting static constants in an interface like your StaticVariable example.
I prefer to keep constants in the class that uses them to the greatest degree possible. I'll add constants to an interface if many sub-classes that implement it need them, but there will be methods that are implemented as well.
A: I would recommend making your sql constants. Whether you put them in the code that will use them, or into another class created specifically to hold your constants is up to you.
public static final String CREATE_TABLE = "CREATE TABLE animal ("
+ "id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))";
public static final String DROP_TABLE = "DROP TABLE IF EXISTS animal";
A: It is better place that queries where you need them. There is no reason to replace them into distinct class. Classes should have fields and methods, state and behavior, otherwise you kill the main idea of OOP. So to have the classes that are entirely a bunch of static strings is a bad idea.
By the way have a look at Spring Jdbc api. It really simplifies your daily work with Jdbc. It doesn't require a spring context if you don't whant to use it. But it is easier to work with jdbc using that api. Here is a small sample that may helps you too:
public int countYellowBoxes(final String color) {
final String query = "select count(*) from boxes where color = ?";
return jdbcTemplate.queryForInt(query, color);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP parser ASP page
Possible Duplicate:
PHP : Parser asp page
I have this tag into asp page
<a class='Lp' href="javascript:prodotto('Prodotto.asp?C=3')">AMARETTI VICENZI GR. 200</a>
how can i parser this asp page for to have the text AMARETTI VICENZI GR. 200 ?
This is the code that I use but don't work :
<?php
$page = file_get_contents('http://www.prontospesa.it/Home/prodotti.asp?c=12');
preg_match_all('#<a href="(.*?)" class="Lp">(.*?)</a>#is', $page, $matches);
$count = count($matches[1]);
for($i = 0; $i < $count; $i++){
echo $matches[2][$i];
}
?>
A: You're regular expression (in preg_match_all) is wrong. It should be #<a class='Lp' href="(.*?)">(.*?)</a>#is since the class attribute comes first, not last and is wrapped in single quotes, not double quotes.
You should highly consider using DOMDocument and DOMXPath to parse your document instead of regular expressions.
DOMDocument/DOMXPath Example:
<?php
// ...
$doc = new DOMDocument;
$doc->loadHTML($html); // $html is the content of the website you're trying to parse.
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//a[@class="Lp"]');
foreach ( $nodes as $node )
echo $node->textContent . PHP_EOL;
A: You have to modify the regular expression a little based on the HTML code of the page you are getting the content from:
'#<a class=\'Lp\' href="(.*?)">(.*?)</a>#is'
Note that the class is first and it is surrounded by single quotes not double. I tested and it works for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to rewrite /archive/* to /post/* in ASP.NET I'm trying to migrate from SubText to BlogEngine.NET and I want to keep the links to the old posts working.
The URLs are very similar, previously they were:
http://server/archive/year/month/day/name-of-the-post.aspx
and now they are
http://server/post/year/month/day/name-of-the-post.aspx
I'm using IIS 7.5 with ASP.NET 4.0 in Integrated Mode. What's the best way to rewrite the "/archive/" to "/post/", knowing that I now also have a http://server/archive.aspx that has to keep working?
Best Regards,
Gustavo Guerra
A: Best thing to do is use the extension:
SEO Redirection
http://www.blogenginewall.com/post/2011/04/01/BlogEngine-SEO-Permanent-Redirection-From-Old-URL-To-New-URL.aspx
Real easy to use and this is what I use.
All you do is put:
Old URl: http://server/archive/year/month/day/name-of-the-post.aspx
New URL: http://server/post/year/month/day/name-of-the-post.aspx
Thats it!
Not only does it redirect but will also return a 301 Status to the search engines telling them that the old URL is no longer being used and to use the new instead url.
This way it also updates the search engines.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Run many .exe files in 1500 folders Hello i have about 1500 folders each containing a .exe file and some associated input files.
The process is simple, when i double click the .exe file it operates on the input files and gives a new output within the folder.
I just want to know how to do this for all 1500 folders with a script or any other way that will save my time.
A: for /r %%I in (*.exe) do "%%I"
Note that this doesn't work if the .exe needs to run from its directory. In that case use
for /r %%I in (*.exe) do cd "%%~pI" && "%%I"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Store files temporarily on server until a task is completed I cant use sessions.
So heres the scenario: I want the user to upload an image, but that image needs to be a particular size. So I allow them to upload any size image, store that temporarily on the server (resize it so it fits on the webpage), display it back to the user, let the user crop it. I then send the crop details back to the server, crop the image and save it and use it as the users profile picture.
I tried to do all this before uploading, but apparently, its a security risk and not allowed.
So how do I temporarily store this file? What if the user does not come back before cropping, I dont want a large image like that sitting on my server. How would I go about removing the file in a stateless application like this?
Files are stored on a CDN.
A: You can use TempData, which is similar to Session, but dies after being read.
A: There are lots of ways to solve this, but perhaps an easy way is that every time a file is uploaded, call a little routine that checks for, and deletes, any 'large' files that are over xxx minutes old.
Alternatively, schedule a job to do the same every xxx minutes in the task scheduler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript perform arithmetic on captured regexp I want to replace my title from its default to "*number* new messages | default"
Here is the code I have, it changes from default to 1 new messages fine, but it never goes above 1.
title = $('title').text();
regexp = /^(\d+)/
if (title.match(regexp))
$('title').text().replace(regexp, (parseInt("$1")+1).toString())
else
$('title').text('1 New Messages | Default')
A: You should be using a function as the second argument to replace, you also need to set the new value:
var title = $('title').text();
$('title').text(title.replace(regexp, function(m) { return parseInt(m, 10) + 1) }));
And, as usual, don't forget the radix argument when you call parseInt or you will be unpleasantly surprised sooner or later.
A: I came across this recently and the issue is to do with calling a function within the second argument of the replace function. The $1 is only valid if called directly in a string literal, not as a string argument to a function.
Another issue is that $('title').text().replace(regexp, (parseInt("$1")+1).toString()) will return a string. You need to pass the value you want to assign the text to as a function argument of the text() function like you have done in your else block.
Try this:
title = $('title').text();
regexp = /^(\d+)/
if (numToReplace = title.match(regexp))
$(title).text(title.replace(regexp, (parseInt(numToReplace[1])+1).toString()))
else
$('title').text('1 New Messages | Default')
And a JSFiddle: http://jsfiddle.net/KFW4G/
A: replace returns a new string, so you have to use text again to set the text to the result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to generate bitcode from dragonegg Back when dragonegg was in llvm-gcc one could issue -emit-llvm and it did generate llvm bitcode. Now when I use dragonegg as a plugin (gcc -fplugin=dragonegg.so) I cannot find any such option anymore. The only thing I found was generating LLVM IR - which is not what I want.
How is it still possible to generate bitcode?
GCC is 4.6, LLVM and Dragonegg are current SVN. And using clang is not an option since its C++11 support is feeble.
A: Since outputting LLVM bitcode doesn't seem to be possible anymore I wrote a python script which then feeds the IR to llvm-as which then gives me bitcode. Performance-wise this is a catastrophe, but at least it works.
#/usr/bin/env python
import sys, subprocess
args = list(sys.argv)
del args[0] # Remove our exec name
compiler = args[0]
del args[0] # Remove the compile name
compileArguments = [compiler]
outputFile = ''
foundFile = False
for arg in args:
if arg.startswith('-o'):
foundFile = True
elif foundFile:
outputFile = arg
foundFile = False
arg = "/dev/stdout"
compileArguments.append(arg)
compileProcess = subprocess.Popen(compileArguments, stdout=subprocess.PIPE)
asbin = 'llvm-as'
ir2bcProcess = subprocess.Popen([asbin, '-f', '-o=' + outputFile], stdin=compileProcess.stdout)
stdout, stderr = ir2bcProcess.communicate()
compileProcess.wait()
ir2bcProcess.wait()
A: From the README:
-fplugin-arg-dragonegg-emit-ir
-flto
Output LLVM IR rather than target assembler. You need to use -S with this,
since otherwise GCC will pass the output to the system assembler (these don't
usually understand LLVM IR). It would be nice to fix this and have the option
work with -c too but it's not clear how. If you plan to read the IR then you
probably want to use the -fverbose-asm flag as well (see below).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to organize / structure methods into namespaces in a WCF service? What is considered as best-pratice when it comes to organizing / structuring methods in a WCF Service?
Let's assume I have a .net dll that I want to expose through a WCF Service.
The .net dll has a namespace structure like this:
Root
-- > SubNameSpace1
-- > SubNameSpace2
-- > -- > CategoryA
-- > -- > CategoryB
-- > SubNameSpace3
How would I expose this namespace structure through a WCF Service? (Because I don't want all methods from all namespaces to be merged as methods of the client object that calls the service.)
When is it appropriate / recommend to create different *.svc files? (in relation to my namespace structure)
A: The best practice is to not expose DLLs through services. Instead, design a service that exposes a coherent set of functionality in a Service-Oriented manner. Then, implement that functionality using the DLL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disadvantages of Sql Cursor I was studying cursor and I read somewhere that. Each time you fetch a row from the cursor, it results in a network round trip whereas normal select query makes only one round trip however large the resultset is.
Can anyone explain what does that means? And what does network round trip and one round trip means in detail with some example. And when we use cursor and when we use while loop?
A: Unfortunately, that reference is incorrect.
A "normal SELECT" creates a cursor that the client fetch from. The mechanics are exactly the same as if you open and return a SYS_REFCURSOR (or any other mechanism for opening a cursor). In both cases, the client will fetch a number of rows over the network every time it requests data from the database. The client can control the number of rows that are fetched each time-- it would be exceptionally rare for the client to fetch 1 row or to fetch all the rows from a cursor in a single network round-trip.
What actually happens when a client application fetches from a cursor (no matter how the cursor is opened), the client application sends a request over the network for N rows (again, the client controls the value of N). The database sends the next N rows back to the client (generally, Oracle has to continue executing the query in order to determine the next N rows because Oracle does not generally materialize an entire result set). The client application does something with those N rows and then sends another request over the network for the next N rows and the pattern repeats.
A: In virtually all database systems, the application that uses the data; and the DBMS that is responsible for storing and searching the data; live on separate machines. They talk to each other over a network. Even when they are on the same machine, there is still effectively a network connection.
This matters because there is some time between when an application decides that it's ready to read data, when that request arrives over the network at the database server, when the database server actually gets the response for that, and when the response finally arrives over the network on the application side.
When you do a query for a whole set of data, you only pay this cost once; Although it may seem wasteful; in fact it's much more efficient to put the burden of holding on to all of the data on the application, because it's usually easier to give more resources to an application than to do the same on a database server.
When your application only fetches data one row at a time, then the cost of the round trip between application and database is paid once per row; If you want to show the titles of 100 blog posts, then you're paying the cost of 100 round trips to the database for that one report. Whats worse is that the database server has to some how keep track of the partially completed result set. That usually means that the resources that could be used for querying data for another request are instead being retained by an application that hasn't happened to ask for all of the data it originally asked for.
The basic rule is to talk to the database only when you absolutely have to, and to make the interaction as short as possible; This means you only ask for the data you really need (have the database do as much filtering as possible, instead of doing it in the application) and accept all of the data as quickly as possible, so that the database can move on to another task.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change to a option on click? jQuery I have a select inside a <tr>. When you click on a link I would like the select change to the option that has value "00:00".
I tried myself and came this far:
jQuery(this).parents('tr').find('select')
A: How about this?
$(this).parents('tr').find('select').val('00:00');
A: $('#myLink').click(function(e){
$(this).closest('tr').find('option').val('00:00');
e.preventDefault();
});
As long as the <select> has an <option ... value="00:00">...</option>, .val() will locate (and select) that <option> for you.
Working Demo showing how .val() finds the <option> (and selects it) for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JBox2D collisions not bouncing I have an Android application using JBox2D for physics simulation. The only dynamic object is a 0.07m radius circle, as well as several static circles and rectangles in a total game area of about 20m by 20m. I'm also using a few custom forces through the ApplyForce method.
Whenever any bodies collide, they do collide correctly however they don't bounce; everything just thuds together. All bodies have their densities, frictions and restitutions set (some objects have a restitution greater than 1).
Does anyone have any ideas why these collisions aren't working? I think it might be because the bodies aren't moving fast enough for JBox2D to count as proper collisions (there is a cutoff in Box2D).
Thanks!
A: setting Settings.velocityThreshold = 0.0001f; (or very small) solved it for me.
A: I found a partial solution to this - Box2D (at least JBox2D) ignores restitution if the velocity is below a certain threshold - by scaling all my objects up by a factor of 10, the threshold becomes relatively lower, and objects bounce.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get max value of a column using Entity Framework? To get maximum value of a column that contains integer, I can use the following T-SQL comand
SELECT MAX(expression )
FROM tables
WHERE predicates;
Is it possible to obtain the same result with Entity Framework.
Let's say I have the following model
public class Person
{
public int PersonID { get; set; }
public int Name { get; set; }
public int Age { get; set; }
}
How do I get the oldest person's age?
int maxAge = context.Persons.?
A: Maybe help, if you want to add some filter:
context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();
A: Your column is nullable
int maxAge = context.Persons.Select(p => p.Age).Max() ?? 0;
Your column is non-nullable
int maxAge = context.Persons.Select(p => p.Age).Cast<int?>().Max() ?? 0;
In both cases, you can use the second code. If you use DefaultIfEmpty, you will do a bigger query on your server. For people who are interested, here are the EF6 equivalent:
Query without DefaultIfEmpty
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Extent1].[Age]) AS [A1]
FROM [dbo].[Persons] AS [Extent1]
) AS [GroupBy1]
Query with DefaultIfEmpty
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Join1].[A1]) AS [A1]
FROM ( SELECT
CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE [Project1].[Age] END AS [A1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT
[Extent1].[Age] AS [Age],
cast(1 as tinyint) AS [C1]
FROM [dbo].[Persons] AS [Extent1]) AS [Project1] ON 1 = 1
) AS [Join1]
) AS [GroupBy1]
A: If the list is empty I get an exception. This solution will take into account this issue:
int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();
A: maxAge = Persons.Max(c => c.age)
or something along those lines.
A: Selected answer throws exceptions, and the answer from Carlos Toledo applies filtering after retrieving all values from the database.
The following one runs a single round-trip and reads a single value, using any possible indexes, without an exception.
int maxAge = _dbContext.Persons
.OrderByDescending(p => p.Age)
.Select(p => p.Age)
.FirstOrDefault();
A: As many said - this version
int maxAge = context.Persons.Max(p => p.Age);
throws an exception when table is empty.
Use
int maxAge = context.Persons.Max(x => (int?)x.Age) ?? 0;
or
int maxAge = context.Persons.Select(x => x.Age).DefaultIfEmpty(0).Max()
A: In VB.Net it would be
Dim maxAge As Integer = context.Persons.Max(Function(p) p.Age)
A: Try this int maxAge = context.Persons.Max(p => p.Age);
And make sure you have using System.Linq; at the top of your file
A: Or you can try this:
(From p In context.Persons Select p Order By age Descending).FirstOrDefault
A: int maxAge = context.Persons.Max(p => p.Age);
The version above, if the list is empty:
*
*Returns null ― for nullable overloads
*Throws Sequence contains no element exception ― for non-nullable overloads
_
int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();
The version above handles the empty list case, but it generates more complex query, and for some reason doesn't work with EF Core.
_
int maxAge = context.Persons.Max(p => (int?)p.Age) ?? 0;
This version is elegant and performant (simple query and single round-trip to the database), works with EF Core. It handles the mentioned exception above by casting the non-nullable type to nullable and then applying the default value using the ?? operator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "116"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.