text stringlengths 8 267k | meta dict |
|---|---|
Q: How to implement the queue of events? I need to implement the queue of events (=updates on the server). New events will be added to this queue when user changes the slider, presses buttons etc. Each event will contain the following properties:
*
*device id (the action will be applied to that device on the server)
*action (set, get etc.)
*value (the value, which should be used in the action)
New event should be added there at the end. But in case there is already event for the same device id and with the same action, then this event should be updated with new value. How should I do that?
I've drafted the following:
var inCall = false;
var queueArrayDevices = new Array();
var queueArrayActions = new Array();
var queueArrayValues = new Array();
// add call to the queue, at the end
function addAPICall(device, action, value){
// should NOT add event here, if device and action already exists
// should update the value instead
queueArrayDevices.push(device);
queueArrayAсtions.push(action);
queueArrayValues.push(value);
}
function doAPICall(device, action, value){
inCall = true;
// call server here
// if not successful, we should add this item to the queue again
inCall = false;
}
function callAPIQueue(){
if(!inCall && queueArrayDevices.length > 0){
device = queueArrayDevices.shift();
action = queueArrayAсtions.shift();
value = queueArrayValues.shift();
doAPICall(device, action, value);
}
}
// start queue processing
setInterval(callAPIQueue, 400);
I use jquery mobile, probably it can help me to simplify such queue creation?
A: If you expect a short event queue, then the solution of @Martin is appropriate. The time complexity of his solution is O(n), where n is the queue length, and this is perfect if n is small.
If your queue could get long, then you might consider a faster approach like the following. The queue is represented by a map mapping the unique identifiers (device_id, action) to values. This provides a fast lookup of existing properties. The time complexity is reduced to O(log n). A convenient implementation of a map in Javascript is to use object properties that encode (device_id, action) into a unique string, e.g. "device_id#action". In addition, the properties are linked to provide first-in/first-out behavior.
var Map = {
// properties: "id#action": {value: value, next: property}
first: "",
last: "",
empty: function() {return Map.first == "";},
enque: function(device, action, value) {
var k = device + "#" + action;
if (k in Map) {
Map[k].value = value;
}
else {
Map[k] = {value: value, next: ""};
if (Map.first == "") {
Map.first = Map.last = k;
}
else {
Map[Map.last].next = k;
Map.last = k;
}
}
},
deque: function() {
var firstProp = Map.first;
var key = firstProp.split("#");
var value = Map[firstProp].value;
Map.first = Map[firstProp].next;
delete firstProp; // delete this property
return {device: key[0], action: key[1], value: value};
}
};
The Map is used as follows:
function addAPICall(device, action, value) {
Map.enque(device, action, value);
}
function callAPIQueue() {
if (!inCall && !Map.empty()) {
var event = Map.deque();
doAPICall(event.device, event.action, event.value);
}
}
A: First of, you should only have one array holding an event object, otherwise you are really over complicating it for yourself.
next just loop over the events and see if one of the same device/action already exists when a new event is added.
try to do it something like this:
var inCall = false;
var queue = [];
// add call to the queue, at the end
function addAPICall(device, action, value){
var found=false;
for(var i=0, event; event = queue[i]; i++) {
if(event.action == action && event.device == device) {
event.value = value;
found = true;
break;
}
}
if(!found) {
queue.push({device: device, action: action, value: value});
}
}
function doAPICall(device, action, value){
inCall = true;
// call server here
// if not successful, we should add this item to the queue again
inCall = false;
}
function callAPIQueue(){
if(!inCall && queueArrayDevices.length > 0){
var event = queue.shift();
doAPICall(event.device, event.action, event.value);
}
}
// start queue processing
setInterval(callAPIQueue, 400)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook publish status I am using facebook ios api and I want to publish a status for the user if he clicks on something.
The problem is that i want to do it without using the FBDialog and I didn't find anyting that do it - I've only found the method:
[[FBRequest requestWithDelegate:self] call:@"facebook.fql.status" params:params];
But this method is not in use in the API any more.
A: They replaced the FBRequest with the Graph API which is really easy to use, just with something like this you can be able to post without the FBDialog (you will need the publish_stream permission in order to do this):
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
kAppID, @"app_id",
@"http://developers.facebook.com/docs/reference/dialogs/", @"link",
@"http://fbrell.com/f8.jpg", @"picture",
@"Facebook Dialogs", @"name",
@"Reference Documentation", @"caption",
@"Using Dialogs to interact with users.", @"description",
nil];
[facebook requestWithGraphPath:@"/me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
And just check in the delegate methods if the post was successfully posted:
(void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data;
(void)request:(FBRequest *)request didFailWithError:(NSError *)error;
A: While technically you can do this via the graph api by publishing to /me/feed with publish_stream permissions, it is against the Facebook Platform Policy to prefill the message text with content that wasn't generated by the user. Facebook deprecated the message parameter from the dialog:
This field will be ignored on July 12, 2011 The message to prefill the
text field that the user will type in. To be compliant with Facebook
Platform Policies, your application may only set this field if the
user manually generated the content earlier in the workflow. Most
applications should not set this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing variables from delegate iOS im passing an array from my app delegate to a view controller as follows :
Delegate *appDelegate = [[UIApplication sharedApplication] delegate];
self.rows = appDelegate.getCourseArray;
My question is, when do i release 'appDelegate'? i tried to release it after the variable is passed but that makes a blank screen (Black). I imagine its because im releasing the actual delegate and not the copy, but in this instance, am i supposed to release it?
A: You don't release it at all as you don't have ownership of it as per Apples Memory Management Rules.
A: There is no new, allco, retain or copy (NARC) in the line that obtains the appDelegate to there is no ownership and no release/autorelease needs or should be issued.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Maintaining privacy when publishing actions to Facebook using Open Graph For the new Open Graph Protocol to work we push an action by sending a request which includes the objects url to Facebook.
Facebook then sends out it's bot with a special user agent string to get the information about the object.
The information being pushed to Facebook could be user specific (not just a book or recipe) and therefore should only be accessible to the user and their friends.
My question is, other than checking the user agent (easily spoofed) and using tough-to-guess urls for my objects, is there any way to stop people accessing what is essentially private information (via the objects unique url)?
Some examples of objects which might be private... a run, anything to do with weight loss, a photo album.
A: After plenty more research, I'll have a good go at answering my own question.
If your app contains information you would like to keep private to those who created it (for example a weekly dieting update) you must ensure your object Open Graph urls aren't guessable. That means when you call the api, or do it via curl...
curl -F 'access_token=[access_token]' \
-F 'object=http://example.com/[object_url]' \ 'https://graph.facebook.com/me/[namespace]:[action]'
..you want to ensure that the [object_url] is not guessable. A good way to do that is to include the objects id AND some other unguessable hash / string.
The steps above ensure only you and Facebook will ever know where the objects information is located allowing you to hand it over, and even to update it occasionally. Even if someone did manage to get access to one object url they could still not access any others.
The second part of the security issue is on the graph side, but as you can see from the result of clicking the following link, you must have an access_token to view an application graph object so this is also secure and private:
http://graph.facebook.com/10150300390106292
I hope this helps someone at some point. It confused the hell out of me.
A: You're going to have to implement a "protection" on your side. Only the authed users should see what you have shared.
In your site design you should consider the display of content on your site based on:
Logged out user
Facebook user, not a user of your app
Facebook user, user of your app, but not allowed to see all of this content
Facebook user, user of your app and allowed to see the content
This way you will handel each scenario correctly. You van use the "protected" views to drum up new users of to encourage more sharing in your app.
When a user "adds the app" they will be able to select the sharing rules for this app. You need to make sure that you implement an authority model that is appropriate for your content and how it is shared with between users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Protect access phone's settings with a password programmatically? Is it possible to implement an application that programmatically protects the access to a phone's "Settings" with a password ?
A: The answer for you may lie in Device Administration API for Android
Also refer an example http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to convert a large JMeter summary report to a chart I have a set of large summary reports from JMeter test cases. The reports contain test results where I have a large number of threads in long-running loops. The summary reports provide me with all the statistics I need, but I would like to be able to convert these reports to graphs/charts. This would allow me to show whether the tests were scaling linearly and so on.
My reports are so large that it doesn't look possible to convert them to graphs within JMeter itself. Can anyone recommend a way of converting large summary reports into decent looking charts? I'm particularly interested in graphing the throughput and response times.
A: Gzip your files and upload them to Loadosophia.org, you'll have several graphs for your test.
Also you may use JMeterPluginsCMD tool to create graphs from command line, this brings you some automation with long-running result analysis.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MVC3 Razor view not coping with jQuery CDN fallback script I'm looking to implement loading jQuery from the Google Content Delivery Network. The issue I'm having is that the recommended script from HTML5 Boilerplate is causing the Razor view to lose sight of it's closing curly bracket.
I've tracked it down to the last script line, in the code below. The IDE seems convinced that it doesn't have a closing tag (unsure if it's VS2010, or Resharper reporting it).
In the View:
@if ([Decision...])
{
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"> </script>
<script type="text/javascript">(window.jQuery || document.write('<script src="/Scripts/jquery-1.6.3.min.js"><\/script>')) </script>
}
And running it gives an error about the closing bracket:
Parser Error Message: The if block is missing a closing `"}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.`
Suggestions as to how to modify the script to suit Razor?
A: @if ([Decision...])
{
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
@:<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"> </script>
@:<script type="text/javascript">(window.jQuery || document.write('<script src="/Scripts/jquery-1.6.3.min.js"><\/script>'))</script>
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I use getenv in daemon process under UNIX environment? I am writing a daemon process (let's say pA), which is kicked off by a another process(let's say pB), in this daemon pA, I want to use getenv to access a evn variable defined in .cshrc, but to my surprise, getenv returns NULL in pA. I write a another standalone program to use getenv to access this same variable, and it works fine. So I want to ask if getenv can't work in daemon process? How can I access env variables in daemons? thank you
A: Probably not relevant any more, but for the people that come here through search - see the answer here: https://stackoverflow.com/a/11850426/397604
In Linux, if you only set the variable (or export it) in a bash
session, it will be available to a kind of "sub" session, which is
only available to the command you just executed, and nothing else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Magento CMS Page/Static Blocks - How to display store name? I have number of Magento CMS pages and static blocks which use the variable {{store url=""}} to display the store url address in some text depending which store is being viewed.
I would like to also display the store name. Is there an equivalent which would display the store name, something like {{store name=""}}? ({{store name=""}} doesn't work btw)
I don't have access to the .php files so would like to know if this is possible without access. If not, then I can request changes to the .php, I just need to know what to request.
A: you can use any method on store object:
{{var store.getFrontendName()}}
search your codebase for further reference:
grep '{{store' app/locale/ -rsn
A: Try {{config path="general/store_information/name"}}.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to walk a dropbox folder tree with node.js I am trying to read dropbox metadata through their API, and write the url paths for ALL folders, subfolders and files into an array. Dropbox basically returns me a metadata response object showing all files and folders for a certain URL, and then I have to go into each folders again to do the same, until I have walked through the whole tree.
Now the problem:
*
*I have 'kind of' managed to walk the whole tree and do this, however due the way I did it I am unable to issue a call back(or event) when I have completed to walk through all possible urls.
*Additionally I am calling a function from within itself. While this seems to work I do not know if it is a good or bad thing to do in Node.js. Any advice on this would also be appreciated, as I am fairly new to node.js.
My code:
function pathsToArray(metadataarr,callback){ //Call this function and pass the Dropbox metadata array to it, along with a callback function
for (aItem in metadataarray ){ //For every folder or file in the metadata(which represents a specific URL)
if (metadataarr[aItem].is_dir){ //It is a folder
dropbox.paths.push(metadataarr[aItem].path+"/"); //Write the path of the folder to my array called 'dropbox.paths'
dropbox.getMetadata(metadataarr[aItem].path.slice(1),function(err, data){ //We go into the folder-->Call the dropbox API to get metadata for the path of the folder.
if (err){
}
else {
pathsToArray(data.contents,function(err){ //Call the function from within itself for the url of the folder. 'data.contents' is where the metadata returned by Dropbox lists files/folders
});
}
});
}
else { //It is a file
dropbox.paths.push(metadataarr[aItem].path); //Write the path of the file to my array called 'dropbox.paths'
}
}
return callback(); //This returns multiple times, instead of only once when everything is ready, and that is the problem!
};
Thanks!
A: OK, so I implemented a counter variable which increases every time the function is called, and decrements every time it has completed the loop. When the counter returns to zero an event gets dispatched.
Not sure if it is a nice solution IMHO so if you anyone knows better please let me know. Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: php script seems to be ignoring if statements? I have AJAX running a query every 5 seconds which checks if a user has requested a session with the coach. and if there is it pops up with a dialog. the script changes the field so that it won't catch the same session request, but it doesn't seem to care if the field is blank or not it just runs all the way through the php script. here's the ajax and php code.
setInterval(function() {
$.ajax({
type: "GET",
url: "includes/checksessionrequests.php",
success: function(msg){
if(msg == "yes") {
$(\'$<div title="Request Recieved"></div>\').load(\'requestreceived.php\').dialog({modal: true, closeOnEscape: false, open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }, height: 300, width: 480, hide: {effect: "fade", duration: 1000}, show: {effect: "fade", duration: 1000}});
}
}
});
the query
<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
$result = mysql_query("SELECT * FROM sessionrequests
WHERE coach='$user'
AND sessionstatus=''
ORDER BY id") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$sessionstatus = $row['sessionstatus'];
$sessionid = $row['id'];
if($sessionstatus != "") {
die("no");
}
elseif($sessionstatus == "")
{
$result = mysql_query("UPDATE sessionrequests
SET sessionstatus='received'
WHERE id='$id'");
echo "yes";
}
mysql_close($con);
?>
A: You are not checking if the query is actually successful or if the query returns a match. If either of these scenarios happen, I believe that $sessionstatus will be set to NULL, thus skipping your if and elseif statements. I am still not too familiar with PHP's weak typing and whether NULL evaluates to "" or not. But, it's worth a shot. :-)
I would try something like this:
$result = mysql_query("SELECT * FROM sessionrequests......");
if ($result) { // Query executed successfully
if (mysql_num_rows($result) > 0) { // Matches returned
$row = mysql_fetch_assoc($result);
$sessionstatus = $row['sessionstatus'];
$sessionid = $row['id'];
// Rest of your code
}
}
mysql_close($con);
A: Your query is only grabbing data WHERE coach='$user' AND sessionstatus=''. $sessionstatus is always "" so if($sessionstatus != "") { die("no"); } is never called.
I still don’t understand the problem though. It’s only gathering requests that have not been received and marking the first such request as received. Isn’t that what you want it to do? What exactly is the problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: how to add record to into array I got a problem with RecordStore when I fetch it and put it into array I got multiple results.
I mean when I have 3 records and fetch it by enumerateRecords then put it into array[][] and then fetch it again, I know that is wrong way to fetch again, but how can I add resultset of recordstore into array[][] and then fetch resultset of array[][]?
My Code:
public Table showRs(){
String sID = null,sName = null,sTOE = null;
hrs.openRecordStore(hrs.getRecordnameBasic());
//hrs.listofRecord();
RecordEnumeration re;
try {
re = hrs.getRcs().enumerateRecords(null, null, true);
while(re.hasNextElement()){
byte[] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
//ID
int iID = record.indexOf(";");
sID = record.substring(0,iID);
//Name
int iName = record.indexOf(";", iID+1);
sName = record.substring(iID + 1,iName);
//Type of Est
int iTOE = record.indexOf(";", iName + 1);
sTOE = record.substring(iName + 1, iTOE);
int rc = hrs.getRcs().getNumRecords();
tb = new Table(mf, this, "List of record");
TableCell cells[][] = new TableCell[rc][3];
for(int i = 0; i< rc ; i++){
System.out.println("-------" + sID);
cells[i][0] = new TableCell(CellType.STRING, sID, true);
cells[i][1] = new TableCell(CellType.STRING, sName, true);
cells[i][2] = new TableCell(CellType.STRING, sTOE, true);
}
String header[] = new String[]{"ID", "Name", "TypeOfEst"};
tb.setData(new int[]{40,97,98}, header, cells);
}
} catch (Exception e) {
e.printStackTrace();
}
return tb;
}
Table
import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class Table extends Canvas implements CommandListener {
private MIDlet midlet;
private Displayable preScreen;
private String tableName;
private int oneRowHeight;
private int Countrow = 2;
private int Countcol = 2;
protected int focusRow = 0;// cursor focus on row
protected int focusCol = 0;// cursor focus on col
private int pad = 0;// pad between row
private int scrollBarWidth = 4;// SCroll bar for table
private int headerHeight;
private String header[] = {" ", " "};//Table header
private int colWidth[] = {118, 118};// total width screen
public TableCell cells[][] = {{new TableCell(CellType.STRING, "Name", false), new TableCell(CellType.STRING, "Bush", true)}, {new TableCell(CellType.STRING, "Sex", false), new TableCell(CellType.ITEM, "Male", new String[]{"Male", "Female"}, true)}};
private Font font = Font.getDefaultFont();// table font
private Command editCommand;
private Command backCommand;
private CellEditor cellEditor;//cell can be edit
public Table(MIDlet midlet, Displayable preScreen, String tableName) {
this.midlet = midlet;
this.preScreen = preScreen;
this.tableName = tableName;
init();
repaint();
}
private void init() {
setTitle(tableName);
editCommand = new Command("Edit", Command.ITEM, 1);
backCommand = new Command("Back", Command.BACK, 1);
addCommand(editCommand);
addCommand(backCommand);
setCommandListener(this);
calculateTableHeight();
repaint();
}
/*
*This method allow me set data into table
*and set total width for table and table header
*/
public void setData(int colWidth[], String header[], TableCell[][] cells) {
if (colWidth.length != cells[0].length || (header != null && colWidth.length != header.length)) {
System.out.println("Invalid Argument.");
return;
}
this.colWidth = colWidth;
this.cells = cells;
this.header = header;
Countrow = cells.length;
Countcol = cells[0].length;
calculateTableHeight();
repaint();
}
/*
* Set table's font
*/
public void setFont(Font font) {
this.font = font;
calculateTableHeight();
repaint();
}
/*
*This method calculate all cells' height.
*Long cell text will be splited into several segments(several lines).
*/
protected void calculateTableHeight() {
oneRowHeight = font.getHeight() + 1;//depends on height of font
if(header==null){
headerHeight=0;
}else{
headerHeight = oneRowHeight;
}
int xTemp = 0;
int yTemp = headerHeight;
int rowHeight=oneRowHeight;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < Countrow; i++) {
rowHeight = oneRowHeight;
xTemp = 0;
for (int j = 0; j < Countcol; j++) {
cells[i][j].x = xTemp;
xTemp += colWidth[j];
cells[i][j].y = yTemp;
cells[i][j].width = colWidth[j];
if (cells[i][j].cellText == null || font.stringWidth(cells[i][j].cellText) < colWidth[j]) {
cells[i][j].height = oneRowHeight;
cells[i][j].multiLine = false;
} else {
cells[i][j].multiLine = true;
cells[i][j].cellString = new Vector();// create vector to store String in that cell
sb.setLength(0);
for (int k = 0; k < cells[i][j].cellText.length(); k++) {
sb.append(cells[i][j].cellText.charAt(k));//append string into sb until the end of string
if (font.stringWidth(sb.toString()) > colWidth[j]) {
sb.deleteCharAt(sb.length() - 1);
cells[i][j].cellString.addElement(sb.toString());
sb.setLength(0);
sb.append(cells[i][j].cellText.charAt(k));
}
}
if (sb.length() > 0) {
cells[i][j].cellString.addElement(sb.toString());
}
cells[i][j].height = oneRowHeight * cells[i][j].cellString.size();
}
if (rowHeight < cells[i][j].height) {
rowHeight= cells[i][j].height;
}
}
for (int j = 0; j < Countcol; j++) {
cells[i][j].height = rowHeight;
}
yTemp += cells[i][0].height;
}
}
protected void paint(Graphics g) {
g.setFont(font);
//draw table background
g.setColor(0xffffff);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//draw table border line
g.setColor(0x000000);
g.drawLine(0, 0, cells[0][Countcol-1].x+cells[0][Countcol-1].width, 0);
g.drawLine(0, 0, 0, cells[Countrow-1][0].y+cells[Countrow-1][0].height);
g.drawLine(cells[0][Countcol-1].x+cells[0][Countcol-1].width, 0, cells[0][Countcol-1].x+cells[0][Countcol-1].width, cells[Countrow-1][0].y+cells[Countrow-1][0].height);
g.drawLine(0, cells[Countrow-1][0].y+cells[Countrow-1][0].height, cells[0][Countcol-1].x+cells[0][Countcol-1].width, cells[Countrow-1][0].y+cells[Countrow-1][0].height);
//draw cells
for (int i = 0; i < Countrow; i++) {
//draw cell background
if (i % 2 == 0) {
g.setColor(0xe7f3f8);
g.fillRect(1, cells[i][0].y - pad + 1, cells[i][Countcol - 1].x + cells[i][Countcol - 1].width, cells[i][0].height - 2);
}
g.setColor(0x000000);
g.drawLine(0, cells[i][0].y - pad + cells[i][0].height, cells[i][Countcol - 1].x + cells[i][Countcol - 1].width, cells[i][0].y + cells[i][0].height - pad);
//draw cell text
for (int j = 0; j < Countcol; j++) {
//draw single-line text
if (!cells[i][j].multiLine) {
if (cells[i][j].cellText != null) {
g.drawString(cells[i][j].cellText, cells[i][j].x + 1, cells[i][j].y - pad + 1, 0);
}
} else {
//draw multi-line text
for (int a = 0; a < cells[i][j].cellString.size(); a++) {
g.drawString(cells[i][j].cellString.elementAt(a).toString(), cells[i][j].x + 1, cells[i][j].y + oneRowHeight * a - pad + 1, 0);
}
}
}
}
//draw table header
if (header != null) {
g.setColor(0xA0A0A0);
g.fillRect(1, 1, cells[0][Countcol - 1].x + cells[0][Countcol - 1].width, headerHeight);
g.setColor(0x000000);
g.drawLine(0, 0, cells[0][Countcol - 1].x + cells[0][Countcol - 1].width, 0);
g.drawLine(0, headerHeight, cells[0][Countcol - 1].x + cells[0][Countcol - 1].width, headerHeight);
for (int i = 0; i < header.length; i++) {
g.drawString(header[i], cells[0][i].x + 1, 0, 0);
}
}
//draw vertical line
int temp = 0;
for (int i = 0; i < colWidth.length; i++) {
temp += colWidth[i];
g.drawLine(temp, 0, temp, cells[Countrow - 1][0].y + cells[Countrow - 1][0].height);
}
//draw scrollbar
g.drawLine(this.getWidth() - scrollBarWidth, 0, this.getWidth() - scrollBarWidth, this.getHeight() - 1);
g.fillRect(this.getWidth() - scrollBarWidth, 0, scrollBarWidth, ((int) (this.getHeight() * (focusRow + 1) / Countrow)));
//draw focus cell
g.setColor(0x3a9ff7);
g.fillRect(cells[focusRow][focusCol].x + 1, cells[focusRow][focusCol].y - pad + 1, cells[focusRow][focusCol].width - 1, cells[focusRow][focusCol].height - 1);
g.setColor(0x000000);
if (!cells[focusRow][focusCol].multiLine) {
if (cells[focusRow][focusCol].cellText != null) {
g.drawString(cells[focusRow][focusCol].cellText, cells[focusRow][focusCol].x + 1, cells[focusRow][focusCol].y - pad + 1, 0);
}
} else {
for (int i = 0; i < cells[focusRow][focusCol].cellString.size(); i++) {
g.drawString(cells[focusRow][focusCol].cellString.elementAt(i).toString(), cells[focusRow][focusCol].x + 1, cells[focusRow][focusCol].y + oneRowHeight * i - pad + 1, 0);
}
}
}
public void commandAction(Command com, Displayable display) {
if (com == backCommand) {
Display.getDisplay(midlet).setCurrent(preScreen);
} else if (com == editCommand) {
if (cells[focusRow][focusCol].editable) {
editCell(cells[focusRow][focusCol]);
}
}
}
private void editCell(TableCell cell) {
if (cellEditor == null) {
cellEditor = new CellEditor(midlet, this, "");
}
cellEditor.setCell(cell);
Display.getDisplay(midlet).setCurrent(cellEditor);
}
public void keyPressed(int keyCode) {
switch (keyCode) {
case -3: //left
focusCol--;
if (focusCol <= 0) {
focusCol = 0;
}
break;
case -4: //right
focusCol++;
if (focusCol >= Countcol - 1) {
focusCol = Countcol - 1;
}
break;
case -1: //up
focusRow--;
if (focusRow <= 0) {
focusRow = 0;
}
if (cells[focusRow][0].y < pad+headerHeight) {
pad = cells[focusRow][0].y-headerHeight;
}
break;
case -2: //down
focusRow++;
if (focusRow >= Countrow - 1) {
focusRow = Countrow - 1;
}
if (cells[focusRow][0].y + cells[focusRow][0].height-pad> this.getHeight()) {
pad = cells[focusRow][0].y + cells[focusRow][0].height - this.getHeight();
}
break;
case 13:
if (cells[focusRow][focusCol].editable) {
editCell(cells[focusRow][focusCol]);
}
break;
}
repaint();
}
}
Table Cell
import java.util.Vector;
public class TableCell {
int x, y, width, height;
int cellType;// types of cell - String , int or other type.
boolean editable = false;// cell can be edit or not.
boolean multiLine = false;// long text can be split into several lines.
public Vector cellString;
public String[] itemOptions;// itemOptions used when cell type is Item.
public String cellText;
public TableCell(){
this(CellType.STRING, "", true);
}
public TableCell(int cellType, String cellText, boolean editable) {
this.cellType = cellType;
this.cellText = cellText;
this.editable = editable;
}
public TableCell(int cellType, String cellText, String[] itemOptions, boolean editable){
this.cellType = cellType;
this.cellText = cellText;
this.itemOptions = itemOptions;
this.editable = editable;
}
/*
*all objects need to be represent by string
*
*/
public String toString(){
return "TableCell: x=" + x + ",y=" + y + ",width=" + width + ",height=" + height+",cellText="+cellText;
}
}
Cell Type
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ui.table;
public class CellType {
public static final int STRING = 0;
public static final int NUMBER = 1;
public static final int ITEM = 2;
}
Cell Editor
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class CellEditor extends Form implements CommandListener {
private MIDlet midlet = null;
private Table previousScreen = null;
private Command backCommand = null;
private Command OKCommand = null;
private TextField textField;
private ChoiceGroup choiceGroup;
private TableCell cell;
public CellEditor(MIDlet midlet, Table previousScreen, String title) {
super(title);
this.midlet = midlet;
this.previousScreen = previousScreen;
initialize();
}
private void initialize() {
backCommand = new Command("Back", Command.BACK, 1);
OKCommand = new Command("OK", Command.OK, 1);
addCommand(backCommand);
addCommand(OKCommand);
setCommandListener(this);
}
public void setCell(TableCell cell) {
this.cell = cell;
deleteAll();
if (cell.cellType == CellType.STRING) {
textField = getTextField();
textField.setConstraints(TextField.ANY);
textField.setString(cell.cellText);
append(textField);
} else if (cell.cellType == CellType.NUMBER) {
textField = getTextField();
textField.setConstraints(TextField.NUMERIC);
textField.setString(cell.cellText);
append(textField);
} else {
choiceGroup=getChoiceGroup();
choiceGroup.deleteAll();
for (int i = 0; i < cell.itemOptions.length; i++) {
choiceGroup.append(cell.itemOptions[i], null);
if (cell.cellText.equals(cell.itemOptions[i])) {
choiceGroup.setSelectedIndex(i, true);
}
}
append(choiceGroup);
}
}
public TextField getTextField() {
if (textField == null) {
textField = new TextField("", "", 300, TextField.ANY);
}
return textField;
}
public ChoiceGroup getChoiceGroup() {
if (choiceGroup == null) {
choiceGroup = new ChoiceGroup("", ChoiceGroup.EXCLUSIVE);
}
return choiceGroup;
}
public void commandAction(Command com, Displayable display) {
if (com == backCommand) {
Display.getDisplay(midlet).setCurrent(previousScreen);
} else if (com == OKCommand) {
if (cell.cellType == CellType.ITEM) {
previousScreen.cells[previousScreen.focusRow][previousScreen.focusCol].cellText = choiceGroup.getString(choiceGroup.getSelectedIndex());
} else {
previousScreen.cells[previousScreen.focusRow][previousScreen.focusCol].cellText = textField.getString();
}
previousScreen.calculateTableHeight();
Display.getDisplay(midlet).setCurrent(previousScreen);
}
}
}
And I want to output data from ResultSet
A: It's still not quite clear what exactly is the problem, but it feels like you better try dropping internal for loop and moving table / cells declaration outside of while:
//...
String sID = null, sName = null, sTOE = null;
hrs.openRecordStore(hrs.getRecordnameBasic());
//hrs.listofRecord();
RecordEnumeration re;
try {
// move table / cells declaration outside of while:
int rc = hrs.getRcs().getNumRecords();
tb = new Table(mf, this, "List of record");
TableCell cells[][] = new TableCell[rc][3];
int i = 0;
re = hrs.getRcs().enumerateRecords(null, null, true);
while(re.hasNextElement()){
byte[] recordBuffer = re.nextRecord();
//... stuff that was there
sTOE = record.substring(iName + 1, iTOE);
// drop that loop - for(int i = 0; i< rc ; i++){
System.out.println("-------" + sID);
cells[i][0] = new TableCell(CellType.STRING, sID, true);
cells[i][1] = new TableCell(CellType.STRING, sName, true);
cells[i][2] = new TableCell(CellType.STRING, sTOE, true);
i++;
}
String header[] = new String[]{"ID", "Name", "TypeOfEst"};
tb.setData(new int[]{40,97,98}, header, cells);
} catch (Exception e) {
e.printStackTrace();
}
//...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Visual Studio 2010 very slow Core I7 + 16gb ram + raid 0 stripping + win7 ultimate 64bit
When I compile my web project with Visual Studio 2010 ultimate 32bit, it takes long time (the total build time!!!) and usually appends when I change something into the ASPX code.
Compiling single projects is very fast, but after compiling, it takes a lot of time to finish the overall process.
Any suggestions?
ps I already tried to disable antivirus and intellitrace
Build Summary
-------------
00:00.561 - Success - Debug Any CPU - CodcastWeb.Infrastructure.Data\CodcastWeb.Infrastructure.Data.csproj
00:00.546 - Success - Debug Any CPU - CodcastWeb.Web.Client\CodcastWeb.Web.Client.csproj
00:00.196 - Success - Debug Any CPU - CodcastWeb.Database\CodcastWeb.Database.dbproj
00:00.174 - Success - Debug Any CPU - CodcastWeb.Web.Client.Tests\CodcastWeb.Web.Client.Tests.csproj
00:00.097 - Success - Debug Any CPU - CodcastWeb.Application\CodcastWeb.Application.csproj
00:00.092 - Success - Debug Any CPU - CodcastWeb.Infrastructure.CrossCutting\CodcastWeb.Infrastructure.CrossCutting.csproj
00:00.085 - Success - Debug Any CPU - CodcastWeb.Application.DTOs\CodcastWeb.Application.DTOs.csproj
00:00.081 - Success - Debug Any CPU - CodcastWeb.Application.Tests\CodcastWeb.Application.Tests.csproj
00:00.077 - Success - Debug Any CPU - CodcastWeb.Domain\CodcastWeb.Domain.csproj
00:00.034 - Success - Debug Any CPU - CodcastWeb.DistributedServices\CodcastWeb.DistributedServices.csproj
00:00.013 - Success - Debug Any CPU - CodcastWeb.Modeling\CodcastWeb.Modeling.modelproj
Total build time: 06:27.796
========== Build: 11 succeeded or up-to-date, 0 failed, 0 skipped ==========
A: Are your projects 'Web Sites' or 'Web Applications', as the former take a lot longer to compile than the later (as the compiler goes through each file individually, getting slower the more files the site has).
Check for file sizes, are there any dependencies (such as the output from another project or library) that are getting copied the the output bin directory that have to be moved, as this could have attached resources that are getting copied - hence the slow down is a file-copy operation.
Looking at your build output, is there anything missing? Each item takes seconds, so unsure where the 6-hour total comes from. Does it seem to just hang after the last item? In which case it's sound like Visual Studio would benefit from being reinstalled.
A: If you have Layer Diagrams in your modelling project they can take a long time to validate. Try removing the model project from your solution temporarily and recompiling just to test if that is the source of the slowdown.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cannot match %2F in mod_rewrite I have a set of rewrite rules (in a .htaccess) something like this:
RewriteRule ^list/vendor/(.*)$ list.php?vendor=$1
RewriteRule ^list/product/(.*)$ list.php?product=$1
RewriteRule ^list/(.*)$ list.php?search=$1
(I don't think the first two are relevant to my question, though).
When I type in myserver.com/list/foo%2Cbar or even myserver.com/list/foo/bar, I get the results I expect: list.php is called with foo,bar and foo/bar in $_GET['search'].
But if I type in myserver.com/list/foo%2Fbar, it seems that the rule doesn't match! I get a 404 error instead. What can be going on here? Apache 2.2.14, if it matters.
(I tried in Firefox and Chrome, same results -- but it could be the browser acting up, of course).
A: Bah, I found it... Apache option AllowEncodedSlashes, which cannot be set per directory or from .htaccess, and which is Off by default.
Build-a-workaround time, if I can't get the hosting guys to turn it on in my virtual server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Can't reload self-made captcha on the page using JS <a href="javascript:void(0);" onclick="document.getElementById("capchaimage").src="captcha.php"><img id="captchaimage" src="http://website.org/captcha.php" border="0" width="70" height="20" alt="Captcha image"></a>
Captcha image successfully loads but it's not possible to reload it with the code above. What am I doing wrong?
Thanks in advance.
A: Your images are cached. Add a random string +(new Date).getTime() to at the query string after the image URL:
document.getElementById("capchaimage").src="captcha.php?"+ (new Date).getTime();
A: You are replacing image src with exactly the same string.
You can try to work around that by using some "fake" arguments:
http://website.org/captcha.php?fake=234342412341
That way the browser will be forced to reload. The argument needs to be different each time of course (random, or just counter)
A: Look carefully at your code:
<a href="javascript:void(0);" onclick="document.getElementById("capchaimage").src="captcha.php"><img id="captchaimage" src="http://website.org/captcha.php" border="0" width="70" height="20" alt="Captcha image"></a>
^ ^
I'm surprised you are not getting JavaScript syntax errors. My advise is to move code to external functions to avoid the need of complex escaping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Full text search solutions for Java? There's a large set of entities of different kinds:
interface Entity {
}
interface Entity1 extends Entity {
String field1();
String field2();
}
interface Entity2 extends Entity {
String field1();
String field2();
String field3();
}
interface Entity3 extends Entity {
String field12();
String field23();
String field34();
}
Set<Entity> entities = ...
The task is to implement full text search for this set. By full text search I mean I just need to get entities that contain a substring I'm looking for (I don't need to know exact property, exact offset of where this substrig is, etc). In current implementation the Entity interface has a method matches(String):
interface Entity {
boolean matches(String text);
}
Each entity class implements it depending on its internals:
class Entity1Impl implements Entity1 {
public String field1() {...}
public String field2() {...}
public boolean matches(String text) {
return field1().toLowerCase().contains(text.toLowerCase()) ||
field2().toLowerCase().contains(text.toLowerCase());
}
}
I believe this approach is really awful (though, it works). I'm considering using Lucene to build indexes every time I have a new set. By index I mean content -> id mappings. The content is just a trivial "sum" of all the fields I'm considering. So, for Entity1 the content would be concatenation of field1() and field2(). I have some doubts about the performance: building the index is often quite an expensive operation, so I'm not really sure if it helps.
Do you have any other suggestions?
To clarify the details:
*
*Set<Entity> entities = ... is of ~10000 items.
*Set<Entity> entities = ... is not read from DB, so I can't just add where ... condition. The data source is quite non-trivial, so I can't solve the problem on its side.
*Entities should be thought of as of short articles, so some fields may be up to 10KB, while others may be ~10 bytes.
*I need to perform this search quite often, but both the query string and original set are different every time, so it looks like I can't just build index once (because the set of entities is different every time).
A: I would strongly consider using Lucene with SOLR. http://lucene.apache.org/java/docs/index.html
A: For such a complex Object domain, you can use lucene wrapper tool like Compass which allow quickly map you object graph to lucene index using the same approach as ORM(like hibernate)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP Remote Sudo Script Execution I want a PHP script to cause a shell script to execute on a remote server as root. The script needs to execute sudo commands itself so it needs to be executed as root.
Any Ideas?
I tried having PHP ssh login and execute with sudo but it was too slow.
(I have Ubuntu 10.04 & PHP5 on both servers)
A: SSH shouldn't be to slow unless your running many individual commands. If it is slow either the systems are under high load or you have reverse DNS problems. You could try setting UseDNS no in /etc/ssh/sshd_config and restart sshd if that makes it faster DNS is the problem.
The script needs to execute sudo commands itself so it needs to be executed as root.
Doesn't make sense if the script is running as root it doesn't need to use sudo.
A: I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd('yourFirstCommand');
$return2 = $shell->exeCmd('yourSecondCommand');
//the return will be a string containing the return of the script
echo $return1;
echo $return2;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange behaviour with directories and FileTest.directory I am working on this ruby script where I have to recursively look inside all the subdirectories starting at a particular directory. But for some reason FileTest.directory? only seems to recognise a directory if it is located in the same folder as the script
def files(start)
dir = Dir.open (start)
dir.each do |x|
p "#{x}: #{FileTest.directory?(x)}"
if FileTest.directory?(x) && x != '.' && x != '..'
start = x
files (start)
end
end
end
files '.'
Supposed my directory structure is as follows: In the current dir I have a file a.txt and two directories called 'b' and drct2. 'b' contains another directory 'c' and 'drct' contains another directory 'dir3'. The code above when run from the current directory recognizes 'b' & 'drct2' as directories but not their sub directories. Can anyone think of a reason why FileTest.directory? is behaving this way?
A: You need to give a full path to the FileTest as it works relative to your current dir
So if you have dira -> dirb -> filec you need to run:
FileTest.directory?('dira/dirb')
and not just
FileTest.directory?('dirb')
BTW I suggest you look into Dir.glob('**/*') method - there is a good chance it does what you need to do out-of-the-box.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Coding Style Standards for Android I would like to know if there is some standard code styling for Android(maybe a book?) (styling XML , Java programming , file naming , etc...)
A: @inazaruk: The codesearch link for android-formatting.xml is now obsolete. I found the file at geobeagle.
Funny thing is that the file is also mentioned at android source (Using Eclipse) with no further linking :D (Most probably it was linking to the obsolete one).
One more file mentioned at android's Using Eclipse and found at geobeagle ;-) is android.importorder.
(This should be a comment but I don't have 50pt yet :/ Sorry)
Edit: March 2015
As Google Code is fading away you may find the two file at bitbucket.
A: please refer:
https://www.fer.unizg.hr/download/repository/ProjectConventions-_Java_Android.pdf
A: There is a good description of code style rules here.
If you want to enforce this rules without remembering all of them, and you are using eclipse then you can use formatting rules provided by Android team: android-formatting.xml. Just import it into eclipse using Preferences->Java->Code Style->Formatter, click Import.
A: There is a ton of information available here:
http://source.android.com/source/code-style.html
A: I was looking for something like that and found this. We are using it combined with some of our own conventions. Very helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
} |
Q: Gitosis on Dotcloud Is it possible to setup gitosis on dotcloud? If so, what are the steps? I tried to follow this but it wasn't very comprehensive.
Thanks!
A: You can try this recipe:
https://github.com/jpetazzo/gitosis-on-dotcloud
Sorry, it is not documented yet, but the quickstart informations in the README.rst file should hopefully be enough to use it :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Compare static addressing and import for extends/implements Is there any difference between using
public ClassName extends some.package.Class implements another.package.Interface {}
and
import some.package.Class;
import another.package.Interface;
public ClassName extends Class implements Interface {}
when talking about performance, compatibility, etc..
A: There is no difference. The byte code is identical. All this happens at compile time, there is zero performance impact. You should make this decision based solely on your evaluation of readability.
A: It's a compile-time feature, so it's related to performance by no means. From compatibility standpoint, the only idea is that if you have 2 packages with classes named Entity and there's a module where you'd like to use both of them, having import ... means only one of these entities would be available using it's unqualified name. But it's more to maintenance than to compatibility.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: PHP Path to Include Files I have a site with an index.php.
The index.php has a number of include files like
<?php include_once('scripts/php/index_mainImageJoin.php');?>
I've created a new folder off the root called 'extrapages' and I'm going to have pages in there that have information relating to the site. I've added the include_once files like above and change the path and these hook up fine.
The problem I'm find is paths within the include files fail. eg: if an image or another include file is within the include it fails when run from the 'extrapages' folder. Pathing issue.
Is there a good way to deal with this?
Can I change/set the path to the site root (www) for pages under 'extrapages' to one folder down by chance?
I could move these pages onto the root and they would run fine but I really don't want all the clutter on the root of the site.
Any ideas & thx
A: The key to any path problem is called absolute path
*
*while creating hyperlinks for your site (including image sources), always start it from / followed by full correct path. And it never fail you.
*same for the filesystem calls: always use absolute path. Your server usually provides you with very handy variable called $_SERVER['DOCUMENT_ROOT'] contains the point where filesystem meet web-server, pointing to your web root directory.
So, when called from anywhere in your site,
include $_SERVER['DOCUMENT_ROOT'].'/scripts/php/index_mainImageJoin.php';
will point always to the same location
A: you should use dirname and the __FILE__ by using this both constant you should be able to include file relative to the current file instead of the php script called by the web server.
for example
include_once dirname(__FILE__) . '/../include.php';
dirname: would return the directory part of a path
__FILE__: is a magic constant, it's replaced by the path of the current file.
The only problem with doing such thing you lock the structure of your project but most of the times it's acceptable.
A: Just add your include path once (somewhere at the beginning or in a config file) using set_include_path(), see the manual. Use an absolute path (not relative; can utilize dirname(__FILE__)) and it should work all the time.
A: If you're on PHP 5.3.0 or newer, you can (instead of what RageZ) suggested, use just __DIR__ (a newly defined magic constant).
example:
include __DIR__ . '/../include.php';
Now, this doesn't help when you want to avoid ../ and mapping out your includes. There's a better way to do it, though - in all front-end files (which should be the ONLY user-accessible PHP files) you define a constant which provides the root path of your script (and not of the current file).
For example:
index.php
<?php
define('MYSCRIPT_ROOT', dirname(__FILE__));
// or in php 5.3+ ...
define('MYSCRIPT_ROOT', __DIR__);
// ... do some stuff here
include MYSCRIPT_ROOT . '/includes/myinclude.php';
Now let's say we want to include a file in our includes directory.
Let's do it in includes/myinclude.php, and include the file includes/myotherinclude.php
includes/myinclude.php
<?php
if(!defined('MYSCRIPT_ROOT')) exit; // prevent direct access - ALWAYS a good idea.
// ... do stuff here or something
include MYSCRIPT_ROOT . '/includes/myotherinclude.php';
Keep in mind that the include paths should be directly relative to the root directory of the project itself, not to just one of the front-end files. If you have a front-end file in a subdirectory, you need to back out to the project root itself when defining the constant.
example:
subdirectory/index.php
index.php
<?php
define('MYSCRIPT_ROOT', dirname(dirname(__FILE__)));
// or in php 5.3+ ...
define('MYSCRIPT_ROOT', dirname(__DIR__));
// ... do some stuff here
include MYSCRIPT_ROOT . '/includes/myinclude.php';
All we do here is add a dirname() call, which takes off a directory in the path.
See: http://us.php.net/manual/en/function.dirname.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dismiss the keyguard in a Service? how to dismiss the keyguard in a Service?
Flag.Dismiss.keyguard cannot be use as there is no window - am I right?
A: Yes you are correct. You have to either send a call back message to an activity to get the window or apply a dummy activity. Answer to your question Here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Covering union of intervals I am trying to implement a solution to a problem that boils down to interval covering.
by googling I know usually this is solved using a greedy approach, but my own first idea was to use breadth first search. I am starting out assuming the intervals's union is an interval and all intervals are closed. The problem is:
Given k closed intervals find a subset with as few elements as
possible such that every point in an interval from the original collection
is in an interval in the found subset.
My idea is to work in a graph where the intervals are the vertices and two vertices
form an undirected edge if the corresponding intervals overlap. In the special case
where the union is an interval I can pick nodes containing the end and start point
having maximal length and then a path between these of minimal length is an optimal solution.
My problem is: How do I build the interval graph efficiently so that I avoid looking at each pair of intervals. I have tried different ways of sorting the intervals but still I seem not get away from quadratic time.
A: I think that in the worst case, you can't get away from quadratic time. That's because the number of edges may be quadratic.
But normal shortest-path algorithm (like Dijkstra) isn't needed here. Start with the first interval (the one with lowest start). Then choose an interval that starts after this one and whose end is the highest. Repeat until you reach end.
A: I am answering this question because previous entries do not answer it correctly or are incomplete, to the best of my knowledge.
There is an algorithm that runs on O(N log N), where N is the number of closed segments:
*
*Order in ascending order the segments by the left end, breaking ties by giving priority to those with the largest right end (breaking ties really does not matter).
*Apply a greedy strategy from "left to right":
2.1 while not missing a point, force to choose the segment with largest left end
2.2 If there is a missing point, there is no solution.
2.3 Otherwise, go to 2.1
The time complexity of step 1 is O(N log N) and the time complexity of step 2 is O(N). Hence, this greedy algorithm takes O(N log N) time.
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iOS / Cocoa / Data interpretation with NSString initWithData to build a string drives me crazy I have a very simple callback called when a HTTP request has just been completed through a NSURLConnection object (connectionDidFinishLoading). This code just turns raw 7-bit encoded data read from a remote file into a NSString.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *string = [[NSString alloc] initWithData:mReceivedData encoding:NSASCIIStringEncoding];
NSLog(@"string = %@", string);
}
The issue is that string is NIL. I then suspected a bad conversion due to the presence of bad bytes (>0x80) but all my bytes read are pure 7-bit encoded ASCII data:
(gdb) po mReceivedData
<2366696c 65566572 73696f6e 0a310a23 66696c65 54797065 0a626964 4465660a 23657865 72636973 654c6576 656c0a31 0a23636f 6c756d6e 54657874 0a537564 2f4f7565 73742f4e 6f72642f 4573740a 23636f6c 756d6e43 6f6c6f72 0a677265 656e2f72 65642f67 7265656e 2f726564 0a236269 6456616c 7565730a 2a2f3144 2f582f2d 0a3f2f2a 2f2a2f2a 0a2a2f2a 2f2a2f2a 0a2a2f2a 2f2a2f2a 0a236164 76696365 4c696e65 310a5370 6f75746e 696b2028 52c3a970 6f6e6461 6e740a23 61647669 63654c69 6e65320a 617072c3 a8732069 6e746572 76656e74 696f6e0a 2368616e 64436172 64730a4a 2f392f36 2f350a38 2f350a41 2f580a4b 2f372f36 2f332f32 0a237363 6f726547 7269640a 32532f31 300a3343 2f360a31 532f330a 32432f30 0a23616e 73776572 436f6d6d 656e7473 0a32532f 4f75693a 20646520 3820c3a0 20313020 706f696e 74732065 74203420 63617274 657320c3 a020532e 0a33432f 5072696f 726974c3 a920c3a0 206c6120 6d6f7965 6e6e652e 0a31532f 436f6d6d 65206176 6563207a c3a9726f 20706f69 6e74203f 0a32432f 4168206e 6f6e2021 0a236d61 696e436f 6d6d656e 740a4c65 20636f6d 6d656e74 61697265 20646520 4d696368 656c2042 65737369 732e0a0a 456e2072 c3a9706f 6e736520 61752063 6f6e7472 652064e2 80996170 70656c2c 20696c20 66617574 20646f6e 6e657220 6c652070 6c65696e 20646520 7361206d 61696e2e 20416e6e 6f6e6365 72203153 206d6f6e 74726572 61697420 64652030 20c3a020 3720706f 696e7473 202872c3 a9706f6e 73652066 6f7263c3 a965292e 0a0a4963 692c2069 6c206661 75742073 61757465 7220c3a0 2032532c 20656e63 68c3a872 65207175 69206e65 2070726f 6d657420 70617320 63696e71 20636172 74657320 65742071 75692064 c3a96372 69742075 6e206a65 75206465 203820c3 a0203130 20706f69 6e747320 482028c3 a0207061 72746972 20646520 31312070 6f696e74 732c2063 e2809965 73742075 6e206375 652d6269 64206f75 20756e20 73617574 20c3a020 6c61206d 616e6368 65207175 69207365 72612063 686f6973 69292e>
Those raw data are exactly the same as bytes contained into the remote file, so there are no polluting bytes.
I also tried to play with UTF-8 conversion but this is still the same issue.
I have another way of doing which would be to build a C string from those raw data and to build a NSString with something like NSStringWithCString... but I consider this is very ugly and I really would like to use the Cocoa API designed for such a purpose. There is no reason why I should not be able to use Cocoa power for such a basic task.
Do I totally miss something ?
Many thanks,
Franz
A: Despite your insistance that
All 7-bit bytes shown here have values < 0x80
a quick glance shows bytes 0x99 0xa8 0xa9 0xc3 0xa0 0xe2 and more. So this isn't valid ascii encoded as 8bit bytes.
If it really is 7bit values (not each encoded in an 8bit byte) then the string doesn't start
#file
as you suggest, but
Yj-
Which i don't think is what you are expecting.
So it seems that your file isn't ascii or isn't being transmitted as ascii. Either way your problems start before it gets to Cocoa.
A: Sometimes, gdb is not your friend.
po string does not work and says:
(gdb) po string
Unable to access variable "string"
Can't print the description of a NIL object.
But if I print it with
NSLog(@"string = %@", string);
then it is properly printed and string contains the accented characters... and in fact the file is properly decoded when using the NSUTF8StringEncoding parameter:
NSString *string = [[NSString alloc] initWithData:mReceivedData encoding:NSUTF8StringEncoding];
NSLog(@"string = %@", string);
Hard to believe that gdb can provide erronous information about string. I am only half satisfied of this explanation. I would like to understand why gdb provides such an information about string.
EDIT: I finally set the "Run" action to debug instead of release by Product -> Manage schemes and the debug information is properly displayed by gdb.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Debugging iphone application crashes When testing my iPhone application on the actual device after a while the application seems to crash/exit by itself. It does not crash at any particular point but instead crashes after a while of use, for example : i can use the application and then leave it idle. It will crash. How can i debug the problem and what could the cause be?
A: remove the Break points and disable the breakpoints
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add support for OpenSSL in PHP without recompiling Is this possible? I'm on Mac OSX.
I'm using a custom install already, with the Mac OSX default*ish* apache.
A: I was able to do this by:
cd {php_dir}/ext/openssl
phpize
./configure
make && make install
Restart apache
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: google maps infowindows is always attached to the first marker i'm looping over an array to create markers and infowindows but the infowindow is always attached to the first marker... (even if you click another marker)
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(50.902946,4.241436),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
setMarkers(map, shops);
}
var shops = [['United Brands', 51.218342, 4.405464, 4, 'ZZEERRR'],['United Brands', 51.162582, 4.991303, 4, 'ZZEERRR'],['United Brands Hasselt', 50.929314, 5.339501, 4, 'ZZEERRR'],['United Brands Oud-Turnhout', 51.320259, 4.974206, 4, 'ZZEERRR'],['United Brands Leuven', 50.879509, 4.705221, 4, 'ZZEERRR'],['United Brands Veurne', 51.083534, 2.644152, 4, 'ZZEERRR'],['United Brands Wijnegem', 51.222084, 4.498419, 4, 'ZZEERRR'],['United Brands Knokke', 51.340641, 3.234586, 4, 'ZZEERRR'],['United Brands Aalst', 50.938343, 4.034963, 4, 'ZZEERRR'],['UBextreme', 51.052570, 3.723077, 4, 'ZZEERRR'],['UBextreme', 51.218273, 4.402394, 4, 'ZZEERRR']];
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var shop = locations[i];
var myLatLng = new google.maps.LatLng(shop[1], shop[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
animation: google.maps.Animation.DROP,
title: shop[0],
zIndex: shop[3],
clickable: true
});
var infowindow = new google.maps.InfoWindow({ content: shop[4] });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
initialize();
A: try this:
var map;
function initialize(){
...
map = ...
}
The variable "map" now is out of setMarker's scope
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bbc beta panorama with jquery Just been looking at the bbc's beta homepage http://beta.bbc.co.uk/
and thought the panorama looked decent.
It'd make an interesting home page for a video site.
Has anyone seen something similar (open source) and preferably built with jQuery?
If not, any pointers on how best to achieve this without loading all the images at once (to reduce load time) but then load them once rendered so that the slide left or right works without delay...?
A: It's called carousel - there are million implementations out there for it. Just google for jquery carousel:
http://sorgalla.com/projects/jcarousel/examples/static_circular.html
http://www.pixelzdesign.com/blog_view.php?id=55
http://www.thomaslanciaux.pro/jquery/jquery_carousel.htm
And so on...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why this warning comes in making stand-alone .exe from my .m & .fig file ? see i have one .m file & .fig file for gui feature associated with that .m file now for making standalone .exe file for that .m file
i am using
mcc -m -mv jig322.m jig322.fig
after doing this i get warning like this
Warning: No matching builtin function available for C:\MATLAB7\toolbox\simulink\simulink\set_param.bi
i am not getting why this warning comes ?
& after this all ma exe becomes ready but it doesn't work 100% by executing some function it gets crash ?
why this all is happening here? how can i make my exe to better work?
A: According to MathWorks Support, you need to comment out the following two lines
set_param(0,'PaperType',defaultpaper);
set_param(0,'PaperUnits',defaultunits);
from C:\MATLAB7\toolbox\compiler\deploy\matlabrc.m
and then call rehash toolboxcache at the MATLAB prompt. See the above link for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Insert N random values into table I need to insert @N rows with random float values into one table and use IDs of every new inserted row for another INSERT. All this I need to do in stored procedure. For example:
CREATE PROCEDURE Proc
@N int
AS
-- START LOOP, REPEAT @N TIMES
INSERT INTO [T1]
([Value])
VALES
(<random_float>)
INSERT INTO [T2]
([ValueID])
VALUES
(@@IDENTITY)
-- END LOOP
END
GO
Thanks in advance.
A: No loops, one insert
;WITH cte AS
( --there are easier ways to build a numbers table
SELECT
ROW_NUMBER() OVER (ORDER BY (select 0)) AS rn
FROM
sys.columns c1 CROSS JOIN sys.columns c2 CROSS JOIN sys.columns c3
)
INSERT INTO [T1] ([Value])
OUTPUT INSERTED.ID INTO T2 -- direct insert to T2
SELECT RAND(CHECKSUM(NEWID()))
FROM cte
WHERE rn <= @N;
A: It's not entirely clear what you are trying to do. Did you mean something like this:
create table dbo.RandomTable
(
rowid int not null PRIMARY KEY,
pure_random float null,
)
declare @row int
set @row = 1
while (@row <= @N)
begin
insert into dbo.RandomTable (rowid, pure_random)
values (@row, rand())
set @row = @row + 1
end
[I'm not advocating the use of a loop; it's not the most efficient way of doing this. It's just that's the form the poster was asking for...]
A: CREATE TABLE [T1]
(
[ValueID] INT IDENTITY(1,1),
[Value] FLOAT
)
GO
CREATE TABLE [T2]
(
[ValueID] INT
)
GO
CREATE PROCEDURE [Proc]
@N int
AS
BEGIN
DECLARE @i INT = 0;
WHILE (@i < @N)
BEGIN
INSERT INTO [T1]
([Value])
SELECT RAND()
INSERT INTO [T2]
([ValueID])
VALUES
(SCOPE_IDENTITY())
SET @i += 1
END
END
GO
TRUNCATE TABLE T1
TRUNCATE TABLE T2
EXEC [Proc] @N = 10
See WHILE (Transact-SQL), and SCOPE_IDENTITY (Transact-SQL).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery - get character pressed - REGARDLESS of Keyboard I am trying to retrieve the character inserted into a textfield/input with jQuery.
I use the usual:
var character = String.fromCharCode( e.keyCode || e.which );
method, but the only problem occurs when I use a different keyboard layout which I just noticed.
So for example, on a Standard US Keyboard it works perfectly. On a German Keyboard for instanece, if I have the language set to English - basically rendering it a standard US Keyboard, when I press the characters equivalent to :;'\,./[]=-, I get the German characters I actually see on my keyboard (although the English equivalent of then is added to the input).
Example: if I console.log( character ) for the folowing sentence I get:
*
*In the input: []\';/.,
*In the console: ÛݺÞܼ¾¿
My obvious question is, how can I make sure to get the true character inserter?
A: What you can do is making the character appear in a hidden textbox and fetch the actual value. That way, you will get the character. You are currently passing the key code as if it is a character code. They are not the same.
http://jsfiddle.net/RQQpT/
(function() {
var input = $("<input>").appendTo('body') // an hidden input element
.css({ position: "absolute",
left: -500,
top: -500 });
$('body').bind({ keydown: function(e) {
input.focus(); // make characters appear in input element
},
keyup: function() {
var value = input.val(); // get value when key pressed
input.val(""); // reset value of input element
if(value) {
alert(value); // if there is a value, display it
}
}
});
})();
A: The keypress event is different from the keyup and keydown events as it contains the key actually pressed. Try using that instead. Check it out with this snippet:
$('body').keypress(function(e){
console.log('keypress', String.fromCharCode( e.which ));
});
$('body').keyup(function(e){
console.log('keyup', String.fromCharCode( e.which ));
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Trying to recover sites from a .htaccess redirect badware on Wordpress Forgive me if this is a noob question, but I'm honestly stumped.
My site, hosted on Wordpress, has been blacklisted because of some badware. So far, I've tried unmaskparasites.com, google webmaster tools, and sucuri sitecheck. I've narrowed down (what I think is) most of the problem to some condition redirects in the .htaccess. This is what I found:
ErrorDocument 400 http://securesoftconnection.ru/aposte/index.php
ErrorDocument 401 http://securesoftconnection.ru/aposte/index.php
ErrorDocument 403 http://securesoftconnection.ru/aposte/index.php
ErrorDocument 404 http://securesoftconnection.ru/aposte/index.php
ErrorDocument 500 http://securesoftconnection.ru/aposte/index.php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond % {HTTP_REFERER} .*google.* [OR]
RewriteCond % {HTTP_REFERER} .*ask.* [OR]
RewriteCond % {HTTP_REFERER} .*yahoo.* [OR]
RewriteCond % {HTTP_REFERER} .*baidu.* [OR]
RewriteCond % {HTTP_REFERER} .*youtube.* [OR]
RewriteCond % {HTTP_REFERER} .*wikipedia.* [OR]
RewriteCond % {HTTP_REFERER} .*qq.* [OR]
RewriteCond % {HTTP_REFERER} .*excite.* [OR]
RewriteCond % {HTTP_REFERER} .*altavista.* [OR]
RewriteCond % {HTTP_REFERER} .*msn.* [OR]
RewriteCond % {HTTP_REFERER} .*netscape.* [OR]
RewriteCond % {HTTP_REFERER} .*aol.* [OR]
RewriteCond % {HTTP_REFERER} .*hotbot.* [OR]
RewriteCond % {HTTP_REFERER} .*goto.* [OR]
RewriteCond % {HTTP_REFERER} .*infoseek.* [OR]
RewriteCond % {HTTP_REFERER} .*mamma.* [OR]
RewriteCond % {HTTP_REFERER} .*alltheweb.* [OR]
RewriteCond % {HTTP_REFERER} .*lycos.* [OR]
RewriteCond % {HTTP_REFERER} .*search.* [OR]
RewriteCond % {HTTP_REFERER} .*metacrawler.* [OR]
RewriteCond % {HTTP_REFERER} .*bing.* [OR]
RewriteCond % {HTTP_REFERER} .*dogpile.* [OR]
RewriteCond % {HTTP_REFERER} .*facebook.* [OR]
RewriteCond % {HTTP_REFERER} .*twitter.* [OR]
RewriteCond % {HTTP_REFERER} .*blog.* [OR]
RewriteCond % {HTTP_REFERER} .*live.* [OR]
RewriteCond % {HTTP_REFERER} .*myspace.* [OR]
RewriteCond % {HTTP_REFERER} .*mail.* [OR]
RewriteCond % {HTTP_REFERER} .*yandex.* [OR]
RewriteCond % {HTTP_REFERER} .*rambler.* [OR]
RewriteCond % {HTTP_REFERER} .*ya.* [OR]
RewriteCond % {HTTP_REFERER} .*aport.* [OR]
RewriteCond % {HTTP_REFERER} .*linkedin.* [OR]
RewriteCond % {HTTP_REFERER} .*flickr.*
RewriteRule ^ (.*)$ http: //securesoftconnection.ru/aposte/index.php [R=301,L]
</IfModule>
So, I've obviously gathered that this is not cool. I tried editing the .htaccess to the standard wordpress format:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
But it didn't work. Is there a better way to fix this? Or is just not worth it? I don't know much about .htaccess, so I'm kind of at a loss. I'm also now having trouble uploading the new .htaccess file.
Any help you have about resetting a wordpress .htaccess file, getting rid of badware, or anything else that I might not even know about yet, I'd really appreciate it.
A: Delete .htaccess and then reset permalinks in WP to regenerate .htaccess with the correct rewrite block.
And see FAQ: My site was hacked « WordPress Codex and How to completely clean your hacked wordpress installation and How to find a backdoor in a hacked WordPress and Hardening WordPress « WordPress Codex. Tell your host. Change all passswords. Scan your own PC for spyware.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to specify a default value for VARIANT_BOOL? MS IDL has syntax for specifying a defaultvalue for parameters.
I tried to specify a default value for a function that accepts a VARIANT_BOOL:
[id(42)] HRESULT Foo([in, defaultvalue(VARIANT_TRUE)] VARIANT_BOOL bar);
And got the following error message:
error MIDL2035 : constant expression expected
What is the correct syntax for specifying that the default value of bar should be VARIANT_TRUE?
A: VARIANT_TRUE is #defined in WTypes.h. You can't directly use it in your .idl. The common approach is to simply use the value directly, like it is done in mshtml.idl for example:
[id(42)] HRESULT Foo([in, defaultvalue(-1)] VARIANT_BOOL bar);
Or you can add a #define to your .idl if you prefer, put it somewhere near the top:
#define VARIANT_TRUE -1
#define VARIANT_FALSE 0
A: Although one should not mix up bool, BOOL and VARIANT_BOOL it appears that in idl BOOL is interpreted as a VARIANT_BOOL value.
[id(42)] HRESULT Foo([in, defaultvalue(TRUE)] VARIANT_BOOL bar);
When called from VBScript with no parameter specified this reaches the C++ code as -1.
I'm not sure which way is more idiomatic TRUE or as @Hans suggested -1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Command line arguments in Visual C++ in VS2010 How do I access the command line argument that I set in my project.
for example if I give following input to command line "abc def ghi"
then how do I access them using argc &/or argv.
I am getting some integer values if I am accessing them via argv[i] or *argv[i]
Thanks.
A: You can access them like in this example:
#include <iostream>
int main(int argc, char* argv[] ) {
for(int i=0;i<argc;i++) {
std::cout<<argv[i];
}
}
The cause of the error you are experiencing probably is that you use the TCHAR form of the main function:
int _tmain(int argc, _TCHAR* argv[]);
In Visual C++ per default UNICODE is defined. Therefore you have to use std::wcout for output instead of std::cout.
This is the way it probably will work:
for(int i=0;i<argc;i++) {
std::wcout<<argv[i];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need help with jQuery hide/show I'm using jQuery to show and hide elements upon user interaction. The following code works fine:
<script type="text/javascript">
$(document).ready(function () {
$('.c').hide();
$('.b').click(function() {
var t = $(this);
t.parent().find('.c').show();
});
});
</script>
<div class="a">
<a href="#" class="b">Show</a>
<div class="c">This is hidden text</div>
</div>
But when i put the link inside a div tag the code does not work. I couldn't figure out the problem. So I'm expecting some help.
<script type="text/javascript">
$(document).ready(function () {
$('.c').hide();
$('.b').click(function() {
var t = $(this);
t.parent().find('.c').show();
});
});
</script>
<div class="a">
<div class="d"><a href="#" class="b">Show</a></div> //if i place it inside div it doesn't work
<div class="c">This is hidden text</div>
</div>
Can anyone point out why it's not working??
A: $(this).parent() is a div.d, not div.a, so it doesn't contain div.c, that's why find('.c') wont give you any elements.
A: As the containing div is no longer the parent of the link, it doesn't work to use .parent() to find it. Use .closest('.a') to find it:
t.closest('.a').find('.c').show();
This will work to find the element with class c in the same containing element, regarldess of what elements you put in there.
A: Sure, you are doing a find() from the wrong place (div class=d) so you can't find (div class=c) from there.
Why do you need that anyway? Wouldn't it be simpler to just:
$('.c').show()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sizing in Android In my new application I want to have one Linear Layout width height: XXXdip and green background. Than show a scrollview be shown in the middle an at the Buttom of the viw there should be two Buttons like "Next" and "Back". The Scrollview contains many text.
In every tries the buttons wouldn't be shown.
I hope you could understand my bad english discription.
Here is my code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom|top">
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/linearLayout8">
<LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="wrap_content" android:background="@color/gruen" android:id="@+id/LinearLayout01">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/weiss" android:id="@+id/TextView06" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/tx_einstellungen"></TextView>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="wrap_content" android:background="@color/gruen" android:id="@+id/linearLayout2">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/weiss" android:id="@+id/first_titel" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/app_name"></TextView>
</LinearLayout>
<ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/scrollView1">
<LinearLayout android:id="@+id/linearLayout11" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent" android:paddingBottom="0dip" android:layout_height="wrap_content">
<ViewFlipper android:layout_width="fill_parent" android:id="@+id/viewFlipperBalling" android:layout_height="fill_parent">
<LinearLayout android:paddingLeft="10dip" android:paddingRight="10dip" android:orientation="vertical" android:layout_width="fill_parent" android:paddingTop="10dip" android:layout_height="wrap_content" android:id="@+id/viewThanks">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView1" android:text="@string/thanks_titel"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView2" android:textStyle="bold" android:text="@string/app_name"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="10dip" android:id="@+id/textView7"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/imageView1" android:src="@drawable/meinaquarium" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="wrap_content" android:layout_height="10dip" android:id="@+id/textView8"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/thanks_satz1" android:text="@string/thanks_satz1"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="20dip" android:id="@+id/textView3"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView4" android:text="@string/thanks_satz2"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="20dip" android:id="@+id/textView5"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView6" android:textStyle="bold" android:text="@string/thanks_satz3"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView9" android:textSize="10dip" android:text="@string/thanks_satz4"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="10dip" android:id="@+id/textView10"></TextView>
</LinearLayout>
<LinearLayout android:paddingLeft="10dip" android:paddingRight="10dip" android:orientation="vertical" android:layout_width="fill_parent" android:paddingTop="10dip" android:layout_height="wrap_content" android:id="@+id/viewEinheiten">
<RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/radioGroup1">
<RadioButton android:id="@+id/radio0" android:text="@string/tx_si_einheiten" android:layout_width="fill_parent" android:checked="true" android:layout_height="wrap_content" android:gravity="center"></RadioButton>
<TextView android:id="@+id/TextView04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_empholen_fuer_europa"></TextView>
<TextView android:id="@+id/textView13" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_verwendete_einheiten"></TextView>
<TextView android:id="@+id/textView14" android:layout_width="wrap_content" android:layout_height="50dip"></TextView>
<RadioButton android:id="@+id/radio1" android:text="@string/tx_andere_einheiten" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center"></RadioButton>
<TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_verwendet_in_us_uk"></TextView>
<TextView android:id="@+id/textView15" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_verwendete_einheiten_us_uk"></TextView>
</RadioGroup>
</LinearLayout>
<LinearLayout android:paddingLeft="10dip" android:paddingRight="10dip" android:orientation="vertical" android:layout_width="fill_parent" android:paddingTop="10dip" android:layout_height="wrap_content" android:id="@+id/viewAquarium">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView16" android:textStyle="bold" android:text="@string/tx_name_bezeichnung"></TextView>
<EditText android:layout_width="250dip" android:layout_height="wrap_content" android:id="@+id/et_name_erstes_aquarium"></EditText>
<TextView android:layout_width="wrap_content" android:layout_height="25dip" android:id="@+id/textView17"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView18" android:textStyle="bold" android:text="@string/tx_gesamt_wasservolumen"></TextView>
<LinearLayout android:gravity="right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/linearLayout5">
<TextView android:layout_width="100dip" android:layout_weight="1" android:layout_height="wrap_content" android:id="@+id/textView25"></TextView>
<EditText android:layout_width="100dip" android:layout_weight="1" android:layout_height="wrap_content" android:inputType="number" android:id="@+id/et_first_beckenvolumen"></EditText>
<TextView android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content" android:id="@+id/textView23" android:text="@string/tx_einheit_liter"></TextView>
</LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView19" android:text="@string/tx_aquarium_einstellungen_text1"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="25dip" android:id="@+id/textView20"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView21" android:textStyle="bold" android:text="@string/tx_volumen_wasserwechsel"></TextView>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/linearLayout3">
<TextView android:layout_width="100dip" android:layout_weight="1" android:layout_height="wrap_content" android:id="@+id/textView26"></TextView>
<EditText android:layout_width="100dip" android:layout_weight="1" android:layout_height="wrap_content" android:inputType="number" android:id="@+id/et_first_wasserwechsel"></EditText>
<TextView android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content" android:id="@+id/textView24" android:text="@string/tx_einheit_liter"></TextView>
</LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView22" android:text="@string/tx_aquarium_einstellungen_text2"></TextView>
</LinearLayout>
<LinearLayout android:paddingLeft="10dip" android:paddingRight="10dip" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/viewMessmethode">
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout6">
<RadioGroup android:layout_width="220dip" android:layout_height="wrap_content" android:id="@+id/radioGroup2">
<RadioButton android:id="@+id/radio_messmethode_salzgehalt_salinitaet" android:textStyle="bold" android:text="@string/tx_salinitaet" android:layout_width="fill_parent" android:checked="true" android:layout_height="wrap_content" android:gravity="center"></RadioButton>
<TextView android:id="@+id/textView27" android:textSize="11dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_messgerat_refr"></TextView>
<TextView android:id="@+id/textView28" android:textSize="11dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_messaretn_satz2"></TextView>
<RadioButton android:id="@+id/radio_messmethode_salzgehalt_dichte" android:textStyle="bold" android:text="@string/tx_dichte" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center"></RadioButton>
<TextView android:id="@+id/textView29" android:textSize="11dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_messart_satz4"></TextView>
<RadioButton android:id="@+id/radio_messmethode_salzgehalt_relative_dichte" android:textStyle="bold" android:text="@string/tx_rel_dichte" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center"></RadioButton>
<LinearLayout android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="@+id/linearLayout10">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView11" android:text="@string/bezogen_auf_"></TextView>
<EditText android:text="25" android:layout_width="60dip" android:layout_weight="1" android:layout_height="43dip" android:inputType="numberDecimal" android:id="@+id/input_Bezugstemperatur"></EditText>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView12" android:text="@string/_c_"></TextView>
<TextView android:layout_width="5dip" android:layout_height="wrap_content" android:id="@+id/textView34"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/info_relative_dichte" android:src="@drawable/info" android:onClick="info" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
<TextView android:id="@+id/textView32" android:textSize="11dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_messart_satz5"></TextView>
<RadioButton android:id="@+id/radio_messmethode_salzgehalt_leitwert" android:textStyle="bold" android:text="@string/tx_leitwert" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center"></RadioButton>
<TextView android:id="@+id/textView36" android:textSize="11dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tx_messart_satz6"></TextView>
</RadioGroup>
<LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="wrap_content" android:id="@+id/linearLayout4">
<ImageView android:layout_width="wrap_content" android:id="@+id/imageView5" android:src="@drawable/salinitaet" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="wrap_content" android:layout_height="35dip" android:id="@+id/textView30"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/imageView2" android:src="@drawable/dichte" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="wrap_content" android:layout_height="35dip" android:id="@+id/textView31"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/imageView4" android:src="@drawable/reldichte" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="wrap_content" android:layout_height="35dip" android:id="@+id/textView33"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/imageView3" android:src="@drawable/leitwert" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/viewGraphen">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView01" android:textStyle="bold" android:text="@string/graphen_die_nicht_angezeigt_werden_sollen_n_nwerte_die_nicht_angezeigt_werden_sollen"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView03"></TextView>
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/LinearLayout02">
<LinearLayout android:paddingLeft="10dip" android:gravity="center|left" android:paddingRight="10dip" android:layout_width="wrap_content" android:orientation="vertical" android:layout_height="wrap_content" android:paddingTop="10dip" android:id="@+id/LinearLayout05">
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckAmmonium" android:text="@string/ammonium"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckNitrit" android:text="@string/nitrit"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckNitrat" android:text="@string/nitrat"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckPhosphat" android:text="@string/phosphat"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckCalcium" android:text="@string/calcium"></CheckBox>
</LinearLayout>
<LinearLayout android:paddingLeft="10dip" android:gravity="center|left" android:paddingRight="10dip" android:layout_width="wrap_content" android:orientation="vertical" android:layout_height="wrap_content" android:paddingTop="10dip" android:id="@+id/LinearLayout04">
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckMagnesium" android:text="@string/magnesium"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckAlkalinitaet" android:text="@string/alkalinit_t"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckSilikat" android:text="@string/silikat"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckSalinitaet" android:text="@string/salinit_t"></CheckBox>
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/ckTemperatur" android:text="@string/temperatur"></CheckBox>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ViewFlipper>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="wrap_content" android:id="@+id/linearLayout9">
<LinearLayout android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="@+id/linearLayout7">
<ImageView android:layout_width="wrap_content" android:id="@+id/img1" android:src="@drawable/dotgrey" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="10dip" android:layout_height="wrap_content" android:id="@+id/textView37"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/img2" android:src="@drawable/dotgrey" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="10dip" android:layout_height="wrap_content" android:id="@+id/textView38"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/img3" android:src="@drawable/dotgrey" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="10dip" android:layout_height="wrap_content" android:id="@+id/textView39"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/img4" android:src="@drawable/dotgrey" android:layout_height="wrap_content"></ImageView>
<TextView android:layout_width="10dip" android:layout_height="wrap_content" android:id="@+id/TextView05"></TextView>
<ImageView android:layout_width="wrap_content" android:id="@+id/img5" android:src="@drawable/dotgrey" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1">
<Button android:onClick="onWeiter" android:layout_width="wrap_content" android:visibility="invisible" android:layout_height="48dip" android:text="@string/bt_zurueck" android:id="@+id/bt_first_thanks_zurueck" android:clickable="false" android:enabled="true"></Button>
<Button android:onClick="onWeiter" android:layout_width="wrap_content" android:layout_height="48dip" android:text="@string/bt_weiter" android:id="@+id/bt_first_thanks_weiter"></Button>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
There Top Linear Layout (Green) and the Buttom Linear Layout("Next" and "Back") should always be shown, no matter what size the android phone is. And only the Scrollview should be variable.
Hope you uderstand it and could help me.
A: <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1">
<Button android:onClick="onWeiter" android:layout_width="wrap_content" android:visibility="invisible" android:layout_height="48dip" android:text="@string/bt_zurueck" android:id="@+id/bt_first_thanks_zurueck" android:clickable="false" android:enabled="true"></Button>
<Button android:onClick="onWeiter" android:layout_width="wrap_content" android:layout_height="48dip" android:text="@string/bt_weiter" android:id="@+id/bt_first_thanks_weiter"></Button>
</LinearLayout>
Two things :
First if you wanna show buttons all the time , you must put them out of the scrollView
Second I tell you to use RelativeLayout in order to avoid some screen sizes problems.
A: Thanks all, i found the Solution....
Instead of LinearLayouts now i am using RelativLayout. The Buttons at the Buttom of the Page:
android:layout_alignParentBottom="true"
And the text wich should ONLY be scrollable in the middle of the view:
android:layout_above="@+id/linearLayout9"
linearLayout9 is the LinearLayout around the Buttons
Thats all^^
| {
"language": "ja",
"url": "https://stackoverflow.com/questions/7544836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problems with glew and gltools, _glewInit already defined I am trying to add shadders from opengl Superbible example to my program. The problem is, when I call any function from gltools i get
glew32.lib(glew32.dll) : error LNK2005: _glewInit already defined in gltools.lib(glew.obj)
After this i swapped glew32.lib with glew32s.lib. That resulted in an unhandled exception at
const M3DMatrix44f& GetMatrix(void) { return pStack[stackPointer]; }
The code I added
void Shadders::RenderScene()
{
static CStopWatch rotTimer;
// Clear the window and the depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
modelViewMatrix.PushMatrix(viewFrame);
modelViewMatrix.Rotate(rotTimer.GetElapsedSeconds() * 10.0f, 0.0f, 1.0f, 0.0f);
GLfloat vColor[] = { 0.1f, 0.1f, 1.f, 1.0f };
glUseProgram(flatShader);
glUniform4fv(locColor, 1, vColor);
glUniformMatrix4fv(locMVP, 1, GL_FALSE, transformPipeline.GetModelViewProjectionMatrix()); // The line that causes the unhandled exception
torusBatch.Draw();
modelViewMatrix.PopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
When i try to work aroud with
GLfloat modmatrix[16], projmatrix[16];
glGetFloatv(GL_PROJECTION_MATRIX, projmatrix);
glGetFloatv(GL_MODELVIEW_MATRIX, modmatrix);
//M3DMatrix44f
float MDWPRJMatrix[16];
m3dMatrixMultiply44(MDWPRJMatrix, modmatrix, projmatrix);
glUniformMatrix4fv(locMVP, 1, GL_FALSE, MDWPRJMatrix);
I get assertion failed with Expression:OPENGLUT_READY
I would like to know what causes this, and if possible, how to solve it
Thanks in advance
A: Solved it by linking glew32s.lib and adding #define GLEW_STATIC at the beginning of my code. Also, linked freeglut instead of openglut.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to edit project settings in xcode 4.2? This sounds dumb but i want to edit my project settings and change my delevelper profile of a project which in xcode 3.2 was project>>edit active targets/ edit project settings
but cant find this on xcode 4.2 beta version :(
Does anyone know how to.
thnx alot in advance.
A: As previously mentioned I can't talk about Xcode 4.2, however in Xcode 4.1 to change your provisioning profile you would do this:
*
*Select the Project navigator using folder icon on the left of the navigator sidebar
*Select the Project, which will be at the top of that view.
*The project configuration will appear in the main editor panel, to edit the provisioning profile select "Build Settings" at the top and search for provisioning to pull up the
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Avoid Maven complaints about mock objects without any @Test Maven 3.x.x complains about my mock "TestPacket" class that I use for another real test:
java.lang.Exception: No runnable methods
How can I avoid Maven complaining about this?
I did this for now (in TestPacket):
@Test
public void workaround() {
}
But there should be another clean way...
Thank you for your time!
Andrew
A: This is more of an JUnit issue than a maven one. If you don't want your TestPacket class to be treated as a JUnit test class by JUnit, annotate it (at the class level) with JUnit's @Ignore annotation
A: Exclude the default "**/Test*.java" inclusion rule in the configuration of the surefire plugin in the pom:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/Test*.java</exclude>
</excludes>
</configuration>
</plugin>
A better solution is excluding only your TestPacket class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pass a targeted method as a parameter first of all, my english is not very good so if you could be kind it would be appreciated. Thanks.
Now my problem, like I said in the title, I would like to pass a "method name" as a parameter in another method. Like a picture is worth thousand words, there is a chunk of my function:
public void RemoveDecimalPoints(TextBox txtBoxName, Func<string, TextBox> txtBoxMethod)
{
//Some Code
txtBoxName.KeyPress += new KeyPressEventHandler(txtBoxMethod);
}
I want the second parameter to point to this other method:
private void txtIncomeSelfValue1_KeyPress(object sender, KeyPressEventArgs e)
{
//Some Code
}
Sorry if im not clear for some, I lack some vocabulary...
Thanks for your help.
A: Assuming you are calling this RemoveDecimalPoints method from the same class that contains the txtIncomeSelfValue1_KeyPress method you could pass it like this:
RemoveDecimalPoints(someTextBox, this.txtIncomeSelfValue1_KeyPress);
but you will have to modify the signature as Func<string, TextBox> doesn't match the txtIncomeSelfValue1_KeyPress method:
public void RemoveDecimalPoints(TextBox txtBoxName, KeyPressEventHandler txtBoxMethod)
{
//Some Code
txtBoxName.KeyPress += txtBoxMethod;
}
A: If you're happy to write your code like this:
RemoveDecimalPoints(txtBoxName, txtIncomeSelfValue1_KeyPress);
then you can use:
public void RemoveDecimalPoints(
TextBox txtBoxName,
KeyPressEventHandler txtBoxMethod)
{
//Some Code
txtBoxName.KeyPress += txtBoxMethod;
}
If you want to use a string then you need to use reflection and your signature would need to look like this:
void RemoveDecimalPoints(TextBox txtBoxName, string txtBoxMethod)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android XMLSerializer namespace exception I'm using XMLSerializer to write xml but i keep coming across an exception that doesn't explain much, can you help?
09-25 10:46:31.733: WARN/System.err(23654): java.lang.IllegalArgumentException: </{}titleid> does not match start
09-25 10:46:31.944: WARN/System.err(23654): at org.kxml2.io.KXmlSerializer.endTag(KXmlSerializer.java:504)
Exception occurs in the following KXmlSerializer.java
public XmlSerializer endTag(String namespace, String name)
throws IOException {
if (!pending)
depth--;
// if (namespace == null)
// namespace = "";
if ((namespace == null && elementStack[depth * 3] != null)
|| (namespace != null && !namespace
.equals(elementStack[depth * 3]))
|| !elementStack[depth * 3 + 2].equals(name))
throw new IllegalArgumentException("</{" + namespace + "}"
+ name + "> does not match start");
any ideas?
private String writeXml(List<Message> messages){
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "messages");
serializer.attribute("", "number", String.valueOf(messages.size()));
for (Message msg: messages){
serializer.startTag("", "message");
serializer.attribute("", "date", msg.getDate());
serializer.startTag("", "title");
serializer.text(msg.getTitle());
serializer.endTag("", "title");
serializer.startTag("", "url");
serializer.text(msg.getLink().toExternalForm());
serializer.endTag("", "url");
serializer.startTag("", "body");
serializer.text(msg.getDescription());
serializer.endTag("", "body");
serializer.endTag("", "message");
}
serializer.endTag("", "messages");
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
A: The above examlple is completely correct but the actual code i used had two endTags that were the same without starting (startTag) the second tag...
My error
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run different threads on different cores?
Possible Duplicate:
how to set CPU affinity of a particular pthread?
I am writing a c++ program, using g++ compiler in Ubuntu. I have 4 threads in my program and 4 cores on my CPU. I want to be sure that each thread will be run on a different core. I am rarely familiar with pthread.
A: See sched_setaffinity function: http://manpages.courier-mta.org/htmlman2/sched_setaffinity.2.html
A: Don't do this. Let the system schedule the threads. If you affinitise the threads to distinct cores you just handicap the scheduler. When your app is the only one consuming CPU, the scheduler will naturally schedule each thread on a separate core.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Regarding asp.net routing in webform & Asterisk sign I saw people use asterisk sign at the time of routing in webform. i just do not understand the importance of Asterisk sign like below one
routes.MapPageRoute(
"View Category", // Route name
"Categories/{*CategoryName}", // Route URL
"~/CategoryProducts.aspx" // Web page to handle route
);
what is the meaning of asterisk sign and also tell me what kind of situation i should use asterisk sign like above.
"Categories/{*CategoryName}"
it would be better if anyone come with small sample code of using Asterisk sign just to show the importance & use of asterisk sign in real life apps.
A: It is called catch all route mapping. See the below question as well :
Infinite URL Parameters for ASP.NET MVC Route
A: Since this was the first resource Google returned me for variable number of parameters I added below example from MSDN so future readers would find the solution here.
The following example shows a route pattern that matches an unknown number of segments.
query/{queryname}/{*queryvalues}
Case 1
URL :
/query/select/bikes/onsale
Resolved Parameter Values:
*
*queryname = "select"
*queryvalues = "bikes/onsale"
Case 2
URL :
/query/select/bikes
Resolved Parameter Values:
*
*queryname = "select"
*queryvalues = "bikes"
Case 3
URL :
/query/select
Resolved Parameter Values:
*
*queryname = "select"
*queryvalues = Empty string
Reference:
MSDN: Handling a Variable Number of Segments in a URL Pattern
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Cross browser border gradient I want to get border gradient (from top: #0c93c0; to bottom: white). I wonder, is there any way to get it with css3 for both webkit and moz browsers?
A: instead of borders, I would use background gradients and padding. same look, but much easier, more supported.
a simple example:
<div class="g">
<div>bla</div>
</div>
CSS:
.g {
background-image: -webkit-linear-gradient(top, #0c93C0, #FFF);
background-image: -moz-linear-gradient(top, #0c93C0, #FFF);
background-image: -ms-linear-gradient(top, #0c93C0, #FFF);
background-image: -o-linear-gradient(top, #0c93C0, #FFF);
background-image: linear-gradient(top, #0c93C0, #FFF);
padding: 1px;
}
.g > div { background: #fff; }
A: Using less.css (of course you can do it without also), the trick is in pseudoselectors (:before and :after):
1. define cross-browser gradient:
.linear-gradient (@dir, @colorFrom, @colorTo) {
background: -webkit-linear-gradient(@dir, @colorFrom, @colorTo);
background: -moz-linear-gradient(@dir, @colorFrom, @colorTo);
background: -ms-linear-gradient(@dir, @colorFrom, @colorTo);
background: -o-linear-gradient(@dir, @colorFrom, @colorTo);
}
2. define border-gradient bundle:
.border-gradient(@colorFrom, @colorTo){
border-top:1px solid @colorFrom;
border-bottom:1px solid @colorTo;
position:relative;
.border-bundle(@colorFrom, @colorTo){
position:absolute;
content:"";
width:1px;
height:100%;
top:0;
.linear-gradient(top, @colorFrom, @colorTo);
}
&:before{ .border-bundle(@colorFrom, @colorTo); left: 0; }
&:after { .border-bundle(@colorFrom, @colorTo); right:0; }
}
We can use it now like this:
.some-class{
/* other properties */
.border-gradient(#0c93c0, #FFF);
}
A: Fiddle: http://jsfiddle.net/9ZDTA/
Add an extra declaration for each browser engine that you want to support, using the specific prefixes.
background-color: #0c93C0; /* fallback color if gradients are not supported */
background-image: -webkit-linear-gradient(top, #0c93C0, #FFF);
background-image: -moz-linear-gradient(top, #0c93C0, #FFF);
background-image: -ms-linear-gradient(top, #0c93C0, #FFF);
background-image: -o-linear-gradient(top, #0c93C0, #FFF);
background-image: linear-gradient(top, #0c93C0, #FFF); /* standard, but currently unimplemented */
See this source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VSTO Outlook before item changed event, or previous item status I am developing a visual studio VSTO add in and monitoring item changed events for mail, contacts, tasks and appointment items. This I have done using the following
//subsrribe to task events
taskItems = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks).Items;
taskItems.ItemChange += new Outlook.ItemsEvents_ItemChangeEventHandler(TaskItems_ItemChange);
taskItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(TaskItems_ItemAdd);
appointmentItems = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar).Items;
appointmentItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(appointmentItems_ItemAdd);
//Added back as itemchanged requested
appointmentItems.ItemChange += new Outlook.ItemsEvents_ItemChangeEventHandler(appointmentItems_ItemChange);
contacts = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts).Items;
contacts.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(contacts_ItemAdd);
contacts.ItemChange += new Outlook.ItemsEvents_ItemChangeEventHandler(contacts_ItemChange);
I need to be able to save the previous state of the item changed, but in the above event handlers all I get is the item that has changed. Ideally what I require is a 'before item' changed event, or alternatively a way of keeping track of the item a user selects in outlook and then saving the required property state (e.g category), then I can access this in the changed event handler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: call controller and action method and pass model values I'm calling another controller and action method here
[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
if (ModelState.IsValid)
{ some lines of code . bla bla bla
return RedirectToAction("indexaction","premiumcontroller");
}
}
Now, what happens is the indexaction of premiumcontroller is now executed.
How can i pass the values of loginmodel (or the loginmodel object) to the premiumcontroller? i cant figure it out. Thanks.
I'm using asp.net mvc 3.
A: You could pass them as query string parameters:
return RedirectToAction(
"index",
"premium",
new {
id = loginModel.Id,
username = loginModel.Username,
}
);
and inside the index action of premium controller:
public ActionResult Index(LoginModel loginModel)
{
...
}
Another possibility is to use TempData:
[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
if (ModelState.IsValid)
{
// some lines of code . bla bla bla
TempData["loginModel"] = loginModel;
return RedirectToAction("index", "premium");
}
...
}
and inside the index action of premium controller:
public ActionResult Index()
{
var loginModel = TempData["loginModel"] as LoginModel;
...
}
A: you can use new keyword to pass the values in the controller action...
return RedirectToAction(
"indexaction",
"premium",
new {
Id = loginModel.Id,
UserName = loginModel.UserName,
Password = loginModel.Password
}
);
in your other controller
public ActionResult indexaction(int id, string uName, string paswrd)
{
// do some logic...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Installing CouchDB on Android I watch this video
and I followed a lot of tutorial how to install couchDB on my android phone but many of them need to install CouchDB application which should be on Play Store. e.g. like in the link above. But at this moment android couchDB application isn't on Play Store.
In this tutorial I found that I looking for is needed to using couchdb on android:
Can you help me that where I can download this app? Will this app on android market in the future? I would like to install this app and use couchDB on my HTC desire. If you know the other way how to use couchDB on my device please help me.
A: That is my blog post, as mentioned in the header its out of date, I should update the link but the current installation instructions are at
http://www.couchbase.org/get/couchbase-mobile-for-android/current
This is if you want to build an application that uses Couch for a backend
if you just want to play around with Couch on the device you can install the application that has a standalone version of couch along with a mobile admin interface
https://market.android.com/details?id=com.daleharvey.mobilefuton
Cheers
Dale
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem cache with django/Wsgi apache I am working on apache with a Django project and i got some issues. When i modify a file, sometimes my modifications is not use by apache. I have to restart it to apply my modification.
How can i force to reload all file on every request?
Thank you
A: If you are running a development environment locally, you should use the built in HTTP server that the django package provides:
https://docs.djangoproject.com/en/1.2/intro/tutorial01/#the-development-server
This will reload any changes. If you are running this dev server, you will need to also tell it to server your media files:
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development
The dev server shouldn't be used to server live code, so when you launch your code on your production server, you will always need to use apache/nginx (and will have to restart the server anytime you want to see the changes)
A: Read:
http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode
It explains everything about how/when code reloading works under Apache/mod_wsgi if that is what you are using.
A: Graham just got it:-)
You will need the Daemon Mode to tackle with your issues.
Do follow to read:
Reloading Source Code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dot Net Nuke 5 calling webservice in module this is very confusing for me, cannot picture how it can be done. I have the following scenario:
I have a server A & server B, Server A hosts an application that saves in it information. Server B hosts a Dot Net Nuke website where the information should be displayed.
Now on server A web service resides and it converts the data to xml and is scheduled to run daily at a particular time. On server B there are methods which reads the xml and import.
I need to expose the import method so that server A can use it. It can be done by implementing a webservice residing in the same application pool, I want to package this webservice as a module which once installed will immediately create the virtual directory in the iis of the dot net nuke site and expose the needed methods.
My concerns are the following:
Can I create a module to act as a webservice?
or should I create a webservice and call it in the module?
Please help!
A: You can use and package .ashx files in your DotNetNuke module. If you are creating a module to display the information that would be preferred over setting up it's own web service and putting it stand alone in IIS beside DNN.
You can then do whatever is necessary on Server A since it's not in DNN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Efficient way of XML parsing in ElementTree(1.3.0) Python I am trying to parse a huge XML file ranging from (20MB-3GB). Files are samples coming from different Instrumentation. So, what I am doing is finding necessary element information from file and inserting them to database (Django).
Small part of my file sample. Namespace exist in all files. Interesting feature of files are they have more node attributes then text
<?xml VERSION="1.0" encoding="ISO-8859-1"?>
<mzML xmlns="http://psi.hupo.org/ms/mzml" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="http://psi.hupo.org/ms/mzml http://psidev.info/files/ms/mzML/xsd/mzML1.1.0.xsd" accession="plgs_example" version="1.1.0" id="urn:lsid:proteios.org:mzml.plgs_example">
<instrumentConfiguration id="QTOF">
<cvParam cvRef="MS" accession="MS:1000189" name="Q-Tof ultima"/>
<componentList count="4">
<source order="1">
<cvParam cvRef="MS" accession="MS:1000398" name="nanoelectrospray"/>
</source>
<analyzer order="2">
<cvParam cvRef="MS" accession="MS:1000081" name="quadrupole"/>
</analyzer>
<analyzer order="3">
<cvParam cvRef="MS" accession="MS:1000084" name="time-of-flight"/>
</analyzer>
<detector order="4">
<cvParam cvRef="MS" accession="MS:1000114" name="microchannel plate detector"/>
</detector>
</componentList>
</instrumentConfiguration>
Small but complete file is here
So what I have done till now is using findall for every element of interest.
import xml.etree.ElementTree as ET
tree=ET.parse('plgs_example.mzML')
root=tree.getroot()
NS="{http://psi.hupo.org/ms/mzml}"
s=tree.findall('.//{http://psi.hupo.org/ms/mzml}instrumentConfiguration')
for ins in range(len(s)):
insattrib=s[ins].attrib
# It will print out all the id attribute of instrument
print insattrib["id"]
How can I access all children/grandchildren of instrumentConfiguration (s) element?
s=tree.findall('.//{http://psi.hupo.org/ms/mzml}instrumentConfiguration')
Example of what I want
InstrumentConfiguration
-----------------------
Id:QTOF
Parameter1: T-Tof ultima
source:nanoelectrospray
analyzer: quadrupole
analyzer: time-of-flight
detector: microchannel plate decector
Is there efficient way of parsing element/subelement/subelement when namespace exist? Or do I have to use find/findall every time to access particular element in the tree with namespace? This is just a small example I have to parse more complex element hierarchy.
Any suggestions!
Edit
Didn't got the correct answer so have to edit once more!
A: Here's a script that parses one million <instrumentConfiguration/> elements (967MB file) in 40 seconds (on my machine) without consuming large amount of memory.
The throughput is 24MB/s. The cElementTree page (2005) reports 47MB/s.
#!/usr/bin/env python
from itertools import imap, islice, izip
from operator import itemgetter
from xml.etree import cElementTree as etree
def parsexml(filename):
it = imap(itemgetter(1),
iter(etree.iterparse(filename, events=('start',))))
root = next(it) # get root element
for elem in it:
if elem.tag == '{http://psi.hupo.org/ms/mzml}instrumentConfiguration':
values = [('Id', elem.get('id')),
('Parameter1', next(it).get('name'))] # cvParam
componentList_count = int(next(it).get('count'))
for parent, child in islice(izip(it, it), componentList_count):
key = parent.tag.partition('}')[2]
value = child.get('name')
assert child.tag.endswith('cvParam')
values.append((key, value))
yield values
root.clear() # preserve memory
def print_values(it):
for line in (': '.join(val) for conf in it for val in conf):
print(line)
print_values(parsexml(filename))
Output
$ /usr/bin/time python parse_mxml.py
Id: QTOF
Parameter1: Q-Tof ultima
source: nanoelectrospray
analyzer: quadrupole
analyzer: time-of-flight
detector: microchannel plate detector
38.51user 1.16system 0:40.09elapsed 98%CPU (0avgtext+0avgdata 23360maxresident)k
1984784inputs+0outputs (2major+1634minor)pagefaults 0swaps
Note: The code is fragile it assumes that the first two children of <instrumentConfiguration/> are <cvParam/> and <componentList/> and all values are available as tag names or attributes.
On performance
ElementTree 1.3 is ~6 times slower than cElementTree 1.0.6 in this case.
If you replace root.clear() by elem.clear() then the code is ~10% faster but ~10 times more memory. lxml.etree works with elem.clear() variant, the performance is the same as for cElementTree but it consumes 20 (root.clear()) / 2 (elem.clear()) times as much memory (500MB).
A: If this is still a current issue, you might try pymzML, a python Interface to mzML Files. Website:
http://pymzml.github.com/
A: In this case I would get findall to find all the instrumentList elements. Then on those results just access the data as if instrumentList and instrument were arrays, you get all the elements and don't have to search for them all.
A: If your files are huge, have a look at the iterparse() function. Be sure to read this article
by elementtree's author, especially the part about "incremental parsing".
A: I know that this is old, but I run into this issue while doing XML parsing, where my XML files where really large.
J.F. Sebastian's answer is indeed correct, but the following issue came up.
What I noticed, is that sometimes the values in elem.text ( if you have values inside XML and not as attributes) are not read correctly (sometimes None is returned) if you iterate through the start attributes. I had to iterate through the 'end' like this
it = imap(itemgetter(1),
iter(etree.iterparse(filename, events=('end',))))
root = next(it) # get root element
If someone wants to get the text inside an xml tag (and not an attribute) maybe he should iterate through the 'end' events and not 'start'.
However, if all the values are in attributes, then the code in J.F. Sebastian's answer is more correct.
XML example for my case:
<data>
<country>
<name>Liechtenstein</name>
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
</country>
<country>
<name>Singapore</name>
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
</country>
<country>
<name>Panama</name>
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
</country>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Inheritance + NestedClasses in C# We can have nested classes in C#. These nested classes can inherit the OuterClass as well. For ex:
public class OuterClass
{
// code here
public class NestedClass : OuterClass
{
// code here
}
}
is completely acceptable.
We can also achieve this without making NestedClass as nested class to OuterClass as below:
public class OuterClass
{
// code here
}
public class NestedClass : OuterClass
{
// code here
}
I am wondering, what is the difference between above two scenarioes? What is achievable in scenario I which can't be achievable in scenario II? Is there anything that we get more by making NestedClass "nested" to OuterClasss?
A: Inheriting from a parent class does not allow a nested class to see its parent's private members and methods, only protected (and public) ones. Nesting it within the parent class lets it see all private members and invoke its private methods, whether the nested class inherits from the parent class or not.
A: Its maybe too late But Let me Add my 2 cents Please , If I could understand your question correctly , You mean :
What is the advantage of a nested class that also inherited from its outer class?
The key point is in Construction
First Code :
public class OuterClass
{
public OuterClass{console.writeln("OuterClaass Called");}
public class NestedClass : OuterClass //It does Inherit
{
public NestedClass{console.writeln("NestedClass Called");}
}
}
static void Main()
{
outerClass.NestedClass nestedobject = new outerClass.NestedClass();
}
OutPut :
Outerclass Called
NestedClass Called
Second Code :
public class OuterClass
{
public OuterClass{console.writeln("OuterClaass Called");}
public class NestedClass //it dosent Inherit
{
public NestedClass{console.writeln("NestedClass Called");}
}
}
static void Main()
{
OuterClass.NestedClass nestedobject = new OuterClass.NestedClass();
}
Output :
NestedClass called
In the first code when constructing the NestedClass object , the Constructor of the OutrClass also would be Called and In my opinion it means Composition Relationship between NestedClass and The OuterClass But In the Second Code Object Construction of the NestedClass and the Outerclass Is not bounded together and its done independently .
hope it would be helpfull.
A: the second example you provided is not a nested class, but a normal class that derives from OuterClass.
*
*nested types default to private visibility, but can be declared with a wider visibility
*nested types can access properties, fields and methods of the containing type (even those declared private and those inherited from base types)
also take a look at this question here on when and why to use nested classes.
MSDN link : Nested Types (C# Programming Guide)
EDIT
To address @Henk's comment about the difference in nature of the both relations (inheritance vs. nested types):
In both cases you have a relation between the two classes, but they are of a different nature. When deriving from a base class the derived class inherits all (except private) methods, properties and fields of the base class. This is not true for nested class. Nested classes don't inherit anything, but have access to everything in the containing class - even private fields, properties and methods.
A: Nested classes are different from sub-classes in the the way they can access the properties and private fields of the container class when inheriting from it.
Nested classes represent the combining of inheritance with encapsulation in OOP, in terms of a singleton design pattern implementation, where dependencies are well hidden and one class provide a single point of access with static access to the inner classes, while maintaining the instantiaion capability.
For example using practical class to connect to database and insert data:
public class WebDemoContext
{
private SqlConnection Conn;
private string connStr = ConfigurationManager.ConnectionStrings["WebAppDemoConnString"].ConnectionString;
protected void connect()
{
Conn = new SqlConnection(connStr);
}
public class WebAppDemo_ORM : WebDemoContext
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public int result = 0;
public void RegisterUser()
{
connect();
SqlCommand cmd = new SqlCommand("dbo.RegisterUser", Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("FirstName", FirstName);
cmd.Parameters.AddWithValue("LastName", LastName);
cmd.Parameters.AddWithValue("Phone", Phone);
cmd.Parameters.AddWithValue("Email", Email);
cmd.Parameters.AddWithValue("UserName", UserName);
cmd.Parameters.AddWithValue("UserPassword", UserPassword);
try
{
Conn.Open();
result = cmd.ExecuteNonQuery();
}
catch (SqlException se)
{
DBErrorLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
}
}
}
The WebAppDemo_ORM class is a nested class inside WebDemoContext and in the same time inheriting from WebDemoContext in that way the nested class can access all the members of the container class including private members which can be effective in reducing DRY and achieving SOC.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Detect radio button changes based on a button id In some circumstances I have to detect radio-buttons changes. The problem is the app only have the ID of the button it is interested. For example, given that HTML piece:
<label class="required">Type</label><br/>
<span class="vertical">
<input checked="checked" id="diabetes_type-none" name="diabetes_type" type="radio" value="none" /><label for="diabetes_type-none">No diabetes</label><br />
<input id="diabetes_type-dm1" name="diabetes_type" type="radio" value="dm1" /><label for="diabetes_type-dm1">DM1</label><br />
<input id="diabetes_type-dm2" name="diabetes_type" type="radio" value="dm2" /><label for="diabetes_type-dm2">DM2</label><br />
<input id="diabetes_type-other" name="diabetes_type" type="radio" value="other" /><label for="diabetes_type-other">Other type</label>
<input class="small free" id="diabetes_type-other_more" name="diabetes_type-other_more" type="text" />
</span>
and given the ID "diabetes_type-other" the app must execute some code each time user checks or unchecks the "Other type" button. The code only must be executed when the user clicks on this radio button or when the user clicks on any other button unchecking a previous "Other type" checked button. If user clicks on DM1 and then clicks on DM2 the function shouldn't be executed. This is my approach:
$("#" + _var).change(function() {
alert('changed');
});
Problem here is the code is the function is triggered when user clicks on "Other type" but not when user unchecks this.
Other approach is to obtain radio name and then do something like this:
_radioName = "diabetes_type"; // Obtain programmatically
$("input[name=" + _radioName + "]").change(function() {
alert('changed');
});
Now the problem is this function is triggered always, on any button click and I need the function to be triggered only when user checks or unchecks the given radio button. You can play with this jsfiddle.
A: Fiddle: http://jsfiddle.net/sn7eU/1/
Examine this code, it should meet your wishes:
var _radioName = "diabetes_type"; // Obtain programmatically
var _var = "diabetes_type-other";
#(document).ready(function(){
var lastChecked = false;
$("input[name=" + _radioName + "]").change(function() {
if(this.id == _var) lastChecked = true;
else if(lastChecked){
/*The radio input isn't "other". Check if the last checked element equals
"other" (lastChecked == true). If true, set lastChecked to false*/
lastChecked = false;
} else return; /*The input isn't "other", and the last checked element isn't
"other". Return now. */
alert('changed');
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Maven dependencies for JSF 2 and IceFaces 2 i have a Spring JSF 2 project which is using IceFaces 2, and i made the project use JSF and IceFaces libraries from properties>project facets, and added jsf capabilities to the project, then used a user library JSF 2.1 Mojara, then added icefaces capabilities too,
what i want to do is add those jars for JSF 2, IceFaces2 in pom file as maven dependencies
any help ?
A: well, i was able to fix it by adding following dependencies:
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.0-b11</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.0-b11</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.icepush</groupId>
<artifactId>icepush</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.icefaces</groupId>
<artifactId>icefaces</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.icefaces</groupId>
<artifactId>icefaces-ace</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.icefaces</groupId>
<artifactId>icefaces-compat</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<dependency>
<groupId>net.sf.jcharts</groupId>
<artifactId>krysalis-jCharts</artifactId>
<version>1.0.0-alpha-1</version>
</dependency>
and i added the repo:
<repository>
<id>ICEfaces Repo</id>
<name>ICEfaces Repo</name>
<url>http://anonsvn.icefaces.org/repo/maven2/releases/</url>
</repository>
A: I added the ICEfaces repository to my Maven pom.xml:
<repositories>
<repository>
<id>maven2-repository.org.icefaces</id>
<name>ICEfaces Repository</name>
<url>http://anonsvn.icefaces.org/repo/maven2/releases/</url>
<layout>default</layout>
</repository>
</repositories>
This Maven repository contains the icefaces and icefaces-compat artifacts
for ICEfaces version 2 and I included them as dependencies in my pom.xml.
The following answer describes how to include Mojarra JSF in your
pom.xml:
JSF Maven Mojarra implementation
If your application server already provides a non-Mojarra JSF implementation then use <scope>provided</scope>
for the Mojarra JSF artifacts in your pom.xml and change the application server to provide Mojarra JSF.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Grails problem with shiro-quick-start: imports cannot be resolved (by Eclipse) On my fresh new grails project, I installed shiro
(grails install-plugin shiro)
and the quick setup grails shiro-quick-start. This generated new files as described in the shiro documentation.
However, in one of those files, controllers/(default package)AuthController.groovy there are eight problem marked by eclipse (SpringSource Tools Suite). Five of those problems address the five imports respectively:
Groovy:unable to resolve class org.apache.shiro.authc.AuthenticationException
…
Specifying the correct package and moving the file to that package doesn’t solve the problem. The three other problem markers are:
Groovy:Catch statement parameter type is not a subclass of Throwable.
(x3)
I suppose this problem might be related to the failed imports and might thus vanish once the previous problem is resolved.
Now, I could set up shiro myself without the quick start, but tbh I’d prefer to stick with the quick start and expand on that, as described in the guide.
(obvious) Question 1: Does anybody have an idea as to why Eclipse gives me those error messages? Did I miss a step in the installation process?
(not so important) Question 2: I tried to apply the fix to the (default package) issue, only to find that there is already a reference to the package path at the relevant part of _ShiroInternal.groovy. Why does it still install to default directory? Might this be related to my problem?
Additional oddity: There is another file, realm/ShiroDbRealm.groovy, that includes imports of org.apache.shiro resources. There is no package declaration and there are no error markers in Eclipse. Once I add the correct package declaration of my project and move the file to that package, imports cannot be resolved anymore. This might be a clue to what is happening here.
A: You have to add the shiro library jars to the eclipse project build path.
The librarys (in my case) are by default installed to the grails project plugin directory in my home folder.
A: Perhaps an even easier fix, that solved the issue when I was running into it:
Regardless of whether you have already installed it by other means, run:
grails install-plugin shiro
While this might tell you that the plugin is already installed, this will also sort out the pathing for you, which should fix the issue.
A: I found that making sure you have done the following worked
Inserted compile ":shiro:1.2.1" into BuildConfig.groovy
Run the command grails compile
right click in the project > grails tools > refresh dependencies
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Facebook FQL photo_tag table not returning all appropriate photos I'm trying to run a query that returns all the latest tags that happened on my friends photos.
Here is my query:
String query = "SELECT subject, created FROM photo_tag WHERE subject IN (SELECT uid2 FROM friend WHERE uid1 = me()) ORDER BY created DESC LIMIT 200";
This is supposed to return the latest 200 tags performed.
Unfortunately, after looking at my news feed, here are the first few results I get
(formatted by SUBJECT at CREATED_TIME)
522274044 at Sun Sep 25 20:01:03 AEST 2011
522274044 at Sun Sep 25 20:00:26 AEST 2011
522274044 at Sun Sep 25 20:00:00 AEST 2011
522274044 at Sun Sep 25 20:00:00 AEST 2011
522274044 at Sun Sep 25 20:00:00 AEST 2011
522274044 at Sun Sep 25 20:00:00 AEST 2011
522274044 at Sun Sep 25 20:00:00 AEST 2011
521123280 at Sun Sep 25 16:39:19 AEST 2011
521123280 at Sun Sep 25 16:39:19 AEST 2011
522274044 at Sun Sep 25 15:00:04 AEST 2011
521342837 at Sun Sep 25 12:10:06 AEST 2011
521123280 at Sun Sep 25 11:20:45 AEST 2011
521123280 at Sun Sep 25 11:20:14 AEST 2011
521123280 at Sun Sep 25 11:16:51 AEST 2011
521123280 at Sun Sep 25 11:16:51 AEST 2011
521123280 at Sun Sep 25 11:16:51 AEST 2011
521123280 at Sun Sep 25 11:16:51 AEST 2011
521123280 at Sun Sep 25 11:16:51 AEST 2011
521123280 at Sun Sep 25 11:16:51 AEST 2011
As you can see, there is a massive gap between 8PM and 4:39PM, and by checking my news feed, there are a WHOLE LOT of photos between these times that should be listed here. Is my FQL query correct? or does the facebook servers just not handle these kinds of queries.. Also, later down the list:
512328700 at Sun Jul 24 00:30:02 AEST 2011
523619736 at Sat Jul 23 17:36:37 AEST 2011
521342837 at Tue Jul 19 12:23:32 AEST 2011
519156948 at Fri Jul 15 15:08:11 AEST 2011
More massive inconsistencies.. Is there any explanation for this?? Thanks for your help!
UPDATE: Of all 200 results, I'm only retrieving about 10 unique subject names
UPDATE2: I tried querying a bunch of names that weren't in that list of 10 unique names above, and they resulted in the photos they were tagged in, concluding that their names aren't showing from the larger query above because of any 'privacy' settings or anything. So maybe it's a server side thing?
A: You will also want to make sure you have both user_photos and friends_photos permissions. Also, friends can opt out of the Facebook platform so that their photos, etc are not available to applications via the Facebook API:
A: Request denied: source address is sending an excessive volume of requests. hope your not recieving this while tag(photos)....i agree with facebook API:
0down vote
You will also want to make sure you have both user_photos and friends_photos permissions. Also, friends can opt out of the Facebook platform so that their photos, etc are not available to applications via the Facebook API:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does anyone have experience with Perl5i? I occasionally see Perl5i being mentioned. It looks great and make things easier. Some questions:
*
*Is this module compatible with other modules, e.g. Dancer, Mojolicious, XML::RSS, etc.?
*It it compatible with Moose, or does it have better OO features?
*It wraps the best CPAN modules, if my script uses these…
use strict;
use utf8::all;
use XML::RSS::JavaScript;
use DateTime::Format::Mail;
… should I just replace it with:
use perl5i::2;
use XML::RSS::JavaScript;
use DateTime::Format::Mail;
Any experience, good and bad, please share.
A: I'm the primary author of perl5i.
1) perl5i is compatible with other modules. If you find a conflict, let us know. http://github.com/schwern/perl5i/issues
2) Yes, it is compatible with Moose and Mouse. It does not have ambitions to reinvent those wheels. Its contribution to OO is autoboxing, where non-objects can have methods called on them like $string->trim.
3) In general, you can safely use perl5i with existing code. However, it does do some small backwards incompatible changes, generally to bits of Perl that don't make sense anyway. The biggest things to look out for are 1) file operations (like open) now throw exceptions on failure and 2) utf8::all changes how non text files are read.
My experiences with perl5i are biased. I can say the biggest negatives about perl5i are 1) sometimes there are bugs and its lexical effects leak out of scope 2) the dependency chain is pretty big and 3) some of those dependencies have issues on Windows. The positive sides are how much autoboxing and built-in exceptions change how one writes Perl.
There is a FAQ and I give a talk about perl5i.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Rails: Model and model template interaction Using: Ruby on Rails (3.0.3)
I am building a website where one can perform different health and diet related calculations.
Each calculation holds different inputs:
Calculation 1
height, weight, waist_measurement
Calculation 2
weight, hip_measurement
Calculation 3
hip_measurement, lifestyle_type (string), age, calory_intake
...and so on.
I have (as a suggestion from a friend who knows RoR) created a model "Calculation" (which stands as a template) and another model "CalculationSheet" that will be used as an instance model etc.
Model:Calculation (the template) holds data like:
- TypeOfCalculation ('health', 'lifestyle' etc)
- SearchTags
- isSpecial (a boolean to isolate certain special Calculations)
There are as many Calculation objects as there are calculation "types" on the website (such as the 3 I mentioned earlier)
Model: CalculationSheet will only hold data like:
- Result (such as BMI=>22)
A CalculationSheet will be created when a calculation is performed on the website using Create. I have no need to save these calculations (prefer not to actually).
The most important reason for using the CalculationSheet model is to be able to validate the input...and here is the problem.
Problem:
How do I validate inputs from a model that does not hold each input as an attribute. I cannot make an attribute for each type of input (there are literally 100's), such as height, weight, life_style, waist, age etc...
This is my plan as for now:
class CalculationSheet < ActiveRecord::Base
belongs_to :calculation
# BMI
validates :height, :numericality => true, :if => :calculation_is_bmi?
validates :weight, :numericality => true, :if => :calculation_is_bmi?
def calculation_is_bmi?
# do something
end
end
which (obviously) does not work. It tries to validate height which does not exist.
What I would like to do is to "validates params[:height], :numer... etc" but it does not seem to work either...
How can I solve this?
A: You can use ActiveModel instead of ActiveRecord as shown in these lines:
class CalculationSheet
include ActiveModel::Validations
attr_accessor :height, :weight
validates_numericality_of :height, :weight
end
This will allow for form validation of every attribute, but you don't store anything. Here's a great post by Yehuda Katz about ActiveModel: ActiveModel: Make Any Ruby Object Feel Like ActiveRecord
For Rails 3 use validates_with to use a custom validator.
See this great post for information on how to use them.
edit:
How about this:
class CalculationSheet
include ActiveModel::Validations
attr_accessor :height, :weight, :hip_circumference
validates_numericality_of :height, :weight, :if => :bmi?
validates_numericality_of :height, :hip_circumference, :if => :bai?
def bmi?
[height, weight].all?(&:present?)
end
def bmi
weight / (height**2)
end
def bai?
[height, :hip_circumference].all?(&:present?)
end
def bai
(hip_circumference / height**1.5) − 18
end
end
A: The trick is in your comment "I have no need to save these calculations":
ActiveRecord is all about providing persistence for your data (i.e. saving). If you're just wanting to do calculations, you can use plain old ruby objects :)
With stuff like this I'd be tempted to build a little library (perhaps in /lib now and as a gem later) that does your calculations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Symfony2+Twig: Using a template both for authenticated and anonymous user I'm new to symfony and twig and I have some headache with security, firewalls and templates.
What I'm trying to do is to have a "base" template that shows a topbar. I would like this top bar show a "You are not logged in" if the user is not logged and a "Welcome user U" message if the user is logged.
Because this I put an
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
in the "base" template to differentiate between logged and anonymous users but I have problems about security context tokens.
My public paths (not secured by firewall) are:
/myapp/
/myapp/home
/myapp/about
/myapp/help
and later there are some paths for actions only can access authenticated users:
/myapp/action1
/myapp/action2
...
/myapp/actionN
The problem is, once a user is logged in my "base" show the welcome message in the view of actions1, ..., actionN but when user goed to "home" or "help" pages the message is "you are not logged in".
Some has a similar situacion? how did you solve it? how are your router and security files configured?
A: The firewall doesn't share the security context. So when a action is not behind the firewall you can't acces the user info. Try placing the entire app behind the firewall (and allow anonymous users):
firewalls:
secured_area:
pattern: ^/
anonymous: ~
form_login:
check_path: /login_check
login_path: /login
logout:
path: /logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/action, roles: ROLE_USER }
Make sure the login_path can be accessed by anonymous users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert Between Latin1-encoded Data.ByteString and Data.Text Since the latin-1 (aka ISO-8859-1) character set is embedded in the Unicode character set as its lowest 256 code-points, I'd expect the conversion to be trivial, but I didn't see any latin-1 encoding conversion functions in Data.Text.Encoding which contains only conversion functions for the common UTF encodings.
What's the recommended and/or efficient way to convert between Data.ByteString values encoded in latin-1 representation and Data.Text values?
A: The answer is right at the top of the page you linked:
To gain access to a much larger family of encodings, use the text-icu package: http://hackage.haskell.org/package/text-icu
A quick GHCi example:
λ> import Data.Text.ICU.Convert
λ> conv <- open "ISO-8859-1" Nothing
λ> Data.Text.IO.putStrLn $ toUnicode conv $ Data.ByteString.pack [198, 216, 197]
ÆØÅ
λ> Data.ByteString.unpack $ fromUnicode conv $ Data.Text.pack "ÆØÅ"
[198,216,197]
However, as you pointed out, in the specific case of latin-1, the code points coincide with Unicode, so you can use pack/unpack from Data.ByteString.Char8 to perform the trivial mapping from latin-1 from/to String, which you can then convert to Text using the corresponding pack/unpack from Data.Text.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Qt QGraphicsSvgItem renders too big (0.5 unit on each side) If I draw an SVG item at (0, 0) with 64x64, the actual displayed SVG item is from (-0.5, -0.5) with 65x65. I measured this by drawing the boundingbox behind the SVG item. And the SVG item is sticking out at all sides by a half unit on the QGraphicsScene.
Can I remove this effect? I have set the pen to NoPen.
I could scale it down, but that would be quite unprecise (since width and height need different scaling, which is hardly possible). How can I fix this issue?
As you can see, the brown boxes (SVG) stick out over the grey area (bounding box). The bounding box is confirmed with Inkscape.
Thanks
A: Found the solution using transform:
QSvgRenderer *test = new QSvgRenderer(QLatin1String("test.svg"));
QGraphicsSvgItem *item = new QGraphicsSvgItem();
item->setSharedRenderer(test);
addItem(item);
// the following transformation is required if you want the SVG to be exactly on the spot and as big as it should be
item->setTransform(QTransform(test->viewBoxF().width() / (test->viewBoxF().width() + 1.0), 0.0, 0.0, test->viewBoxF().height() / (test->viewBoxF().height() + 1.0), 0.5, 0.5));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XBRL and its link and xlink specification mapping from xml to C# classes I want to model XBRL (consisting of one XSD and many included XSD files and a bunch of referenced linkbases which themselves have xlink elements that point to elements within themselves of outside themselves). I want to be able to do some automatic xml deserialization so I can deal with C# classes at run time which objects are pre-populated using XML deserialization.
Thanks,
Rad
A: It's difficult to give an answer when there is no question... In order to deal with xbrl specificities, you can use Gepsio for .net or altova XBRL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SPHINX : How to set the matchMode on the mysql client I installed Sphinx search on debian squeeze.
Connection trough the mysql client, with :
mysql -h127.0.0.1 -P 9306 --protocol=tcp
gives me access to the searchd. I would like to change the matching mode to
SPH_MATCH_ANY
I don't have any access to the php api (because it is not included into squeeze).
A: Just wrap your query to make it a quarum search. That's the benefit of extended match mode - it can emulate all the others
where match('"one two three"/1')
Can also use
option ranker=matchany
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python, Twisted, Proxy and rotating the proxy server I use the below to starting the reactor for fetching web pages...
So...all pages I fetch use the proxy once the reactor starts. But...what if I want to rotate proxies? How do I do that using e.g. random.choice(proxy_list)
Thanks
site = server.Site(proxy.ReverseProxyResource('173.000.342.234', 8800, ''))
reactor.listenTCP(8080, site)
reactor.run()
A: Take a look at the implementation. Notice where it uses the supplied IP and port to set up a new connection with reactor.connectTCP. Subclass ReverseProxyResource and extend it to be able to connect to your randomly selected address.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use the progress bar? In my application, onclick of menu it is taking time to load the next activity. So in between the screen is black for sometime.What should I do? Shall I add a progress bar? .
A: This is what you need: Async task
It will create a separate thread to display the loader
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can't log in to eclipse google plugin when developing a google app engine project i suddenly can't login with my google acount.
here is the error:
Error
Sun Sep 25 18:03:11 CST 2011
Could not sign in. Check that your computer's date and time are correct; sign-in errors can occur if your computer's time is significantly different from the server's time.
i am using eclipse 3.7 64bit with google plugin, my os is windows8 developer preview 64 bit.
i also tried eclipse 3.7 32bit on a win7 32bit machine, same problem. i don't think there is any problem with my time setting, does anyone have a clue?
A: If that's the time of your computer's clock when you posted this, your clock is off by 12 hours. Try switching PM for AM. If both of your computers have this problem, maybe it's the company NTP server?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to loop through an array, edit the contents of an array in C#, and the loop through it again to show the edited contents? I am trying to loop through an array of products. I was wondering if it would at all be possible to change an element of the array, and then loop through it again to display it with the edited element.
Here is the code:
public enum ProductStatus
{
ForSale,
Sold,
Shipped
}
class Product
{
private string description;
private decimal price;
private ProductStatus status;
public string Description
{
get { return description; }
set { description = value; }
}
public decimal Price
{
get { return price; }
set { price = value; }
}
public ProductStatus Status
{
get { return status; }
set { status = 0; }
}
And then to instantiate the array:
Product[] products = new Product[3];
products[0] = new Product() { Description = "Dress", Price = 69.99M };
products[1] = new Product() { Description = "Hat", Price = 5.95M};
products[2] = new Product() { Description = "Slacks", Price = 32.00M};
Having overridden the ToString() method, I loop through it like so:
ProductStatus status = ProductStatus.ForSale;
ProductStatus nextStatus = status + 1;
for (int i = 0; i < products.Length; i++)
{
Product p = products[i];
Console.WriteLine("{0}: " + p.ToString(), status.ToString());
}
I'd like to use the nextStatus to change the first index's ProductStatus from "ForSale" to "Sold" (and then "Shipped" afterwards), and then loop through the array again to show the changes. How does one do that?
A: Although your question is a little unclear I suppose this is what you want (the code below is not tested).
private void ChangeStatus(ProductStatus initialStatus, Product[] products)
{
ProductStatus nextStatus = initialStatus + 1;
foreach (var p in products)
{
p.Status = nextStatus;
}
}
private void ShowProducts(Product[] products)
{
foreach (var p in products)
{
Console.WriteLine("{0}: " + p.ToString(), status.ToString());
}
}
And the output could appear as follows (assuming ForSale as initial status):
P1 (before): ForSale - P1 (after): Sold
P2 (before): Sold - P2 (after): Sold
Anyway, are you sure you want your application to behave this way? In my opinion what you are trying to achieve is slightly different, something like this:
private void ChangeStatus(Product[] products)
{
foreach (var p in products)
{
p.Status = p.Status + 1;
}
}
In this case the output would be the following:
P1 (before): ForSale - P1 (after): Sold
P2 (before): Sold - P2 (after): Shipped
Hope it helps.
A: If your question is "How can I determine the changed items and view them", you can easily use a list of their endexes:
private List<int> indexes = new List<int>();
Loop through items
{
if (item is changed)
indexes.Add(item's index);
}
A: Why not create a new collection containing the changed statuses, e.g.:
ProductStatus status = ProductStatus.ForSale;
ProductStatus nextStatus = status + 1;
var statusChangesList = new List<KeyValuePair<Product, Status>>();
foreach (var product in products)
{
statusChangesList.Add(new KeyValuePair<Product, Status>(product, product.Status));
product.Status = nextStatus;
}
foreach (var statusChange in statusChangesList)
{
Console.WriteLine("Product: " + statusChange.key + " changed status from: " + statusCahnge.value);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Framework 4.1 Foreign Key question I'm trudging ahead with an ecommerce database desgin in EF 4.1 Code First.
I've come to a situation where I think I'm justified, but not sure..
Consider:
class Download
{
int ID
string Mime
string Filename
string Extension
}
class DownloadBinary
{
int ID
int DownloadID
Download Download
byte[] Binary
}
class DownloadURL
{
int ID
int DownloadID
Download Download
string URL
}
Now I've placed the Foreign Keys for Download in the other two classes as I wish to remove nulls basically. Also this has the byproduct of allowing multiple DownloadBinary and DownloadURL classes per Download class, which seems ok. But this seems the wrong way round from an EF point of view, as the Download class does not encapsulate the DownloadBinary and DownloadURL classes.
I know I can search the DbContext and retireve DownloadBinary and DownloadURL classes for a given Download class ID, so i can get data out ok.
If I held DownloadBinary ID and DownloadURL ID in the Download class, I could be subject to nulls, which is my point for doing it this way..
I'm really expecting to enforce a one to zero or one relationship from Download to DownloadBinary or DownloadURL classes in my data input forms..
I don't see much of a problem here, but what do more experienced people think??
A: Remove DownloadID from both DownloadBinary and DownloadUrl and map ID of these classes as foreign key to ID of Download. EF supports one-to-one relation only over primary keys because it doesn't support unique keys.
modelBuilder.Entity<Download>()
.HasOptional(d => d.DownloadBinary)
.WithRequired(db => db.Download);
modelBuilder.Entity<Download>()
.HasOptional(d => d.DownloadUrl)
.WithRequired(du => du.Download);
Both DownloadBinary and DownloadUrl must not use autogenerated Id in database because their ID is defined by Download:
modelBuilder.Entity()
.Property(db => db.ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<DownoladUrl>()
.Property(du => du.ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Memory leak in javascript when using new Image() I seem to have a memory leak, caused by using the 'new Image()' in a javascript script. If I watch the used physical memory in the windows resource monitor, i get the expected increase in memory used when I load the page because it loads some quite large images using as follows:
var imgObjs = [];
// in for loop i = 0, 1, 2...
imgObjs[i] = new Image();
imgObjs[i].onload = function(event) {
// image loaded
}
imgObjs[this.img_src].src = this.img_src;
I would have though that when the page is navigated away from this would automatically destroy the references and free up the memory, but this doesn't seem to be the case. Instead, i navigate away and then go back to the page only the find the memory ramp up even more as it loads the images again without ever freeing up the previously allocated memory. I have tried manually removing references by putting code in the unload event to do this but it doesn't seem to make any difference. The variables were all initially declared with 'var':
// allow garbage collection by removing references
$(window).unload(function() {
for(var i in imgObjs) {
imgObjs[i] = null;
delete imgObjs[i];
}
delete imgObjs
// delete other variables that reference the images
});
does anyone have any pointers as to where I'm going wrong here? I thought the problem might be to do with circular references as i have built a list class where each item contains a reference to the previous and next image, but i have deeted these as follows:
delete galleries[i].pictures.Items[j].prev;
delete galleries[i].pictures.Items[j].next;
A: First off, there is no browser that I know of that leaks when you go to another page just because you have images stored in a JS array.
There are some older browsers that leak if you have circular references between DOM <==> JS where some javascript refers to a DOM element and a custom attribute on the DOM element refers back to the same javacript object, but that does not appear to be what you have here.
So ... I'd be surprised if what you're seeing is actually a leak in going from one page to the next. If you're convinced it is, then create either a plain web page that you can share with us or a jsFiddle that shows the issue and tell us what exact browser you're testing in and exactly how you're measuring the memory usage that determines you have a leak.
For it to truly be a leak, you have to consistently see memory usage go up and and up and up, every time you go to the page over and over again. Just because total memory usage is a little bit higher the second time you go to the page does not mean you have a leak. The browser has some data structures that grow (to a point) with usage like the memory-based cache, the session browsing history, etc... that are not indicative of leaks.
Second off, I don't see anything in the data structures you've shown that are illustrative of the kinds of circular references that are known to cause leaks in older browsers.
Third off, the delete operator is for removing properties from an object. That's all it's for. See these articles: Understanding Delete and MDN Delete for a lot more explanation. So, your cleanup code in the unload handler is not using delete properly. You cannot delete vars or array elements with delete. Though I can't see any reason why this code is necessary, if you were going to have it, it would be like this:
// allow garbage collection by removing references
$(window).unload(function() {
for (var i = 0; i < imgObjs.length; i++) {
imgObjs[i] = null;
}
imgObjs = null;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Taking a screenshot of flash game/animation, server-side? (or client-side?) I'm just wondering, is it possible for a server-side script to take screenshot of a flash animation (no matter the time in the animation, resolution etc) located on the server?
Also acceptable would be a solution that could make use of client-side scripting, like JavaScript, but which could then upload the screenshot to the server (actually, now that I'm thinking about it, this one makes more sense... but I'll just leave the title like that, so it sounds more interesting).
So does anyone have any idea?
For you to understand better, here is an example:
Say I'm starting a flash games website, or flash animations website. Now I already have 22,403 flash animations on my server (duh...) and want my users to be able to take a sneak peak in the game before they play it, offering them a screenshot or image from inside the game before starting (just like most of the flash game websites do...).
And yeah, I don't really want to make all the 22k-something snapshots myself (load the game, press printscreen, paste in Microsoft Paint, cut the game, save and upload... I mean, seriously?
I hope you understood me a little.
If you have any ideas, please don't hesitate to shout it to me!
A: You can use webkit and virtual X server. Here is a simple tool:
http://cutycapt.sourceforge.net/
For example, while plugin support can be enabled, and the plugins
execute properly, their rendering cannot be captured on some
platforms. Use of with caution.
Hope it helps you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php name spelling correction from mysql I have a database containing "FirstName - LastName - Company" from users
I'm looking for a spelling corrector to help me to do matching between data on a form and the database
Imagine I have "Luk - Vandbrol - Google" on my database... I want to be able to find this entry if i enter "Luc - Vandrol - Google"
Do you have anny known class that could help me?
Thanks
A: There is a component for PHP called "PHP Spell Check" which allows you to include spellcheck in your development.
You can test it and download it from http://www.phpspellcheck.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a git personal server for sharing changes between machines? Is there a way to run a no frills git server just so I work on different machines at home?
The main reason for this is that my WiFi network is slow and I'd prefer to work locally and disconnected.
I assume there's something similar to the Mercurial command hg serve.
A: There's a minimalist git daemon server. (See here for basic info, and the man page for more.)
A: A good guide to the different methods is http://www.jedi.be/blog/2009/05/06/8-ways-to-share-your-git-repository/
My preferred method is to use the plain ssh server.
A: the easiest way is just to share disks/directories using the stand OS file sharing.
Otherwise you can run a git server git-daemon or export via http see Git documentation for public repository
A: As per the comments, this is an XY Problem.
Mat's answer tells you about a minimalist git daemon server. As do others.
I'm telling you that this is probably entirely unnecessary.
If your laptop and your desktop can share a filesystem (such as via NFS, CIFS or similar), you can clone the repository like this:
git clone /path/to/repository
If your laptop and your desktop can't share a filesystem but your desktop is running an SSH service, you can clone your repository like this:
git clone ssh://[user@]server/path/to/repository
You may even be able to use other sharing services such as FTP or HTTP, as per the manual page. Setting up a dedicated git server is usually an unnecessary overhead.
Hope this helps.
A: I am using gitolite, I find it easy enough.
Here is the Official documentation and my experience.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Simple regex word question I have the regex:
TheComment = Regex.Replace(TheComment, "(\\@" + r + "\b)", "<span style=\"background:yellow;font-weight:bold;\">@" + ThisUser.Username + "</span>", RegexOptions.IgnoreCase);
This is an example pattern
(\\@to\b)
I want this to match @To but not @Tom. At the moment it's not matching, if I strip the \b away it works but it matches @Tom as well which is musn't.
A: You have to escape \ and not @. Plus, you got to move \b out of the selection.
@"(@" + r + @")\b"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sound when the app is in the Background iOS I'm trying to play a sound when my App is in the background. I use AVAudioPlayer, and it works correctly when the app is active, but in the background AVAudioPlayer doesn't play anything and I don't know how can I do.
I have thought that I could use UILocalNotification, but it shows and alert in the lockscreen and I don't want it.
Thanks for your answers. I have another doubt. If I create this audiosession, and I am playing music the system will mix both at the same time?.
How can I do to decrease ipod music volume will my app sound is playing (3 seconds) and increase again when it had finished like most of the running apps in the AppStore.
(In the background too)
This is my code in the AppDelegate
//Creamos la sesión de audio
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
And in my view when I want to play the sound:
-(void)avisosound{
// AudioSessionSetActive(YES);
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil){
}
else{
[audioPlayer play];
}
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
But when I play the sound, the ipod music stops.
A: You need to make couple of changes in plist file.
*
*Set Required background mode to App plays audio
*Set Application does not run in background to YES
Then, you need to write the following code in your AppDelegate:
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
Now, you can easily run audio while phone screen locks or your app is in the background.
A: The following tells the system to continue playing the audio even when your iPhone screen locks out:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
(Most of the time you put this in your didFinishLaunchingWithOptions.)
And to tell the system to play your audio when your app is in the background, add UIBackgroundModes and set it to audio in you plist.
(Any foreground apps that need to play audio will take precedence over these settings and your app's sound playback).
To add "ducking", to lower the volume of other audio while your audio is playing, you need to implement kAudioSessionProperty_OtherMixableAudioShouldDuck. Look for that in the Audio Session programming guide.
A: To play a sound in the background (assuming your app has set up the proper background modes), your app has to start the sound in the foreground and not stop it. The easiest ways to do this are using the Audio Queue API or the RemoteIO Audio Unit.
A: There's an article explaining what you can do in the iOS developer library. See http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Image segmentations with gradient filled regions I have to work on image segmentation. The idea is to divide an image into regions which have pixels either of the similar color or the ones which can be represented by a gradient equation (linear or radial). I have found many algorithms which do the separation based on colors but could not find anyone which handles gradients. Does someone know any such algorithm or suggestions on how to go for it.
A: Mean-Shift Segmentation might be what you are looking for. It is implemented in OpenCV. It is tolerant of smooth gradients, yielding a more natural result, or something that a human would come up with if he was converting an image to a paint-by-number.
Here is an image that was segmented with mean-shift:
A: In gradient areas, the edge function (laplacian or other edge detection functions) will detect no edge (the result will be nearly zero ("black")). So, apply an edge filter on the image, and then you will have nearly black areas (for gradient or other similarly-colored sections) outlined by bright edges (where there was a strong difference in the original image). This image should be easily segmented by most segmentation algorithms (and if they classify the bright edges as their own segment, simply merge edge pixels back with the closest black area).
Note that you may want to find and segment only the gradient areas first, and then use a more decent segmentation algorithm on the original (non-edges) image. Note also that the edge detection doesn't work exactly for the radial gradients, so you may want to actually compute the edge function twice to acheive better results
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uploading photo from server to facebook I have a facebook canvas application and I want to upload a file from my server to the user's wall.
Facebook says that a form should be created, this is what I did:
<form action="https://graph.facebook.com/me/photos?access_token=<%= @access_token %>" method="post" enctype="multipart/form-data">
<input name="source" type="hidden" value="https://young-water-9853.herokuapp.com/images/1.jpg" />
<input name="commit" type="submit" value="Upload photo" class="cupid-green" />
</form>
This is the error I received:
{
"error": {
"message": "(#324) Requires upload file",
"type": "OAuthException"
}
}
How can I make it work?
Solution:
This is the action I am using to post an image to the wall:
get '/post_photo' do
RestClient.post 'https://graph.facebook.com/me/photos', :source => open('http://i52.tinypic.com/313jaxd.jpg'), :access_token => ACCESS_TOKEN
redirect '/'
end
A: The source parameter needs to be a file object, not a url. If the user was uploading a file from their machine:
<form action="https://graph.facebook.com/me/photos?access_token=<%= @access_token %>" method="post" enctype="multipart/form-data">
<input name="source" type="file" />
<input name="commit" type="submit" value="Upload photo" class="cupid-green" />
</form>
Or if you wanted the user to upload a predefined image, you'd take care of that server-side. The rest_client gem looks like an ideal solution for this:
require 'rest_client'
RestClient.post 'https://graph.facebook.com/me/photos', :source => File.new('/path/to/your/file'), :access_token => YOUR_ACCESS_TOKEN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: H2 database> How to compact / vacuum while running? Heading
In one of my projects I am using h2 database with file storage.
According to h2 db documentation
"Empty space in the database file [is] re-used automatically. When closing the database, the database is automatically compacted for up to 200 milliseconds by default."
Empty space is created every time a row is deleted or updated. Unfortunately at runtime the database file is growing continuously.
In this discussion it is suggested to backup the database, and restore it again.
However I am searching for a solution to compact / vacuum the database at runtime, without shutting down. Is there a way do achieve this?
Of course it is an option to migrate to a database like Postgres. However my project should be very easy to install, so it would be necessary to integrate it into the installer. In general adding a dedicated database adds some overhead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Add page to pdf in php I need to add into pdf file one page after already existing first page and into this added page write text. I read somewhere, that Zend framework can do it, but I have no idea how.
Thanks in advance for answer
A: First you need to create a pdf object and assign it to a variable:
$pdf = pdf_new();
Then you need to read your pdf file into the object:
pdf_open_file($pdf, "path/to/your/pdf/file.pdf");
Now, you add a (A4) page to the pdf object:
pdf_begin_page($pdf, 595, 842);
Then, before you can write text to the page, you need to grab a font:
$arial = pdf_findfont($pdf, "Arial", "host", 1);
And state that you will be using this font:
pdf_setfont($pdf, $arial, 10);
Now you can write text to the page with:
pdf_show_xy($pdf, "Text to write to the page.", 50, 750);
We're done with the page, so close it with:
pdf_end_page($pdf);
Finally, close and save the file:
pdf_close($pdf);
Credit: Generate PDFs with PHP
Other good tutorials:
*
*How To: Create PDF With Php
*PDF Generation Using Only PHP -
Part 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Restricting arguments to certain defined constants Consider the following code
public class ColorScheme {
public static final int DARK_BLACK = 0,
WHITE = 1;
private int Scheme;
public ColorScheme() {
this.Scheme = DARK_BLACK;
}
public ColorScheme(int SchemeType) {
this.Scheme = SchemeType;
}
}
I want the argument to the constructor ColorScheme(int SchemeType) to be restricted to one of the static final int - DARK_BLACK or WHITE or other constant I may define.
For Ex: When someone instantiates the ColorScheme class, he can use
ColorScheme CS = new ColorScheme(DARK_BLACK);
while
ColorScheme CS = new ColorScheme(5); //or any other non-defined constant
should return an error.
A: You're looking for Java enums.
A: maybe you could consider to use Enum http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
A: Enum is the way to go:
public class ColorScheme {
public enum Color {DARK_BLACK,
WHITE}
private Color Scheme;
public ColorScheme() {
this.Scheme = Color.DARK_BLACK;
}
public ColorScheme(Color SchemeType) {
this.Scheme = SchemeType;
}
}
A: As Mat and Kent have already pointed out: enum's the way to go.
Enums are quite powerful, since they offer many concepts you have with classes, e.g. methods and constructors. The corresponding chapters in Effective Java from Josh Bloch, the author of enums, is definitely worth a read, since they describe the many advantages, the disadvantages, as well as several use cases, e.g. EnumMaps and EnumSets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FFmpeg/X264: Split video mid-GOP without reencoding entire stream I've got an H264 video (Stored in an MP4 file). Each GOP is approx 10s long. I want to trim the first couple of seconds off the video, which means I need to split the first GOP. Is there a way to do this without re-encoding the entire video?
I've got FFmpeg and x264 available. I'm happy to use either the FFmpeg command line, or my own program linked against ffmpeg of x264 libraries.
Thanks in advance!
A: I think you realize that some re-encoding is unavoidable. You may be able to avoid re-encoding the entire video using the following approach:
*
*Split the video into two parts: the first GOP and the rest of the video. You should be able to do this without re-encoding (use -vcodec copy)
*Convert the first GOP into something that you can easily cut, such as YUV
*Cut the YUV file
*Re-encode the cut file using the same parameters as the original video (you can get these from ffprobe.
*Join the re-encoded cut file with the rest of the video (from step one). Again, you would use -vcodec copy to ensure no re-encoding is performed.
I've never had to do this, but the FAQ seems to have a section on joining video files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Wrap a span around all children I am trying to get the contents of a div and wrap a span around it and append back to the div.
From this:
<div>
<a href="#">12</a>
Testing
</div>
To this:
<div>
<span>
<a href="#">Hehhehe</a>
Testing
</span>
</div>
So I tried this:
var span = $(document.createElement('span'));
var contents = window.jQuery(this).children();
span.append(contents);
window.jQuery(this).append(span); // I am looping here but this is the div
However, the text "Testing" is always outside the span!
How can I get everything to be within the span?
A: This should do what you want..
$('div').wrapInner('<span>');
Demo at http://jsfiddle.net/gaby/76ND5/
If in your code this refers to the div in question, then all you need is
$(this).wrapInner('<span>');
A: .children() doesn't include text nodes. Use .wrapInner to add the span around your elements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the best way to serialize circular referenced objects? Better that should be text format. The best would be json, with some standart to pointers. Binary would be also good. Remember in old times, soap has standart for this. What you suggest?
A: No problem with binary whatsoever:
[Serializable]
public class CircularTest
{
public CircularTest[] Children { get; set; }
}
class Program
{
static void Main()
{
var circularTest = new CircularTest();
circularTest.Children = new[] { circularTest };
var formatter = new BinaryFormatter();
using (var stream = File.Create("serialized.bin"))
{
formatter.Serialize(stream, circularTest);
}
using (var stream = File.OpenRead("serialized.bin"))
{
circularTest = (CircularTest)formatter.Deserialize(stream);
}
}
}
A DataContractSerializer can also cope with circular references, you just need to use a special constructor and indicate this and it will spit XML:
public class CircularTest
{
public CircularTest[] Children { get; set; }
}
class Program
{
static void Main()
{
var circularTest = new CircularTest();
circularTest.Children = new[] { circularTest };
var serializer = new DataContractSerializer(
circularTest.GetType(),
null,
100,
false,
true, // <!-- that's the important bit and indicates circular references
null
);
serializer.WriteObject(Console.OpenStandardOutput(), circularTest);
}
}
And the latest version of Json.NET supports circular references as well with JSON:
public class CircularTest
{
public CircularTest[] Children { get; set; }
}
class Program
{
static void Main()
{
var circularTest = new CircularTest();
circularTest.Children = new[] { circularTest };
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var json = JsonConvert.SerializeObject(circularTest, Formatting.Indented, settings);
Console.WriteLine(json);
}
}
produces:
{
"$id": "1",
"Children": [
{
"$ref": "1"
}
]
}
which I guess is what you was asking about.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: how to obtain entire text content of a web page within a iframe using javascript I want to obtain the text contained within a web page in an iframe.
As per an existing question on SO, the javascript code to obtain the content of a web page in an iframe is given below--
var myIFrame = document.getElementById(iFrameName); // Creating an object of the iframe
var content = myIFrame.contentWindow.document.body.innerHTML; // Getting it's content into a variable
The problem is that I want to obtain only the text content of the web page in iframe- I dont want to do this by obtaining the entire content and then parsing through it to remove images/links etc...The code above contains HTML Markup in body content of the web page--- Is there some way to obtain only the text content of web page in an iframe?
A: var myIFrame = document.getElementById(iFrameName); // Creating an object of the iframe
var myIFrameBody = myIFrame.contentWindow.document.body; // Getting it's body content into a variable
function getStrings(n, s) {
var txt, childNodes, child, max, m, i;
if (n.nodeType === 3) {
txt = trim(n.data);
if (txt.length > 0) {
s.push(txt);
}
}
else if (n.nodeType === 1) {
for (i = 0, max = n.childNodes.length; i < max; i++) {
child = n.childNodes[i];
getStrings(child, s);
}
}
}
/**
Extract the html text starting from a node n.
*/
function getText(n) {
var s = [],
result;
getStrings(n, s);
result = s.join(" ");
return result;
}
var myIFrameText = getText(myIFrameBody);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: django conditional filter OR if w:
conditions['is_discount_table'] = 'Q( is_discount_table = True )'
conditions['is_discount_banquet'] = 'Q( is_discount_banquet = True )'
pl = Place.objects.filter( **conditions ).order_by( 'name' )
SQL WHERE looks like
WHERE (
"places_place"."is_discount_banquet" = true AND
"places_place"."is_discount_table" = true
)
How to modify w condition that SQL WHERE looked like
WHERE (
"places_place"."is_discount_banquet" = true OR
"places_place"."is_discount_table" = true
)
equivalent of
Place.objects.filter( Q( is_discount_table = True ) | Q( is_discount_banquet = True ) )
A: i found the answer:
conditions_unnamed = list()
conditions_named = dict( )
if type:
conditions_named['types__id__in'] = list_unique( type.split( '-' ) )
if w:
conditions_unnamed.append( Q( is_discount_table = True ) | Q( is_discount_banquet = True ) )
pl = Place.objects.filter( *conditions_unnamed, **conditions_named ).order_by( 'name' )
if somebody knows a better solution, please share.
A: You seem to have added some additional logic. I think this is what you are trying to express:
pl = Place.objects.all()
if type:
pl = pl.filter(types__id__in=type.split( '-' ))
if w:
pl = pl.filter( Q( is_discount_table = True ) | Q( is_discount_banquet = True ) )
pl = pl.order_by( 'name' )
A: queres = {Q()}
...
if ...
queres.update({Q(deprecation_date__lte=datetime.date.today())})
if ...
queres.update({Q(deprecation_date=None)})
...
devices = Device.objects.filter(*queres)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Any reason to favor MathML syntax over TeX in MathJax? MathJax, opensource javascript library to render maths, support multiple syntaxes, including MathML and LaTeX. Are there any reason to favor the use of the MathML syntax for in-page equations vs the TeX syntax? It only looks to me that MathML is vastly more verbose.
A: Well, if you actually look closely at the coding, you will find that MathJax, as well as jsMath, and other similar javascript programs, all do pretty much the same thing. They convert what is LaTeX in the source code of the webpage, as it is served by the server, into MathML on the client side. Feel free to highlight your "LaTeX" and see what the selected source code actually looks like to the browser. You will find that it is MathML (in most cases).
Unless you use a script or a hosting site that rasterizes LaTeX into a GIF or PNG image (which is another viable option), then your LaTeX is rendered as MathML-Presentation.
In the case of MathJax, however, it also gives you the option of SVG and HTML-CSS rendering. Both of which require massive amounts of client-side source code. SVG is not really practical (unfortunately it isnt even universally recognized), but it certainly is cool. HTML-CSS, though perhaps looks better, is not readable by a math parser or XML parser... it is also the MathJax default and it puts a heavier load on the client-side. So defaulting to their MathML rendering is better, in my opinion.
Thus, if I understand your question correctly, your question is actually moot. You are already dealing with MathML in both cases. The difference is, which do you find easier to write and embed into the page? Personally, I prefer writing in LaTeX, not MathML.
I have used jsMath and most recently MathJax. But I also currently do still use Codecogs.com to convert latex into GIF on the fly. (They have both a <script> and you can use direct linking <img src=> )
The fact of the matter is, you only have two options (well, four technically). You have MathML or GIF images as the primary two. What all these scripts and hosting sites do is they facilitate a conversion from LaTeX to either GIF or MathML (or the less desirable SVG or HTML-CSS). Straight LaTeX text is as difficult to read as MathML source code - you have to have some sort of rendering process.
One enormous advantage to coding your own MathML is that you have total control over the grammar and structure of the XML-based language (in case you make it available to other math programs and sites). But the other advantages are: you do not require javascript, and therefore your visitors dont have to enable javascript.
Coincidentally, ASCIIMath is a good example of a simple javascript converting LaTeX to Unicode and HTML-CSS in a very beautiful and streamlined way.
A: If you do not need a human to write the equations, MathML is more robust. There's a clear interpretation to the mark-up, (which display mode will be used by default in all MathJax implementations?), there's a better chance for text-to-speech support for MathML. It is easy to search by XPath where your mathematical elements are, etc.
Other disadvantages of the MathJax approach are, start-up time tax, the fact it forces your browser to use Javascript.
A: MathML provides accessibility to the visually impaired, but you can display your equations as MathML even if you author them with LaTeX.
As to Elazar's question about "which display mode will be used by default in all MathJax implementations", it's strictly up to you when you set up the page. It's done with the <script> tag, as described in the MathJax documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Canvas draws lines too thick I want to draw lines on my canvas element at every 48px high. Here's my code (a little jquery selector included since I also use jQuery).
var $canvas = $('canvas')
, maxY = $canvas.outerHeight()
, maxX = $canvas.outerWidth()
, X = 0
, Y = 0
, ctx = $canvas.get(0).getContext('2d');
ctx.strokeStyle = "rgb(100,0,0)";
ctx.lineWidth = 1.0;
ctx.lineCap = "round";
while (Y < maxY) {
ctx.beginPath();
ctx.moveTo(X, Y);
ctx.lineTo(maxX, Y);
//ctx.closePath();
ctx.stroke();
Y += 48;
};
Y = 0;
What I experience is that my first line is crisp and 1px high. All my other lines are higher. Here's the result:
(source: ghentgators.be)
A: Change your initial Y to +0.5 (or -0.5) and you'll get nice lines.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Calculating dimensions of STL (stereolithography) object from .stl files How can I get the length,width and height of 3D object stored as a .stl file?
A: STL files are dimensionless, so whatever is reading the stl must know what units the file was written in.
The format of stl files is detailed in wikipedia
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can someone explain this: 0.2 + 0.1 = 0.30000000000000004?
Duplicates:
How is floating point stored? When does it matter?
Is floating point math broken?
Why does the following occur in the Python Interpreter?
>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> 0.1+0.1
0.2
>>> 0.2+0.1
0.30000000000000004
>>> 0.3-0.3
0.0
>>> 0.2+0.1
0.30000000000000004
>>>
Why doesn't 0.2 + 0.1 = 0.3?
A: That's because .1 cannot be represented exactly in a binary floating point representation. If you try
>>> .1
Python will respond with .1 because it only prints up to a certain precision, but there's already a small round-off error. The same happens with .3, but when you issue
>>> .2 + .1
0.30000000000000004
then the round-off errors in .2 and .1 accumulate. Also note:
>>> .2 + .1 == .3
False
A: Not all floating point numbers are exactly representable on a finite machine. Neither 0.1 nor 0.2 are exactly representable in binary floating point. And nor is 0.3.
A number is exactly representable if it is of the form a/b where a and b are an integers and b is a power of 2. Obviously, the data type needs to have a large enough significand to store the number also.
I recommend Rob Kennedy's useful webpage as a nice tool to explore representability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: "Bare" git repository: how can I let Apache always "see" the latest commit? We've got a "bare" git repository on a server, for a Web portal project. Several programmers, designers, etc... perform dozens of push and pull from/to it.
Now we want to test the project on the server itself, and always test the last commit through an Apache web server which is installed on the same machine the "bare" git repository is stored in.
How can we 'unbare' the repository, and let the working directory contain always and only the last commit deriving from the last push?
Or anything else aiming to achieve the same result?
A: You can use a post-receive hook to do a git pull inside your webserver document root/repository.
in your bare repository
do
mv hooks/post-receive.sample hooks/post-receive
chmod +x .git/hooks/post-receive
the post receive should be something like
#!/bin/sh
WEB_ROOT='/var/www/project'
cd $WEB_ROOT
git pull
A more elegant solution that doesn't involve that the web server area being a git repository, you can also review the git documentation about hooks
Note: if you use the simple solution, please make sure that your webserver doesn't serve the .git directory, this would give some hackers/crackers the access to the website source code!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ActiveMQ: Publish Messages in bulk, persistent, but not async? is it possible to store a large amount of messages in bulk?
I want to send them sync, persistent, but to get speed very much at one time.
I am using NMS, the .net version of the java-framework. But if you only know how to do this in java, it would even help. Maybe I can find a solution for .net more easier.
I thought of things like transactions. But I only got transactions to work for consumers, not for producers.
A: Conventional wisdom used to suggest that if you wanted maximum throughput when sending in bulk, then you should a SESSION_TRANSACTED acknowledgement mode and batch all of the message sends together with a .commit().
Unfortunately, here's a benchmark showing this not to be the case http://www.jakubkorab.net/2011/09/batching-jms-messages-for-performance-not-so-fast.html and that are you better off just sending them as normal without transactions. If you are already using transactions, then it may make sense to try and batch them.
My advice here also is that unless you are dealing with messages that are extremely time sensitive, the rate at which you produce isn't going to be that big of a deal - you should be more concerned with bandwidth as opposed to speed of message sends. If you don't mind your messages being out of order you can have multiple producers produce these messages to a given destination... or if you need them in order use multiple producers and then a resequencer after they are in the broker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ActionScript 3 feather vector I've been looking at gradient masks to add a feathered/blurred effect to the edges of some shapes I'm drawing in AS3 (only with code) but I need it to work on squares/rectangles as well as circles.
Is there any kind of matrix that allows for this type of transformation? I could really use some guidance.
The target is to keep the file size down which means I don't want to add any PNG's to use as masks.
Thanks in advance.
[EDIT]
I've put the code that I'm using to draw the shape and I'm trying to put a feathered edge to each shape (except for cases 3 and 4 which I'm trying to draw shapes with for a different product type) The variable imageCont is the container for the image I'm trying to mask. But I don't seem to be able to put a feathered edge on either the circles/ovals or on the rectangle.
public function drawMask (drawI:int, clipWidth:int, clipHeight:int) {
var maskingShape:Shape = new Shape();
this.addChild(maskingShape);
maskingShape.x = 0;
maskingShape.y = 0;
var matr:Matrix = new Matrix();
var colors:Array = [0xFFFFFF, 0xFFFFFF];
var alphas:Array = [1, 0];
var ratios:Array = [200,255];
matr.createGradientBox( clipWidth, clipHeight );
//Calculate the positions automatically so they're centered
var centerX = 250 - (clipWidth / 2);
var centerY = 250 - (clipHeight / 2);
maskingShape.graphics.lineStyle();
//Only draw what we wanted..
switch ( drawI ) {
case 1:
showBalloonApp();
maskingShape.graphics.beginGradientFill ( GradientType.RADIAL, colors, alphas, ratios, matr );
maskingShape.graphics.drawEllipse ( centerX, centerY, clipWidth, clipHeight );
break;
case 2:
showBalloonApp();
maskingShape.graphics.beginGradientFill ( GradientType.RADIAL, colors, alphas, ratios, matr );
maskingShape.graphics.drawRoundRect ( centerX, centerY, clipWidth, clipHeight, 100, 100 );
break;
case 3:
hideBalloonApp();
//verticle shadow
maskingShape.graphics.beginFill ( 0x3B3B3B, 0.65 );
maskingShape.graphics.drawRect ( ( centerX + clipWidth - 30 ), centerY, 30, clipHeight );
maskingShape.graphics.endFill();
//horizontal shadow
maskingShape.graphics.beginFill ( 0x3B3B3B, 0.65 );
maskingShape.graphics.drawRect ( centerX, ( centerY + clipHeight - 30 ), clipWidth, 30 );
maskingShape.graphics.endFill();
//rectangle
maskingShape.graphics.drawRect ( centerX, centerY, clipWidth, clipHeight );
break;
case 4:
hideBalloonApp();
//verticle shadow
maskingShape.graphics.beginFill ( 0x3B3B3B, .65 );
maskingShape.graphics.drawRect ( ( centerX + clipWidth - 20 ), centerY, 20, clipHeight );
maskingShape.graphics.endFill();
//horizontal shadow
maskingShape.graphics.beginFill ( 0x3B3B3B, .65 );
maskingShape.graphics.drawRect ( centerX, ( centerY + clipHeight - 20 ), clipWidth, 20 );
maskingShape.graphics.endFill();
//rectangle
maskingShape.graphics.drawRect ( centerX, centerY, clipWidth, clipHeight );
break;
default:
showBalloonApp( );
maskingShape.graphics.beginGradientFill ( GradientType.RADIAL, colors, alphas, ratios, matr );
maskingShape.graphics.drawEllipse ( centerX, centerY, clipWidth, clipHeight );
break;
}
//End the filling process
maskingShape.graphics.endFill ( );
//Cache them as Bitmap items
imageCont.cacheAsBitmap = true;
maskingShape.cacheAsBitmap = true;
//Apply the mask
imageCont.mask = maskingShape;
}
A: Since you don't supply any code or info on what you have tried, it is a bit difficult to know how to answers, so I'll start with some of the basics - that both the mask and the masked DisplayObject has be be bitmaps for gradient masks to work, in the line of this schematic code:
gradientMask.cacheAsBitmap = true;
drawing.cacheAsBitmap = true;
drawing.mask = gradientMask;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Selecting columns from resultset into array I'm trying to get a number of columns from a PDO resultset into seperate arrays, so resulting as such:
<?php
$query = 'SELECT col1,col2 FROM tbl_imaginary';
...
$col1 = array(col1_row1, col1_row2,...);
$col2 = array(col2_row1, col2_row2,...);
?>
I know I could loop through the resultset with fetch, but it seems more efficient to use fetchAll(PDO:FETCH_COLUMN). However, once you do this, you can't perform it again unless you perform execute() on the statement handle again. I get why, you can't empty the cookie jar and then do the same again unless you fill it up again - kind of thing. So I thought I would copy the statement handle object and fetch columns of it as such:
<?php
$sh->execute();
for ($i=0; $i<$sh->columnCount(); $i++)
{
$tmp_sh = $sh;
$output[$i] = $tmp_sh->fetchAll(PDO::FETCH_COLUMN);
}
?>
However, this, just like doing fetchAll() on the original statement handle itself, outputs only the first column and not the second.
If anyone would be so kind to explain this behaviour to me and / or suggest a solution I would be most grateful.
Thank you very much in advance for your time.
Edit: So basically I want to get 2 (or more) columns from one resultset as seperate arrays, just like you would if you would perform 2 (or more) individual queries on 1 single column. The above is mostly an explanation of how I've tried to do this so far.
A: Why do you need two separate arrays?
$statement = $db->prepare('SELECT col1, col2 FROM tbl_imaginary');
$statement->execute();
foreach($sth->fetchAll() as $row) {
echo $row['col1'], $row['col2'];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Questions about Bean Validation vs JSF validation? I have some questions about Bean Validation and JSF validation, currently I am using Bean validation:
*
*With the JSF validation, the validation works client side only, no request sent to server, and Bean validation works on server?
*If javascript is disabled are both will work JSF & Bean Validation, or only bean validation?
*What are the disadvantages of Bean validation if there are any?
A: *
*That is not true. The validations are applied during the jsf life cycle by Process Validations.
"Conversion and validation occurs when the JSF runtime calls the
processValidators() method on each component in the view hierarchy.
The processValidators() method will first initiate any data conversion
that is required before validating the components value against the
application’s validation rules. If there are any errors during the
conversion or validation process the component is marked invalid and
an error message is generated and queued in the FacesContext object.
If a component is marked invalid, JSF advances directly to the render
response phase, which will display the current view with the queued
validation error messages. If there are no validation errors, JSF
advances to the update model values phase." - johnderinger.wordpress.com
You can also find this information in the specification.
*Both work without javascript.
*This is more a question of programming style. I think validation is better made in the model than in the view, because it removes logic from the view and it is more DRY (don't repeat yourself). If you use a bean multiple time, you will have to write the validation only once with bean validation. You should also know that bean validation overwrite constraints in JSF.
More information how to use bean validation, you can find here and the specification here.
For more information about the integrated JSF validation, you should visit this site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Table CSS not working when using position I am experimenting with a fixed header table (I have seen many plugins online but I want to do it myself using PURELY CSS) at http://dev.driz.co.uk/table.html
However I have two issues:
*
*The headers doesn't stretch the width of the table anymore and is no longer in sync with the table rows below. How do I fix this?
*I have put a border around the table and also around the table cells and so have now ended up with double borders in some places. How can I get around this? As I need the table to have the border as the cells will not always be on screen and cannot be relied on to provide the box around the table.
If someone can help, it'd be much appreciated.
A: Through experimenting I've found that position:absolute on either tbody or thead is causing the issue where your table head items aren't lining up to the table data. Absolutely positioning an element breaks it out of the rendering flow of the page. So adding position:absolute to thead causes the header items to collapse to the content in them and adding it to tbody breaks the table data cells from normal flow which means thead cannot relate its cell widths to tbody's.
This is just what I've found but if I'm wrong I'm open to correction.
A: Using table-layout: fixed; solves the issues!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: help with perl regex rules I would need some help with a regex issue in perl. I need to match non_letter characters "nucleated" around letter characters string (of size one).
That is to say... I have a string like
CDF((E)TR)FT
and I want to match ALL the following:
C, D, F((, ((E), )T, R), )F, T.
I was trying with something like
/([^A-Za-z]*[A-Za-z]{1}[^A-Za-z]*)/
but I'm obtaining:
C, D, F((, E), T, R), F, T.
Is like if once a non-letter characters has been matched it can NOT be matched again in another matching.
How can I do this?
A: A little late on this. Somebody has probably proposed this already.
I would consume the capture in the assertion to the left (via backref) and not consume the capture in the assertion to the right. All the captures can be seen, but the last one is not consumed, so the next pass continues right after the last atomic letter was found.
Character class is simplified for clarity:
/(?=([^A-Z]*))(\1[A-Z])(?=([^A-Z]*))/
(?=([^A-Z]*)) # ahead is optional non A-Z characters, captured in grp 1
(\1[A-Z]) # capture grp 2, consume capture group 1, plus atomic letter
(?=([^A-Z]*)) # ahead is optional non A-Z characters, captured in grp 3
Do globally, in a while loop, combined groups $2$3 (in that order) are the answer.
Test:
$samp = 'CDF((E)TR)FT';
while ( $samp =~ /(?=([^A-Z]*))(\1[A-Z])(?=([^A-Z]*))/g )
{
print "$2$3, ";
}
output:
C, D, F((, ((E), )T, R), )F, T,
A: The problem is that you are consuming your characters or non letter characters the first time you encounter them, therefore you can't match all that you want. A solution would be to use different regexes for different patterns and combine the results at the end so that you could have your desired result :
This will match all character starting with a non character followed by a single character but NOT followed by a non character
[^A-Z]+[A-Z](?![^A-Z])
This will match a character enclosed by non characters, containing overlapping results :
(?=([^A-Z]+[A-Z][^A-Z]+))
This will match a character followed by one or more non characters only if it is not preceded by a non character :
(?<![^A-Z])[A-Z][^A-Z]+
And this will match single characters which are not enclosed to non characters
(?<![^A-Z])[A-Z](?![^A-Z])
By combining the results you will have the correct desired result:
C,D,T, )T, )F, ((E), F((, R)
Also if you understand the small parts you could join this into one Regex :
#!/usr/local/bin/perl
use strict;
my $subject = "0C0CC(R)CC(L)C0";
while ($subject =~ m/(?=([^A-Z]+[A-Z][^A-Z]+))|(?=((?<![^A-Z])[A-Z][^A-Z]+))|(?=((?<![^A-Z])[A-Z](?![^A-Z])))|(?=([^A-Z]+[A-Z](?![^A-Z])))/g) {
# matched text = $1, $2, $3, $4
print $1, " " if defined $1;
print $2, " " if defined $2;
print $3, " " if defined $3;
print $4, " " if defined $4;
}
Output :
0C0 0C C( (R) )C C( (L) )C0
A: You're right, once a character has been consumed in a regex match, it can't be matched again. In regex flavors that fully support lookaround assertions, you could do it with the regex
(?<=(\P{L}*))\p{L}(?=(\P{L}*))
where the match result would be the letter, and $1 and $2 would contain the non-letters around it. Since they are only matched in the context of lookaround assertions, they are not consumed in the match and can therefore be matched multiple times. You then need to construct the match result as $1 + $& + $2. This approach would work in .NET, for example.
In most other flavors (including Perl) that have limited support for lookaround, you can take a mixed approach, which is necessary because lookbehind expressions don't allow for indefinite repetition:
\P{L}*\p{L}(?=(\P{L}*))
Now $& will contain the non-letter characters before the letter and the letter itself, and $1 contains any non-letter characters that follow the letter.
while ($subject =~ m/\P{L}*\p{L}(?=(\P{L}*))/g) {
# matched text = $& . $1
}
A: Or, you could do it the hard way and tokenize first, then process the tokens:
#!/usr/bin/perl
use warnings;
use strict;
my $str = 'CDF((E)TR)FT';
my @nucleated = nucleat($str);
print "$_\n" for @nucleated;
sub nucleat {
my($s) = @_;
my @parts; # return list stored here
my @tokens = grep length, split /([a-z])/i, $s;
# bracket the tokens with empty strings to avoid warnings
unshift @tokens, '';
push @tokens, '';
foreach my $i (0..$#tokens) {
next unless $tokens[$i] =~ /^[a-z]$/i; # one element per letter token
my $str = '';
if ($tokens[$i-1] !~ /^[a-z]$/i) { # punc before letter
$str .= $tokens[$i-1];
}
$str .= $tokens[$i]; # the letter
if ($tokens[$i+1] !~ /^[a-z]$/i) { # punc after letter
$str .= $tokens[$i+1];
}
push @parts, $str;
}
return @parts;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Weighted randomness. How could I give more weight to rows that have just been added to the database? I'm retrieving 4 random rows from a table. However, I'd like it such that more weight is given to rows that had just been inserted into the table, without penalizing older rows much.
Is there a way to do this in PHP / SQL?
A: SELECT *, (RAND() / id) AS o FROM your_table ORDER BY o LIMIT 4
This will order by o, where as o is some random integer between 0 and 1 / id, which means, the older your row, the lower it's o value will be (but still in random order).
A: I think an agreeable solution would be to use an asymptotic function (1/x) in combination with weighting.
The following has been tested:
SELECT *, (Rand()*10 + (1/(max_id - id + 1))) AS weighted_random
FROM tbl1
ORDER BY weighted_random
DESC LIMIT 4
If you want to get the max_id within the query above, just replace max_id with:
(SELECT id FROM tbl1 ORDER BY id DESC LIMIT 1)
Examples:
Let's say your max_id is 1000 ...
For each of several ids I will calculate out the value:
1/(1000 - id + 1) , which simplifies out to 1/(1001 - id):
id: 1000
1/(1001-1000) = 1/1 = 1
id: 999
1/(1001-999) = 1/2 = .5
id: 998
1/(1001-998) = 1/3 = .333
id: 991
1/(1001-991) = 1/10 = .1
id: 901
1/(1001-901) = 1/100 = .01
The nature of this 1/x makes it so that only the numbers close to max have any significant weighting.
You can see a graph of + more about asymptotic functions here:
http://zonalandeducation.com/mmts/functionInstitute/rationalFunctions/oneOverX/oneOverX.html
Note that the right side of the graph with positive numbers is the only part relevant to this specific problem.
Manipulating our equation to do different things:
(Rand()*a + (1/(b*(max_id - id + 1/b))))
I have added two values, "a", and "b"... each one will do different things:
The larger "a" gets, the less influence order has on selection. It is important to have a relatively large "a", or pretty much only recent ids will be selected.
The larger "b" gets, the more quickly the asymptotic curve will decay to insignificant weighting. If you want more of the recent rows to be weighted, I would suggest experimenting with values of "b" such as: .5, .25, or .1.
The 1/b at the end of the equation offsets problems you have with smaller values of b that are less than one.
Note:
This is not a very efficient solution when you have a large number of ids (just like the other solutions presented so far), since it calculates a value for each separate id.
A: ... ORDER BY (RAND() + 0.5 * id/maxId)
This will add half of the id/maxId ration to the random value. I.e. for the newest entry 0.5 is added (as id/maxId = 1) and for the oldest entry nothing is added.
Similarly you can also implement other weighting functions. This depends on how exactly you want to weight the values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Couchdb: Access to two documents in a shows function I'm trying to create a show function which needs to access to two documents: The document in 'doc' reference and another document called 'users'
My function looks like:
function(doc,req){
var friends = doc.friends;
var listFriends = [];
for(int i = 0; i<friends.length; i++){
var phone = friends[i].phone;
if(users[phone] != "" ){
listFriends.push(users[phone]);
}
}
return JSON.stringify(listFriends);
}
I'm not an expert nor javascript neither couchdb. My question is, Is it possible to access to the second document (users) in a similar way like in the code? So far it returns a compilation error.
Thanks
A: You can only access one document in a CouchDB show function. You could look at using a list function, which works on view results instead of documents.
Create a view where the two documents collate together (appear side-by-side in the view order) and you achieve an effect pretty close to what you wanted to achieve with the show function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: is ajax-PHP-MySQL a good combination for a chat room app? I plan to create a small chat room for my friends at my University.
As I don't want to invest any money, I will use a free host which doesn't allow me to install an IRC server.Also I like using ajax and PHP as I already know them.
Is a self-refreshing ajax and PHP page a good idea? like each second, the ajax triggers a PHP script which returns latest, let's say 20 MySQL entries in the chat history.
When a user writes something, it is inserted in the MySQL DB, as you probably already figured out.
Is this a good idea?
Do you have any other idea for saving the messages? something more optimized than MySQL?
Or any totally different idea that could fulfill my purpose?
Thanks in advance!
andy :)
EDIT: what is better: MySQL DB or text file? (text file is preferred by jquery, why?)
A: You can save a lot of HDD speed if you using memory tables, and you nee choose right indexes.
Example DB structure:
CREATE TABLE `chat` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`channel` varchar(16) NOT NULL,
`user` varchar(32) NOT NULL,
`text` varchar(255) NOT NULL,
`private` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `private` (`private`),
KEY `channel` (`channel`)
) ENGINE=MEMORY
I got about 70-80 users online, but don't get any load on server (server with 2GHz CPU)
A: Maybe a free host should have bad database. So, if you continously access to it, your chat would be really slow (unless the chat is not going to be use a lot).
Anyways, there are some free options that you can use for your purposes (instead of developing by yourself):
http://www.phpfreechat.net/
http://www.phpopenchat.org/
http://hot-things.net/blab-lite-ajax-chat
And here are some tutorials with examples:
http://css-tricks.com/4371-jquery-php-chat/
http://www.tutorialized.com/tutorials/PHP/Chat-Systems/1
http://php.resourceindex.com/Complete_Scripts/Chat/Shoutbox/
Regards!
A: This is a pretty typical approach to a basic chat room and seems just fine to me. The only thing I would suggest is assign each chat record an auto-increment id so your ajax can track the latest message it's received. This way, if the last received message has an ID of 100, ajax can request items that have an ID of 101 or higher. Then you're only pulling new messages and they can just be appended to the chat window, instead of refreshing the whole page.
A: Why would you want to invent electricity again? As you said:
Or any totally different idea that could fulfill my purpose?
There are plenty of chat rooms, why you do not use them?
Anyways from programming perspective, if you plan to make small chat room, your idea seems nice. But as the users increment, you would be facing an overload on the server and may cause crashes on a free host.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: File format that is simple like XML but smaller I'm creating a map editor that saves maps for something. Currently, I've been saving it in XML (because it is built into the .net framework). The problem is, XML is very bloated and there could be thousands of elements per file.
Is there any other simple to use formats (that I don't have to create a complicated parser for) to can store just some simple values?
A: Take a look at JSON http://en.wikipedia.org/wiki/JSON
or protobuf http://code.google.com/p/protobuf/.
For both formats .NET libraries exists.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Calling non-library code from an Android library Since Android introduced library projects, I've been converting my app into a library so that I can make several versions with appropriate tweaks (for example, a free and pro version using the same code base, but changing a few things).
I initially had trouble allowing the library project's code access to fields in my sub-projects. In other words, my free and pro versions each had a class with a few constants in them, which the library project would use to distinguish certain features.
In the sub-project, I extended the library's main activity and added a static initialisation block which uses reflection to change the values of fields in the library.
public class MyMainActivityProVersion extends MyMainActivity {
public static final String TAG = Constants.APP_NAME + "/SubClass";
static {
try {
ConstantsHelper.setConstants(Constants.class);
} catch (Exception e) {
Log.d(TAG, "--- Constants not initialised! ---");
e.printStackTrace();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
In this code, ConstantsHelper is in the library, and I am providing Constants.class from my sub-project. This initialises the constants in the library project.
My approach works great, except for one particular use case. When the app hasn't been used in a while and it is 'stopped' by the OS, the static fields in ConstantsHelper are forgotten.
The constants are supposed to be reset by the main activity (as shown above), but the main activity isn't even launched because the OS resumes a different activity. The result of this is that the initialisation of the constants is forgotten and I cannot re-initialise them because the resumed activity is in the library (which has no knowledge of the sub-project).
How can I 'tell' other activities in the library to call code from sub-projects on resuming? Alternatively, is there a way to ensure that some code in my sub-project is called on every resume?
A: I think you're "cheating" by trying to share data across two Activities through static members. This happens to work when they're in the same, or related, classloaders. Here I believe Android uses separate classloaders for separate Activities, but, child Activities are in child classloaders. So ViewActivity happens to be able to see up into the parent classloader and see statics for the parent. Later I believe that parent goes away, and so your child re-loads MyMainActivity locally when you next access it and it's not initialized as you wanted. (Well, if it's not that, it's something very like this explanation.)
I think there are some more robust alternatives. You could use the LicenseChecker API to decide whether you're in a free or for-pay version rather than rely on details of the activity lifecycle and classloader. That's probably going to be better as it protects you from other types of unauthorized use.
A: I'm afraid I never found a good answer to this question. I'll probably continue with my terrible use of reflection and figure out some hacky workaround.
I felt I should come back and at least point out that I didn't solve this for the benefit of others who come to this page.
A: You can resolve this using Android resources.
Basically, define your constants in a resources xml values file in your Library project
E.g. "lib project"\values\constants.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<bool name="const_free_version">false</bool>
<string name="const_a_constant">pippo</bool>
</resources>
Then, in your sub-project you can redefine the lib-project values using a different resources xml values file:
E.g. "sub project"\values\constants.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<bool name="const_free_version">true</bool>
</resources>
In your lib project code when you refer to R.bool.const_free_version you get the actual value based on sub-project constant values xml.
Note that you don't have to redefine every values defined in the lib project constants.xml but only the ones you need different in your sub project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.