text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Developing ui using Ext-js I m new to Ext-js .I m developing a form.but not able to allign it to center.
This is my code
Ext.onReady(function()
{
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
var reg_form = new Ext.FormPanel({
renderTo: document.body,
title: 'Employee Registration Form',
width:600,
height:500,
bodyStyle: 'padding:10px 10px 15px 15px;background:#dfe8f6;',
items: [
{
xtype: 'numberfield',
fieldLabel: 'Employee Id',
name: 'id',
decimalPrecision:2,
allowBlank: false
},
{
xtype: 'textfield',
fieldLabel: 'Employee Name',
name: 'name',
allowBlank: false,
vtype:'alpha'
}
]
});
});
Thank you in advanced.
A: You'll need to apply css to do that, or use the x & y configs of formpanel
A: One more way to solve this problem:
use
Ext.Window({
maximizeble : false,
resizeble : false,
closable: false,
minimizeble: false,
...
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get return value of php function into my jquery script I a writing a pic upload script. The script moves the picture to a directory and also puts it into a database. I want to return the directory of this script to my Jquery function, and So I can then add it to a <iframe> or whatever. I hope that I am running the script, but I am not sure if that is indeed occurring. To make sure, how do I get the return value of a php function which is called by an $(jquery).Ajax() call?
A: I would suggest using google next time and also reading official manuals..
http://api.jquery.com/jQuery.ajax/
good luck!
this is what you are looking for.
$.ajax({
success: function(data, textStatus, jqXHR){}
});
A: Just echo the path in the php script and it will show up in the data argument of the ajax callback.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: filtering specific lines in C# I have searched but did not find a solid solution for my project that works. What I want to do is open up a text file and filter it for only lines that start with "description".
This is only a small sample of whats in my text file:
interface Ethernet1/5
description INFRA:TRUNK:myserver4
switchport mode trunk
switchport trunk native vlan 64
spanning-tree mst pre-standard
spanning-tree guard root
udld aggressive
no shutdown
interface Ethernet1/6
description INFRA:TRUNK:easyserver99
switchport mode trunk
switchport trunk native vlan 99
spanning-tree mst pre-standard
spanning-tree guard root
udld aggressive
no shutdown
This is my code that I am using right now but it is not getting the job done.
private void scrapeConfig_Click(object sender, EventArgs e)
{
string textline;
string description;
//Open and read file
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(Chosen_File);
textBox1.Text = objReader.ReadToEnd();
//Scrape for certain lines
do
{
textline = objReader.ReadLine() + "\r\n";
textBox1.Text = textline;
} while (objReader.Peek() != -1);
//Close
objReader.Close();
}
Thank you for your help in advance!
A: var lines = File.ReadAllLines(filepath)
.Select(l=>l.Trim())
.Where(l=>l.StartsWith("description"));
textBox1.Text = String.Join(Environment.NewLine, lines);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails Devise User help In devise how would I, I am not sure how to phrase it, return a user.
I am able to user_signed_in? but what about user.
I want to check in show if @user is the same one as the user that is currently signed in.
A: Devise has methods like current_user which returns the "user" that is logged in.
Also, depending on your "User" model the helper methods will be adjust accordingly. So if you have an Admin class that is your devise model, you can use something like current_admin, and so on.
A: Devise has a current_user helper that's available.
A: You could do this:
def show
@user = User.find(params[:id])
if @user == current_user
# something
end
end
But maybe you just want to do this?
class UsersController < ApplicationController
before_filter :authenticate_user!
def show
@user = User.find(params[:id])
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Downloading and parsing JSON kit on iOS I am trying to parse this from a webserver to a tableview in iOS
{
"transactions": [
{
"ID": "350",
"description": "Macbook Pro 17 inch",
"price": "2811.83"
},
{
"ID": "351",
"description": "Macbook - white",
"price": "1720.10"
},
{
"ID": "352",
"description": "iPad 2",
"price": "650.00"
},
{
"ID": "353",
"description": "Macbook Pro 17 inch",
"price": "3233.98"
},
{
"ID": "354",
"description": "Macbook Pro 15 inch",
"price": "2100.55"
},
{
"ID": "355",
"description": "Macbook Air",
"price": "899.99"
},
{
"ID": "356",
"description": "Mac Pro",
"price": "3400.77"
}
]
}
The only things I want from this are the descriptions and the prices. I need to add up the price of each item and get a total. Each transaction name needs to be stored in an NSArray and then displayed in a UITableView.
Any help? The JSONkit doesnt give me the SBJSON parser
A: I really liked JSONKit because of its simplicity and speed. You have to realize, what it returns is the top level construct as an object - so you have to think about it. It will be a NSDictionary (so you can typecast it), and it will have one key "transactions".
This key will return an NSArray of NSDictionary objects, each of which will have the keys ID, description, and price.
So something like this (where itemListData is the JSON data fetched from the URL for example):
JSONDecoder *decoder = [JSONDecoder decoderWithParseOptions:JKParseOptionStrict];
NSData *immutableItemList = [itemListData copy];
NSArray *returnedData = (NSArray *) [[decoder objectWithData:immutableItemList] objectForKey:@"transactions"];
So, we took the raw JSON data, instantiated a decoder, then decoded it into a dictionary - and retrieved the 1 object in the dictionary (as an array in this case, because that's what it is). Not too bad for a newbie, eh?
(I should add - the reason I make an immutable copy of the NSData, is that this code snippet is in an asynchronous download, triggered in the connectionDidFinishLoading method.)
A: Hey man so what I have done in the past is go to facebook and download their developer sdk. In that sdk is a great JSON parsing tool. You can find it here http://developers.facebook.com/docs/reference/iossdk/
Then you simply add that to your project and in you header do an
#import "JSON.h"
and then when you get that string you say
NSDictionary *data = [my_data_string JSONValue];
NSArray *transactions = [data objectForKey:@"Transactions"];
and that should work:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: YUI Listener set on startup lost I'm trying to monitor the clicks on a web page that is written in YUI2.
The events seem to be getting wiped away and the callback function isn't getting called.
The links that I am trying to monitor are all of class 'action-link', but none have an id set on the page. I tried calling YAHOO.util.Event.addListener() first with the actual element, but that didn't work. Next I tried adding an id to each of the element and then calling it, but that still didn't work.
But using the JS debugger, I see that the element id's have been added to all of the links. But the Listeners are not set. In the debugger, I can call YAHOO.util.Event.getListeners() on the various links and see that they are all null. Yet, in the debugger I can manually call YAHOO.util.Event.addListener(elementIDString, "click", fnCallback) and then clicking on the link causes the callback to be entered.
function fnCallback(e) {
alert("click event: " + e.currentTarget.title);
}
function afterLoad()
{
var elements = YAHOO.util.Dom.getElementsByClassName('action-link');
for ( var element in elements )
{
if(elements[element].id=="") elements[element].id = "el_" + element;
YAHOO.util.Event.addListener(elements1[element].id, "click", fnCallback);
}
}
YAHOO.util.Event.onContentReady( "Share", afterLoad, null, false );
A: YAHOO.util.Event.addListener preferably takes a DOM element as its first argument like this:
function afterLoad()
{
var elements = YAHOO.util.Dom.getElementsByClassName('action-link');
for (var i = 0; i < elements.length; i++)
{
YAHOO.util.Event.addListener(elements[i], "click", fnCallback);
}
}
YAHOO.util.Event.onDOMReady(afterLoad);
It can also be passed an id string, but that is not required in this case since you already have a list of DOM elements.
In addition, you should not iterate an array with for x in yy as that can easily include non-numeric indexes such as custom properties.
Or you can write it this way using an anonymous function:
YAHOO.util.Event.onDOMReady(function() {
var elements = YAHOO.util.Dom.getElementsByClassName('action-link');
for (var i = 0; i < elements.length; i++) {
YAHOO.util.Event.addListener(elements[i], "click", fnCallback);
}
});
FYI, YAHOO.util.Event.onContentReady("Share", afterLoad) will only work if "Share" is the id of an item in the page AND, the items you want to operate on in afterLoad are before that item in the page or children of that item in the page. Since I was unsure if this might also be a part of the problem, I switched to onDOMReady() which is simpler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP How to I make my textinput accept single quote or Double quotes How do I make my textinput accept apostrophe or double quotes?
Everytime a user type's in this one: John's Birthday, I store this one in the database using mysql_real_escape_string().
What I wanted to do in here is to retrieve it in my text input.
I tried this one
<input type='text' name='title' value='<?php echo $values->title; ?>' />
The problem here is it removes the single quote and the letters that comes after the quote.
I tried to changed the value= '' from value="" but what if a user types a word that has example this one:
"You and Me". The problem is still in there.
I was thinking to use str_replace in doing this one and replace the ' into `, but again I was thinking that maybe there's an easy way to do it.
Any help would be greatly appreciated.
Thanks!
A: Check out this: http://www.primitivetype.com/articles/quotes_inputs.php
Basically, call htmlentities on your output before placing it in the form's value. This will turn characters like ' into the html equivalent '.
e.g.
<input ... value='<?php echo htmlentities($values->title, ENT_QUOTES); ?>' />
A: You can replace double quotes with ". ' for single quotes.
A: Replace single quote with ‘
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to use properties from a property file within a Maven script? I want to use properties that are defined in a property file in a Maven script, in a plugin configuration section. How can I do that?
Extract from my Maven script:
...
<configuration>
<url>${jdbc.url}</url>
</configuration>
...
And my property file (jdbc.properties) is somewhere in my classpath
jcbc.url=some.url.to.use
Thanks.
A: Use the properties plugin. And it's called a POM, not a script. It may seem like a trivial difference, but a POM describes a project and how it should be built, where a script is a sequence of commands saying what needs to be done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Devise - One Model and Multiple Different Registration Views I want to use Devise for authentication in rails 3.1.
I've created a pricing table on a static "signup" page that has three options. Level A, B and C.
I want to either pass the signup selection to devise as a parameter, or create separate views for the different options, but use the same User model.
I'm not really sure which way to go, or how to customize devise in a way to handle this.
Any input would be greatly appreciated! We're rails newbies.
A: 1) put an attribute "subscription_level" into your user model
2) create views which determine what the value of current_user.subscription_level is,
and which display different content depending on it's value...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to move all comment replies under the ones replied to on my Blogspot blog? Here is the location of the comments I need help with on my scrap Blogger/blogspot blog.
I'm trying to move the replies under the ones they reply to.
*
*I want to move the reply starting from the <li> node it is in, then
*place it in a created <ul class="children"> tag inside of the <li> node of which the comment replies to
*I also want to remove the reply from the moved comment(s)
The comments look like this:
<li class="comments">...</li>
<li class="comments">...</li>
<li class="comments">...</li>
When the comment is moved, it should look like:
<li class="comment">
<div class="comment-body>...</div>
<ul class="children"> /* Inserted via javascript */
<li class="comment">...</li> /* This is the moved comment */
</ul>
</li>
<li class="comment">...</li>
If you are using Firebug, you can see the threaded look I'm looking for by moving an <li class="comment"> inside of another.
Help me please
A: Instead of doing that, you could use the ::first-child pseudo selector to move the first comment or parent comment to the left. You can do this by applying a margin to all the comments except for the first-child one.
Update:
How to use JQuery for this.
*
*Get the contents of a comment and store them in a variable.
*Destroy the HTML tag that stores the comment.
*Use append to put the contents at the end of a div.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R solver optimization problem I have a data frame in r :
buys ges dif bin
1 22.34 12 10.34 0
2 55.56 12 43.56 0
3 78.33 12 66.33 0
4 9.99 12 2.01 1
.. .. .. .. ..
dif is just abs(buys-ges) and bin is an ifelse formula that is 1 if dif is <=10 and 0 otherwise. I'm trying to maximize the sum of the bin column by changing the ges column. The constraint is that ges is the same for all rows. I've tried a couple packages but can't figure out maximizing or optimizing. Thanks for any suggestions.
buys <- rnorm(1:100)
> buys <- data.frame(a*100)
> buys <- round(abs(a), 2)
> summary(buys)
a...100 gs dif bin
Min. : 0.89 Min. :15 Min. : 1.76 Min. :0.00
1st Qu.: 38.29 1st Qu.:15 1st Qu.: 23.29 1st Qu.:0.00
Median : 72.89 Median :15 Median : 57.88 Median :0.00
Mean : 83.91 Mean :15 Mean : 70.52 Mean :0.13
3rd Qu.:123.50 3rd Qu.:15 3rd Qu.:108.50 3rd Qu.:0.00
Max. :269.11 Max. :15 Max. :254.11 Max. :1.00
> gs1 <- 5
> buys$gs <- gs1
> buys$dif <- abs(buys[,1] - buys$gs)
> buys$bin <- ifelse(buys$dif<=10,1,0)
> colnames(buys) <- c("buys","gs","dif","bin")
> head(buys)
buys gs dif bin
1 7.48 5 2.48 1
2 79.08 5 74.08 0
3 139.22 5 134.22 0
4 41.60 5 36.60 0
5 38.35 5 33.35 0
6 157.72 5 152.72 0
> sum(buys$bin)
[1] 10
> num_buys=function(x)
+ {
+ return(length(buys$buys[buys$buys>=x-10 | buys$buys<=x+10]))
+ }
> ans2 <- optimize(f=num_buys,interval=c(min(buys$buys),max(buys$buys)),maximum=TRUE)
>
>
> ans2
$maximum
[1] 269.1099
$objective
[1] 100
A: Since values of bin are either 0 or 1, for a given value of ges, we're really just counting the number of elements in buys that are in the interval [ges-10,ges+10]. Visually, one could imagine "sliding" the interval [ges-10,ges+10] starting at ges=min(buys) and ending at ges=max(buys) and counting the number of entries of buys that are in the interval as the value of a function. In particular:
num_buys=function(x)
{
return(length(buys[buys>=x-10 & buys<=x+10]))
}
With that, we can use optimize to find a maximum:
optimize(f=num_buys,interval=c(min(buys),max(buys)),maximum=TRUE)
As an example:
> buys=rnorm(10000,mean=50,sd=10)
> summary(buys)
Min. 1st Qu. Median Mean 3rd Qu. Max.
11.38 43.22 50.01 50.06 56.93 92.76
> num_buys=function(x){return(length(buys[buys<=x+10 & buys>=x-10]))}
> optimize(f=num_buys,interval=c(min(buys),max(buys)),maximum=TRUE)
$maximum
[1] 50.16788
$objective
[1] 6808
So, in this case, a maximum value of sum(bin) would be 6808, and this maximum would occur when ges=50.16788. Of course, this makes perfect sense, since about 68% of the values should occur within 10 units of 50 (normal distribution and all that). :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySql: Find table2.name WHERE table1.lat = table2.lat AND table1.lng = table2.lng; I have spent the last few days bashing my head in trying to find the answer to this.
I have a Table of Routes of GPS data. and a Table of Points. What I need is a MySql statement that for a given route, will tell me the Point.Name of both end points. I could write 4 separate statements, but I believe there is a better way.
The tables have Similar columns {rowid, userid, latitude, longitude} to make things interesting:
Route.Name = '2011-06-27';
and
Point.Name = 'location_1';
To get the first and last points is easy. (Add DESC before LIMIT for last point )
SELECT `rowid`, `latitude`, `longitude` FROM `$db`.`Route`
WHERE `userid` LIKE '$userid' AND `name` = '$name' ORDER BY `rowid` LIMIT 1;
I have been Reading about OUTER JOIN and thought that would work, this is as close as I have gotten.
SELECT DISTINCT a.`rowid`, a.`latitude`, a.`longitude`, b.`name`
FROM `$db`.`Route` a
RIGHT OUTER JOIN `$db`.`Point` b ON a.`latitude` = b.`latitude`
AND a.`longitude` = b.`longitude` WHERE a.`userid` LIKE '$userid'
AND a.`name` = '$name';
Desired Output:
rowid | latitude | longitude | name
'16660', '49.22551', '-122.57416', 'location_5'
'16792', '49.16722109', '-122.98667883', 'location_1'
Actual Output:
rowid | latitude | longitude | name
'16791', '49.16721654', '-122.98723093', 'location_1'
'16792', '49.16722109', '-122.98667883', 'location_1'
I will be very thankful of any assistance in helping me solve this issue.
Let me know if further detail is needed.
==== EDIT ====
SELECT `name`, `latitude`, `longitude` FROM `$db`.`Point`
WHERE (`latitude`,`longitude`) IN(
SELECT `rowid`, `latitude`, `longitude` FROM
( SELECT `rowid`, `latitude`, `longitude` FROM `$db`.`Route`
WHERE `userid` LIKE '$userid' AND `name` = '$name' ORDER BY `rowid` LIMIT 1) as t1
UNION
( SELECT `rowid`, `latitude`, `longitude` FROM `$db`.`Route`
WHERE `userid` LIKE '$userid' AND `name` = '$name' ORDER BY `rowid` DESC LIMIT 1) )
The catch is this generates Error Code: 1235 This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
So I'll need to experiment a bit more on getting results w/o using LIMIT or retrieve the results and then generate a second query using the results. I'll get back to you later. Thank you Again.
A: You can use a UNION to combine the two SQLs.
SELECT `rowid`, `latitude`, `longitude` FROM
( SELECT `rowid`, `latitude`, `longitude` FROM `$db`.`Route`
WHERE `userid` LIKE '$userid' AND `name` = '$name' ORDER BY `rowid` LIMIT 1) AS t0
UNION
( SELECT `rowid`, `latitude`, `longitude` FROM `$db`.`Route`
WHERE `userid` LIKE '$userid' AND `name` = '$name' ORDER BY `rowid` DESC LIMIT 1) AS t1
A: I broke down and separated the statements into one to collect the endpoints, and then I'll loop the results to query the names. I really would have liked to get all the results at once, to cut down on traffic dealing with a large number of users =\
SELECT TRUNCATE(`latitude`,3) AS latitude, TRUNCATE(`longitude`,3) AS longitude
FROM `$db`.`$table1`
WHERE `rowid` = (
SELECT MIN(`rowid`)
FROM `$db`.`$table1`
WHERE `userid` LIKE '$userid' AND `name` = '$name')
UNION
SELECT TRUNCATE(`latitude`,4) AS latitude, TRUNCATE(`longitude`,3) AS longitude
FROM `$db`.`$table1`
WHERE `rowid` = (
SELECT MAX(`rowid`)
FROM `$db`.`$table1`
WHERE `userid` LIKE '$userid' AND `name` = '$name')
Loop the results from the previous query with this statement to get the points to display end points.
SELECT name, latitude, longitude FROM `$db`.`$table2`
WHERE TRUNCATE(latitude,3) ='$lat' AND TRUNCATE(longitude,3) ='$lng' LIMIT 1;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: vb .net shorten an if statement I'm trying to make this cleaner... I know there's lots of shortcuts for If statements, but I don't know what's best.
If item.RecurrenceId > 0 Then
xmlTextWriter.WriteElementString("recordtype", "2")
ElseIf IsNothing(item.OngoingEndDate) = False Then
xmlTextWriter.WriteElementString("recordtype", "1")
Else
xmlTextWriter.WriteElementString("recordtype", "0")
End If
A: Shortcuts don't always make for better code. Though short code can be "clean", it may not be as legible as what you have stated.
With that said, I would stick with what you have, as long as it meets your purpose. It's "clean", but more importantly it's clear what outcome you're going for.
A: I don't suppose this will work.
xmlTextWriter.WriteElementString("recordtype", If(item.RecurrenceId > 0, "2", If(IsNothing(item.OngoingEndDate) = False, "1", "0")));
A: The If operator would be such:
If(item.RecurrenceId > 0, _
xmlTextWriter.WriteElementString("recordtype", "2"), _
If(Not IsNothing(item.OngoingEndDate), _
xmlTextWriter.WriteElementString("recordtype", "1"), _
xmlTextWriter.WriteElementString("recordtype", "0")))
A: Another approach would be to create a function called
GetRecordType(byval item as whatever) as int
with the if statements inside, determining 0, 1, or 2, and then just call
xmlTextWriter.WriteElementString("recordtype", GetRecordType(item).ToString())
This would keep it short and sweet in your function that has all of the WriteElementString calls, while still keeping the if statement easy to read in the extracted GetRecordType function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do all Facebook Graph API calls require HTTPS starting October 1st? I have an app I host myself which makes use of the graph API. I have already update to OAuth 2.0 but do all of my API calls now require that I use HTTPS? Will Facebook auto redirect calls that are made without HTTPS?
I've noticed that all of the API documentation shows https URLs which makes me worried.
A: I don't think this change will affect your Graph API calls, as they are already using HTTPS.
Example: https://graph.facebook.com/user/
http://developers.facebook.com/docs/reference/api/
The Oct 1st HTTPS thing refers to your canvas URL - it has to be HTTPS.
Example: https://www.myfacebookapp.com
A: The October 1st deadline does not dictate that grahp calls must be sent over HTTPS. Any call that uses an access_token is already required to use SSL, and more and more calls that were open (didn't require an access_token) are starting to require an access_token so it is recommended that you start switching all your graph calls to https as you are able. Facebook won't forward non-http requests over to https.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a DLL from Exe I'm trying to find a solution for creating a DLL from an Exe in C++. I'm currently working on an IIS / Tomcat setup script and need to have a DLL hard coded in my code and have it written as a DLL file.
I have found when dealing with binary files, I should write them one character at a time like so:
ofstream fout;
char c[2000];
fout.open("isapi.dll", ios::binary);
for(int i=0; i<2000; i++)
fout << c[i];
The only problem is, how do I store (hard code) the contents of a DLL in my code to create this DLL in my setup script?
A: you can use decompiler.Many decomiler are free to download,by this you can reach atleast at the all function and parameter also.I think it should be useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cron jobs creating blank file Cron jobs I created is automatically creating a blank file every time it's run.
Is there a way to fix this issue so that it doesn't create this file?
Below is the command for cron jobs:
/usr/bin/wget http://nitelife.wmetools.com/backend/index.php/ratings/overall_ratings_history
A: It's downloading an empty file because that's what that URL gives you. If you are sure and/or don't care about the possibility that some day, that URL may send some data (like some kind of infrequent message, like an error), add "-O /dev/null" to the wget command line. That will make sure that wget never writes a real file at all. If there's a 4xx or 5xx error message, you'll still get something over standard error into an email from cron, but if any message comes via a normal HTML over a 200 response, it would be lost.
That raises the question though, why "wget" that link in the first place? If you just want the .php script to run and don't care about its output, I suppose the first suggestion is sufficient. Otherwise, you may need a short script, which would use -O to write to a temp file, and test for a non-zero file size ("-s" in bash) and then move the file to the correct location, or delete the 0-length file. That way the normal location would only have the file from the last time it had any data in it.
If that PHP file is yours, you could edit it so that it doesn't give an 200 status code and 0 length document anymore. There's a rarely used "204 No Content" HTTP status code. I haven't tested wget with a 204, but it really shouldn't save a file in that case, nor should it be considered an error.
A: Following will delete the file created by wget.
/usr/bin/wget -q --delete-after http://nitelife.wmetools.com/backend/index.php/ratings/overall_ratings_history
You may lose the information in these files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android Particle System converge single point Ok I have a particle system going in Android.
Right now I use 500 or so particles and they randomly move around the screen. I set it so that on touch (actually motion right now). that all the particles would approach your finger. Problem being is that they're approaching at a static angle (not taking into the angle they are from the touch point).
Anyone have the algorithm to determine how to evenly approach a point? My attempt to get the angle in randians.. then convert etc.. got really messy. This simple approach showed that I move at the right pace.. but it's a simple 45 angle approach. (keep in mind on android there are no negative x,y coordinates.. and top left is 0,0.. bottom right is (max,max). the functions takes the ontouch (x,y) coordinates. b.x, b.y are the particle coordiantes.
public void moveParticles(float x, float y) {
for (Particle b : Particles)
{
if (x <= b.x)
b.x = b.x -1;
else b.x = b.x +1;
if (y <= b.y)
b.y = b.y -1;
else b.y = b.y +1;
}
}
A: Naive code that assumes touch is in the centre of the screen:
public void moveParticles(float x, float y) {
for (Particle b : Particles) {
b.x += ((b.x-x)/(x/2))*speedmodifier;
b.y += ((b.y-y)/(y/2))*speedmodifier;
}
}
Code with normalised speeds each side of the touch axis:
public void moveParticles(float x, float y) {
for (Particle b : Particles) {
height_difference = screenheight-x;
width_difference = screenwidth-y;
height_ratio = (b.x < x) ? screen_height-height_difference : height_diffrence;
width_ratio = (b.y < y) ? screenwidth-width_difference : width_difference;
b.x += ((b.x-x)/height_ratio)*speedmodifier;
b.y += ((b.y-y)/width_ratio)*speedmodifier;
}
}
Steps to make this code:
You need to get the ratio of the screen above and below the x and y axis, so as to normalise the speed of the particles from 0 to 1 no matter where the touch is:
height_difference = screenheight-x;
width_difference = screenwidth-y;
height_ratio = (b.x < x) ? screen_height-height_difference : height_diffrence;
width_ratio = (b.y < y) ? screenwidth-width_difference : width_difference;
Once we have that normalisation information we can use it to normalise the particle speeds:
b.x += ((b.x-x)/height_ratio)*speedmodifier;
b.y += ((b.y-y)/width_ratio)*speedmodifier;
A: Take the particle's displacement as a vector with convergence point as origin:
x = particle.x - finger.x
y = particle.y - finger.y
Get unit vector:
norm = sqrt(pow(x, 2.0) + pow(y, 2.0))
x = x / norm
y = y / norm
Displace particle by unit vector * -1 * speed factor:
particle.x -= x * speed
particle.y -= y * speed
Does that work? I just wrote this out, didn't try it or nothin'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.NET MVC3 Unobtrusive Validation and Hand Coded Element Question I understand with built in function to render UI controls like
@Html.TextBoxFor(model => model.CustomerId)
@Html.ValidationMessageFor(model => model.CustomerId)
The rendered Html will look like
<input data-val="true" data-val-number="The field CustomerId must be a number." data-val-required="The CustomerId field is required." id="CustomerId" name="CustomerId" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="CustomerId" data-valmsg-replace="true"></span>
All the attributes inside input elements are used to support unobtrusive validation feature.
But for some reason I cannot render by using Html helper, but I have to hand code Html markup like
<select id="MyId" name="MyId" />
<%=Html.ValidationMessageFor(model => model.MyId)%>
In this case how can I still make unobtrusive validation word without hard code all these attributes in select element?
Thanks
Hardy
A: Unobtrusive validation relies completely on this attributes to determine which validation it will apply to the element, you will have to hard code them in your html is you dont want to use the helper, just make sure the name attribute of you select tag is equal to the property name it binds to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I break out of an each() in jQuery? I have the following HTML + JS. I want the toggleButton to only toggle the first io-section-header. Eventually I will have multiple toggleButton's that will toggle a unique ul.
How can I achieve this?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div><span>Section 1</span></div>
<div class="io-section-header">
<ul>
<li class="advanced">Accounts</li>
<li class="advanced">People</li>
<li class="advanced">companies</li>
<li class="basic">She</li>
</ul>
<div><span>Section 2</span></div>
<div class="io-section-header">
<ul>
<li class="advanced">Accounts</li>
<li class="advanced">People</li>
<li class="advanced">companies</li>
<li class="basic">P</li>
</ul>
</div>
</div>
<div class="toggleButton">Collapse</div>
<script>
jQuery(function ($) {
$('.toggleButton').click(function () {
var currentText = $(this).text();
if(currentText === "Collapse")
$(this).text("Expand");
else
$(this).text("Collapse");
/*$('.io-section-header').each(function() {
$("li").siblings(".advanced").toggle('fast',function(){});
});*/
$('.io-section-header li').siblings(".advanced").toggle('fast');
});
});
</script>
</body>
</html>
A: From the .each() documentation:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
A: This will toggle the first advanced class in each io-section-header class
$('ul li.advanced:first', '.io-section-header').toggle('fast',function(){});
This will toggle the first advanced class in the first io-section-header class
$('ul li.advanced:first', '.io-section-header:first').toggle('fast',function(){});
A: return false is all you need; why aren't you using first()?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XNA resize window without increasing resolution I want to create a low resolution game on a larger window. (96x54 res on 960x540 size window for example).
How would I go about this? Is there a way to resize a window independently of the preferred back buffer width and height? Or should I just keep a low resolution render target I draw on, and just draw it as a full screen quad on my window when I'm done adjusting for nearest texture sampling?
Thanks in advance,
xoorath
A: I tend to opt for the "render to texture" solution so that I can allow for things like full screen without distortions.
The class I use to achieve this usually looks something like:
class VirtualScreen
{
public readonly int VirtualWidth;
public readonly int VirtualHeight;
public readonly float VirtualAspectRatio;
private GraphicsDevice graphicsDevice;
private RenderTarget2D screen;
public VirtualScreen(int virtualWidth, int virtualHeight, GraphicsDevice graphicsDevice)
{
VirtualWidth = virtualWidth;
VirtualHeight = virtualHeight;
VirtualAspectRatio = (float)(virtualWidth) / (float)(virtualHeight);
this.graphicsDevice = graphicsDevice;
screen = new RenderTarget2D(graphicsDevice, virtualWidth, virtualHeight, false, graphicsDevice.PresentationParameters.BackBufferFormat, graphicsDevice.PresentationParameters.DepthStencilFormat, graphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents);
}
private bool areaIsDirty = true;
public void PhysicalResolutionChanged()
{
areaIsDirty = true;
}
private Rectangle area;
public void Update()
{
if (!areaIsDirty)
{
return;
}
areaIsDirty = false;
var physicalWidth = graphicsDevice.Viewport.Width;
var physicalHeight = graphicsDevice.Viewport.Height;
var physicalAspectRatio = graphicsDevice.Viewport.AspectRatio;
if ((int)(physicalAspectRatio * 10) == (int)(VirtualAspectRatio * 10))
{
area = new Rectangle(0, 0, physicalWidth, physicalHeight);
return;
}
if (VirtualAspectRatio > physicalAspectRatio)
{
var scaling = (float)physicalWidth / (float)VirtualWidth;
var width = (float)(VirtualWidth) * scaling;
var height = (float)(VirtualHeight) * scaling;
var borderSize = (int)((physicalHeight - height) / 2);
area = new Rectangle(0, borderSize, (int)width, (int)height);
}
else
{
var scaling = (float)physicalHeight / (float)VirtualHeight;
var width = (float)(VirtualWidth) * scaling;
var height = (float)(VirtualHeight) * scaling;
var borderSize = (int)((physicalWidth - width) / 2);
area = new Rectangle(borderSize, 0, (int)width, (int)height);
}
}
public void BeginCapture()
{
graphicsDevice.SetRenderTarget(screen);
}
public void EndCapture()
{
graphicsDevice.SetRenderTarget(null);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(screen, area, Color.White);
}
}
And then in my game, the initialisation tends look something like:
VirtualScreen virtualScreen;
protected override void Initialize()
{
virtualScreen = new VirtualScreen(96, 54, GraphicsDevice);
Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);
Window.AllowUserResizing = true;
base.Initialize();
}
void Window_ClientSizeChanged(object sender, EventArgs e)
{
virtualScreen.PhysicalResolutionChanged();
}
With the all important call to Update:
protected override void Update(GameTime gameTime)
{
virtualScreen.Update();
base.Update(gameTime);
}
And then the act of drawing itself:
protected override void Draw(GameTime gameTime)
{
virtualScreen.BeginCapture();
GraphicsDevice.Clear(Color.CornflowerBlue);
// game rendering happens here...
virtualScreen.EndCapture();
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
virtualScreen.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
With this in place, I can basically stop caring about resolution at all and just focus on the game.
A: Using the RenderToTexture method you're talking about might be a good idea (plus it will be easier for you if you want to do post-process shaders).
Alternatively, you can set the Window's size, but your code will only work on a desktop.
You must add those 2 references in your project:
using System.Drawing;
using System.Windows.Forms;
And then in your Game class (i.e. in the Initialize method)
GraphicsDeviceManager.PreferredBackBufferWidth = 96;
GraphicsDeviceManager.PreferredBackBufferHeight = 54;
IntPtr ptr = this.Window.Handle;
Form form = (Form) Control.FromHandle(ptr);
form.Size = new Size(960, 540);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: viewDidLoad not being called when pushing UIViewController I'm pushing a UIViewController like so:
UIViewController* individualsController = [[[UIViewController alloc] initWithNibName:@"IndividualsController" bundle:nil] autorelease];
[self.navigationController pushViewController:individualsController animated:YES];
The NIB itself is loading fine, all the elements load on the screen. BUT none of the view controller's methods are getting called. No viewDidLoad, no viewWillAppear, just a pushed NIB with nothing else.
The view outlet is set up in the NIB; I can't figure out why none of it is getting called!
A: One possibility is that you are instantiating it as a UIViewController rather than the name of your UIViewController subclass, so it is calling those methods, but on UIViewController, not on your class. Assuming that the subclass is called IndividualsController, try changing the line to
IndividualsController* individualsController = [[[IndividualsController alloc] initWithNibName:@"IndividualsController" bundle:nil] autorelease];
and see what happens.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: RoutingError when using jQuery UI tabs with ajax I'm getting ActionController::RoutingError in Profiles#show when I click a link to render a layout as part of my implementation of jQuery UI tabs. Here's my link_to:
<%= link_to "Messages", :controller => 'profiles', :action => 'profile_messages', :remote => true %>
My ProfilesController:
def profile_messages
@messages = User.find(@profile.user_id).messages
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @messages }
end
end
My profile_messages erb layout:
<div id="tabs-2">
<% for message in @user.messages %>
<div class="message-1">
</div>
<% end %>
</div><!-- end messages -->
Routes.rb:
resources :messages do
get "messages/profile" => :profile_messages
resources :responses
end
What I want to happen is: when you click the link created by my link_to, the layout in profile_messages.html.erb shows and loads the messages in that specific layout. What's going on here?
UPDATE: Adding the new line in Routes.rb gives me a new route:
message_messages_profile GET /messages/:message_id/messages/profile(.:format) {:action=>"profile_messages", :controller=>"messages"}
So I tried this in my Profiles show.html.erb I put:
<li><%= link_to "Messages", message_messages_profile_path, :remote => true %></li>
This gives me a RoutingError in Profiles#show -- No route matches {:action=>"profile_messages", :controller=>"messages"}. Even when I add the following into my MessagesController:
def profile_messages
@message = @user.messages.find(params[:user_id])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @messages }
end
end
A: get "messages/profile" => "messages#profile_messages", :as => profile_messages
resource :messages do
resource :responses
end
You don't have a route for that controller action. Rails doesn't map ":controller/:action/:id" by default any more. You can also just enable that route if you want. You could be able to reference this via profile_messages_path.
It's assuming 'show' is actually an id for messages here I think. The default routes for a resource are listed here: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions. Make sure you list your routes first!
A: resource :messages do
collection do
get :profile_messages
end
end
in your view
<li><%= link_to "Messages", "/messages/profile_messages", :remote => true %></li>
A: Thanks to the combined efforts of folks here on SO I was able to get this to work. Check out these questions for more code:
Exclude application layout in Rails 3 div
Rails 3 jQuery UI Tabs issue loading with Ajax
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Has anyone ever come up with a way to detect the email program a recipient is using? I know there are ways to detect browsers based on CSS rules but I don't know if the same tricks would work for Outlook. The way I think it could work is have CSS rules that show and hide urls so that when a recipient clicks on a link I can tell which email program it came from.
A: I can't see how this would be possible. Browser detection is done via Javascript (not CSS). And if the user is using a non-web-based email client (such as Outlook), clicking on a link will trigger the default browser to open and load the link. The information the browser sends to your server will have no knowledge of what application caused the browser to launch.
I think your only option would be to have different links for each client and rely on the goodness of the users to click the correct link.
I also think you'd have a fairly high success rate of guessing the client based on a few factors that ARE available after the link is clicked such as:
*
*The device type
*The Browser
*The Operating System
*The email address (if it's gmail.com or hotmail.com you know 99% of them used the web client - or for a better match mix it with the device type)
Then you could make generalisations such as:
*
*Accessed from Windows and not a gmail/hotmail/yahoo webmail address - probably used Outlook
*Accessed from OSX and not webmail address - probably used Mail
*Accessed from either and a webmail address - probably used Browser
Rules like that could probably give you some pretty meaningful statistics.
A: If your challenge is to see what email client the person is using, there are simpler solutions than showing and hiding links. The easiest way would be to embed an image, add a query string to it like so:
http://www.yoursite.com/image.png?email=youremail@email.com
You would then catch this serverside and get the user agent string.
The issue with this is with webmail clients like GMail and Hotmail. In these instances the user agent string would be the same as the web browser. Here you would detect the user's webmail client by inspecting the email address, eg. hotmail.com.
There are edge cases such as Google Apps for Business, but this should catch most cases.
Most email senders such as Mailchimp will do mail client analytics for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot add a UIDatePicker to an xib without generating an Internal Error I am using xCode 4.0.2 and trying to create a view controller with an xib that contains a UIDatePicker. Whenever I try to drag a UIDatePicker object to the view in the xib I get an Internal Error alert. This is a universal app and I am using an xib targeted for the iPhone.
Has anyone else experienced this or have any suggestions on how to work around this problem?
For now I am going to work around it by adding the UIDatePicker to the view in code.
Also, when I click the Crash button in the alert I am not getting the Crash Reporter. Isn't the Crash Reporter supposed to come up automatically? If this is a bug, how can I otherwise report it?
Thanks,
John
A: if you are using the Xcode UI and it crashes, assuming you don't have any huge environmental problems, no disk space... etc, that is a bug; and you should report it to:
bugreport.apple.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Objective-C RegexKitLite match one string or another I'm trying to use regexkitlite for string matching in objective-c and I'm having some problems with it. What I'm trying to do is search a large string for substrings matching:
*
*"http://[something].jpg"
*"http://[something].png"
Basically, I want to find all links to images from the original string. What I have currently is:
NSString *regexString = @"http://[a-zA-Z0-9._%+-/]+\.jpg";
Now this is working for .jpg images, but of course it doesn't match .png images. I would really like to use one regexString that would match either, but I can't figure out how.
Reading some regex tutorials for other languages, I think it is something along the lines of:
NSString *regexString = @"http://[a-zA-Z0-9._%+-/]+\.(?:jpg|png)";
But I can't quite get it right.
Any help would be greatly appreciated.
A: You don't need a non-capturing group around the file extensions. It's good practice to use them, but it could be causing an error here. (Does the library support it?)
Also, I simplified your regex slightly by using a predefined character class.
NSString *regexString = @"http://[\w.%+-/]+\.(jpg|png)";
You can see this in action here.
You can also add any file extensions that you want. Ex: (jpg|png|gif|...).
Updated: Apple now includes regular expression support with NSRegularExpression, which is available in OS X v10.7 and later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to split text into separate UITextView pages? A subquestion is:
How do I determine what the built-in internal margins of a UITextview are?
I have a long master string of text that I am trying to split into separate UITextView pages that I can then scroll from page to page inside a UIScrollView. I use the following method to determine what the height of a string in a UITextView is and whether the string is over the height limit:
-(NSNumber *)getHeightByWidth: (NSString *) myString
mySize: (UIFont *) mySize
myWidth: (NSNumber *) myWidth
{
int intMyWidth = [myWidth intValue];
CGSize boundingSize = CGSizeMake(intMyWidth, CGFLOAT_MAX);
CGSize requiredSize = [myString sizeWithFont:mySize constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
NSNumber *retNumber = [[NSNumber alloc] initWithFloat:requiredSize.height];
return retNumber;
[retNumber release];
}
I call the getHeightByWidth method using the following cellFont as the input for mySize:
UIFont *cellFont = [UIFont fontWithName:@"Arial" size:14.0];
The UITextView is 320 pixels wide, but I notice that the text doesn't go from the left edge to the right edge as there are internal margins which look to be around 10 pixels on each side. So when I call getHeightByWidth I set myWidth = (320 - 10 - 10); But after building strings to fit within the UITextView, there are usually gaps on the last row that could be filled with the next words in the master string.
Can anyone tell me why these gaps on the last row of the text occur using this process for UITextView?
A: The built-in margins are represented by the property contentInset.
Also you can configure the margins yourself.
If you have your text view in IB, look for Content insets. The values must be 0, but it still displays some margin. Trying setting them to negative values such as -4 or -8.
In the code, do something like-
myTextView.contentInset = UIEdgeInsetsMake(-4,-8,0,0);
You have to set these values according to what you find suitable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where to place the AsyncTask() so that i can call it to load image? Below is my coding where it would load the image when this Activity is called. But i wished to display the progressDialog when it was retrieving the images from the server instead of just a black screen presented to the user. I heard that AsyncTask is able to do but i stuck with where to place the AsyncTask function and calling it.
public class LargeImageScroller extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private static Bitmap bmLargeImage; //bitmap large enough to be scrolled
private static Rect displayRect = null; //rect we display to
private Rect scrollRect = null; //rect we scroll over our bitmap with
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //x amount to scroll by
private float scrollByY = 0; //y amount to scroll by
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
public SampleView(Context context) {
super(context);
displayRect = new Rect(0, 0, displayWidth, displayHeight);
scrollRect = new Rect(0, 0, displayWidth, displayHeight);
bmLargeImage = Bitmap.createBitmap(1035 , 665, Config.ARGB_8888);
bmLargeImage = createMap(this.getContext());
}
public boolean onTouchEvent(MotionEvent event) {....}
protected void onDraw(Canvas canvas) {....}
private static Bitmap createMap(Context context) {...}
private static Drawable LoadImageFromWebOperations(String url) {....}
private static Bitmap decodeFile(File f, int requiredSize) {...}
}
}
I wish to know where should i place the AsyncTask function so as to display the progressDialog while the program is loading the image from server/cache. Most of the source i found on the internet doesn't say much.
A: AsyncTask is somehow like a Thread. It is used to handle some time-consuming operations so that the main thread won't be blocked.
In your case, AsyncTask is suitable. However, the place where you would like to put it depends on your logic.
Please read the SDK: AsyncTask to get more info about it. There is also a code snippet that may help you.
Added:
Well, I understand your concern. If you just want to show a progress bar to tell the users that the app is downloading the images from the server. You may handle this way:
1. Create a xml layout file containing a ProgressBar.
2. In OnCreate in Class LargeImageScroller, call setContentView(R.layout.that_layout) to show the progressbar, and Start a AsyncTask to download the images.
3.Inside AsyncTask, override onProgressUpdate(Integer... progress) to tell the ProgressBar the donwloading progress.
4. Inside AsyncTask, override onPostExecute(Long result). This method will be called when the AsyncTask finishes. Here you can do : SampleView sv=new SampleView(this), and then pass the images to the sv object. Then call setContentView(sv) to show your images.
This is just my train of thought. I think you can use AsyncTask in either LargeImageScroller class or SampleView class. Hope ithis comment helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to apply primary key on the text fields in android database I have created a simple table that contains the name and email id's of the persons. When i am giving the create query like this:
"create table contacts (name text not null, email text primary key not null);"
But this is not working. I'm not getting any exception or error while running nor the primary key is working. While browsing the table using SQLite browser i observed that there are only four data types:
Is it possible to apply primary key only on integer? What is the case if i want primary key on text fields. Thank you. This is the code that i used:
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "contacts";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table contacts (_id integer primary key autoincrement, "
+ "name text not null, email text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String name, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_EMAIL}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
A: as per the faq of sqlite documentation, using TEXT as a datatype for primary key should work.
i used your query and here it is, the table is created.
CREATE TABLE contacts ( email text primary key not null, name text not null);
INSERT INTO contacts VALUES ('sample@email.com', 'sample')
INSERT INTO contacts VALUES ('people@email.com', 'sample')
now here is where it went wrong.
when i ran this again
INSERT INTO contacts VALUES ('sample@email.com', 'sample')
nothing happened, no errors.
But it did not update the record. so i conclude data integrity is there but you don't get any feedback about the failure.
A: SQLiteDatabase.insertOrThrow() should throw an exception if the value could not be inserted.
Also its return values, as well the one from SQLiteDatabase.insert() is the rowid of the inserted row or -1 if it fails. You should opt for any of these alternatives in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Adding style to Header when div is clicked using Javascript My intent is to add a class to the header when a div is clicked. I have included the website I'm working with, just to make thing's easier:
URL - http://itsmontoya.com/work/iM/
I have added a class 'expanded' to the header. This is to show how the navigation should look after the button has been pressed. I created a simple Javascript which is supposed to provide an alert when I click the button. I can't seem to get this to work. Any ideas of what I did wrong?
Thanks!
EDIT - I was able to get the alert to properly work when clicking the button div. I'm very close to having this complete! :) Now I'm getting stuck with the variable not passing correctly.
<script type= "text/javascript">
var expanded = false;
function btnClick(){
alert('The variable expanded is '+expanded);
if(expanded === false) {
document.getElementById("header").className = "expanded";
var expanded = true;
} else {
document.getElementById("header").className.replace(/\bexpanded\b/,'');
var expanded = false;
}
};
</script>
I'm updating the ftp server now :)
A: When using jQuery, you have to bind your events in such a way that the elements have already loaded.
You have:
<script type= "text/javascript">
$("#expandBtn").click(function(){
alert('hello');
});
</script>
I think what you want is:
<script type= "text/javascript">
$(document).ready(function(){
$("#expandBtn").click(function(){
alert('hello');
$('header').addClass('expanded');
});
});
</script>
The API documentation is going to be your friend here. First step -- ready().
UPDATE
You have this call to jQuery:
$j('#header').addClass('expanded');
But your markup is for the HTML5 element <header>. In that case your jQuery needs to change to:
$j('header').addClass('expanded');
Where $j is your jQuery object. More typically you would use $ or jQuery.
Time to bone up on jQuery Selectors!
UPDATE
Here's your updated page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>itsMontoya</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="shortcut icon" href="/favicon.ico" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type= "text/javascript">
$(document).ready(function(){
$('.expandBtn').bind('click', function(){
$('header').toggleClass('expanded');
});
});
</script>
</head>
<body>
<div class="wrap">
<header id="header" class="">
<div class="blackBG transparent"></div>
<nav>
<ul>
<li>
Home<img src="images/home.png">
</li>
<li>
Pictures<img src="images/pictures.png">
</li>
<li>
Music<img src="images/mymusic.png">
</li>
<li>
About Me<img src="images/aboutme.png">
</li>
<li>
Resume<img src="images/resume.png">
</li>
</ul>
</nav>
<div id="logo" class="logo"><p>itsMontoya</p></div><div id="expandBtn" class="expandBtn anchor"></div>
</header>
<section class="content">
<article class="blogEntry"></article>
</section>
<footer class="anchor">
<div class="over anchor"><p>2011 itsMontoya.com</p></div>
<div class="blackBG transparent anchor under"></div>
</footer>
</div>
</body>
</html>
A: This is how you would bind a click handler to your div and add the class to your header:
var yourDiv = document.getElementById('your-div-id');
var header = document.getElementById('header');
yourDiv.onclick = function(){
alert("yourDiv was clicked");
header.className = "newCssClass";
};
The above assumes markup like so:
<div id="your-div-id">Click</div>
<div id="header"></div>
Here's an example.
Update: The reason that the expanded variable isn't working as you'd expect is because you're creating a duplicate local variable called expanded in your btnClick() method. As a result, the global expanded variable you declare outside the function is never updated.
This is being caused by how you're using the var keyword:
*
*When used outside a function, var creates a global variable that's accessible anywhere within the current document.
*When used inside a function var creates a local variable that is accessible only within that function.
Here's your function cleaned up to work as you'd expect:
// Define global variable (using var outside function)
var expanded = true;
function btnClick(){
alert('The variable expanded is '+expanded);
// Condition for true
if(expanded) {
// do something
// Condition for false
} else {
// do something else
}
// Flips boolean value of the global variable (notice lack of var keyword)
expanded = !expanded;
}
Here's an example showing the correct way to update the expanded variable.
A: Using jQuery:
$('#your_div_id').click(function(){
console.log("Clicked.");
$("#header").addClass('expanded');
});
Update
In your code:
var expanded = false;
function btnClick(test){
if($expanded === false) {
.
.
.
What the heck is $expanded? Notice that in JavaScript we don't need the $ sign for variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to manage ldap contexts in jboss? In the same way that JBoss can manage jdbc data sources can it manage LDAP contexts using JNDI?
A: Yes, this is just a Tomcat custom <Resource>, see the Tomcat documentation.
In brief, just define a and provide your own implementation of an LdapContextFactory. JBoss will call your getObjectInstance() method with a first parameter that you can cast to a Reference, traverse all its RefAddrs, and get your option names via RefAddr.getType(), and their values via RefAddr.getContent(). Then you use whatever you have passed there to create your LdapContext and return it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: One-liner is SASS In CSS I can do something like this:
.apple { background-image: url('apple.png'); }
.orange { background-image: url('orange.png'); }
.pear { background-image: url('pear.png'); }
but it seems in sass (not scss) the same would take up 6 lines? Is it possible to do a one-liner is sass for rules that only have one property?
A: This isn't by any means meant to help you condense this code to one line, but to think of it from a different perspective.
In this post on The Sass Way titled "Sass control directives: @if, @for, @each and @while", I cover control directives in Sass. Here's a way to write your code using the @each directive.
$fruit-list: apple orange pear
=fruit
@each $fruit in $fruit-list
&.#{$fruit}
background-image: url(#{$fruit}.png)
.fruit
+fruit
Which outputs:
.fruit.apple {
background-image: url(apple.png);
}
.fruit.orange {
background-image: url(orange.png);
}
.fruit.pear {
background-image: url(pear.png);
}
Using .scss we can make this a one liner, but at the cost of readability of the code:
$fruit-list: apple orange pear;
@mixin fruit { @each $fruit in $fruit-list { &.#{$fruit} { background-image: url(#{$fruit}.png); } } }
.fruit { @include fruit; }
A: Sass syntax is principally based on indentation and line breaks, so in Sass that would indeed be six lines (two per rule, excluding blank lines):
.apple
background-image: url('apple.png')
.orange
background-image: url('orange.png')
.pear
background-image: url('pear.png')
As far as I've seen you can't condense those to one-liners in Sass.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why isn't this C# code working? It should return the string between two other strings, but always returns an empty string The title explains it all. It seems simple enough, so I must be overlooking something stupid. Here's what I've got.
private string getBetween(string strSource, string strStart, string strEnd)
{
int start, end;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
start = strSource.IndexOf(strStart, 0) + strStart.Length;
end = strSource.IndexOf(strEnd, start);
return strSource.Substring(start, end - start);
}
else
{
return "";
}
}
Thanks, guys.
A: Your code doesn't make sure that start and end are in order.
static string SubString(string source, string prefix, string suffix)
{
int start = source.IndexOf(prefix); // get position of prefix
if (start == -1)
return String.Empty;
int subStart = start + prefix.Length; // get position of substring
int end = source.IndexOf(suffix, subStart); // make sure suffix also exists
if (end == -1)
return String.Empty;
int subLength = end - subStart; // calculate length of substring
if (subLength == 0)
return String.Empty;
return source.Substring(subStart, subLength); // return substring
}
A: I get the correct answer if I try any of these:
var a = getBetween("ABC", "A", "C");
var b = getBetween("TACOBBURRITO", "TACO", "BURRITO");
var c = getBetween("TACOBACONBURRITO", "TACO", "BURRITO");
The problem is likely with your input argument validation, as this fails:
var a = getBetween("ABC", "C", "A");
var a = getBetween("ABC", "C", "C");
You can improve your validation of the issue by writing some test cases like these as a separate fixture (xUnit, or main loop in throw away app).
A: As couple of peoples said the problem that you code is working on very specific input, it's all because of this start and end IndexOf magic =) But when you try to update you code to work correct on more inputs you will get into problem that your code become very long with many indexes, comparsions, substrings, conditions and so on. To avoid this i like to recommend you use regular expressions with theirs help you can express what you need on special language.
Here is the sample which solves your problem with regular expressions:
public static string getBetween(string source, string before, string after)
{
var regExp = new Regex(string.Format("{0}(?<needle>[^{0}{1}]+){1}",before,after));
var matches = regExp.Matches(source).Cast<Match>(). //here we use LINQ to
OrderBy(m => m.Groups["needle"].Value.Length). //find shortest string
Select(m => m.Groups["needle"].Value); //you can use foreach loop instead
return matches.FirstOrDefault();
}
All tricky part is {0}(?<needle>[^{0}{1}]+){1} where 0 - before string and 1 - after string. This expression means that we nned to find string that lies beetween 0 and 1, and also don't contains 0 and 1.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery repeat text search and cut How jquery search a repeat text and get row id of other repeat row.
<tr id='1'>
<td>AA</td>
</tr>
<tr id='2'>
<td>BB</td>
</tr>
<tr id='3'>
<td>AA</td>
</tr>
<tr id='4'>
<td>AA</td>
</tr>
<tr id='5'>
<td>BB</td>
</tr>
<tr id='6'>
<td>CC</td>
</tr>
<tr id='7'>
<td>BB</td>
</tr>
for example I want id 3,4(for AA) 5,7(for BB) and no id for CC because is no repeat.
thank you.
A: Something like this should work:
function repeats() {
var seen = {};
var ids = [];
jQuery("tr").each(function() {
var text = jQuery(this).find("td").text();
if(!seen[text]) {
seen[text] = 1;
}
else {
seen[text]++;
}
if(seen[text] > 1) {
ids.push(this.id);
}
});
return ids;
}
Fiddle here
A: Something like this...
$('tr td').each(function(){
var a = $(this).parent().attr('id');
if($(this).text() == 'AA'){
document.write(a + '<br />');
}
});
Example: http://jsfiddle.net/jasongennaro/GDEWm/1/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: shell_exec and exec on PHP didn't return string I got headache by this code:
$data = shell_exec("wget -S --spider http://dkphp.com");
echo "Encoded:" .$data;
$data is "NULL"
I don't know why, its support to echo something like :( Spend like 5 hours today, and its still NULL :(
HTTP request sent, awaiting response...
HTTP/1.0 200 OK
Date: Thu, 29 Sep 2011 01:31:45 GMT
Server: LiteSpeed
Connection: close
X-Powered-By: PHP/5.3.8
Set-Cookie: PHPSESSID=50781d657c7632cc1b2e7536d5fa0c50; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0,
Pragma: no-cache
content: text/html
Content-Type: text/html
Length: unspecified [text/html]
200 OK
A: I checked your code snippet in PHP's interactive mode (php -a from the command line)
wget prints that information to STDERR, not STDOUT.
This works:
$data = shell_exec("wget -S --spider http://dkphp.com 2>&1");
echo "Encoded:" .$data;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why is Python more strict with circular imports when using from-imports? I know that Python discourages any situation which can get you into a circular import. But I wanted understand the Python internals of why from-imports are seemingly arbitrarily less forgiving than normal imports in circular import situations.
For example, this code compiles:
# main.py
import CommonUtil
# commonutil.py
import util
class CommonUtil:
# some code that uses util.Util
pass
# util.py
import commonutil
class Util:
# some code that uses commonutil.CommonUtil
pass
But this code does not:
# main.py
import CommonUtil
# commonutil.py
import util
class CommonUtil:
# some code that uses util.Util
pass
# util.py
from commonutil import CommonUtil
class Util:
# some code that uses CommonUtil
pass
Traceback (most recent call last):
File "main.py", line 1, in <module>
import CommonUtil
File "commonutil.py", line 1, in <module>
import util
File "util.py", line 1, in <module>
from commonutil import CommonUtil
ImportError: cannot import name CommonUtil
You don't hit compiler errors as long as you don't try to use the relevant classes before all the imports have completed. But when you try to do some aliasing, then it fails. Can someone explain what's going on internally in the Python that causes this error to rear its head only when from-import is used? And secondarily, is there any easy way around this? (Besides the obvious "pull shared code out to a third module," which I'll likely do anyways.)
A: Modules are executed from top to bottom. When an import is seen for the first time, execution of the current module is suspended so that the other module can be imported. When the other module attempts to import the first module, it gets a reference to the currently partially-executed module. Since code located after the import of the other module hasn't yet been executed, any names contained within it cannot yet exist.
main.py
import a
a.py
var1 = 'foo'
import b
var2 = 'bar'
b.py
import a
print a.var1 # works
print a.var2 # fails
The way around it is to not access the names in the imported module until its execution has completed.
A: see http://effbot.org/zone/import-confusion.htm#circular-imports for an explanation of what is happening.
I assume you launch the main.py file. Python will first try to load commonutil. It will create a module object, and start filling it with class and function and global variable when encountering their definition. The first statement is an import, so now python creates the util module and start filling it. The common module exist, but is empty. In the first version, you do not access any commonutil object at load time, so everything is fine. In the second one, you try to fetch a specific variable in commonutil which does not exist at this moment. If you had used something like f(commonutil.CommonUtil) in the first version, it would have also crashed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Writing a file with vim doesn't fire a file change event on OS X I am using watchdog to monitor .less file change events on OS X. If I change the contents of a .less file with TextMate or Sublime Text the modification event is captured. However, if I edit the content with vim no file modification event is fired (but file creation events for files created with vim are captured). I have seen the same behaviour with FSEvents and kqueue (both of which I have practically zero knowledge of).
I wonder can anybody explain this behaviour?
A: On Watchdog's readme there is a section specifically targeting the problem you describe: About using watchdog with editors like Vim. It is suggested to use set noswapfile in your ~/.vimrc.
A: Vim normally does not create a temporary file and then rename it. This is so that filesystem aspects such as links (both soft and hard) are preserved when writing files. This is discussed briefly in the Writing section of the Vim documentation, with further information in the 'backupcopy' option documentation.
Your file change events might be limited to changing directory entries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Can I combine Create and List class based generic views using mixins? I'm looking for the easiest way to combine List and Create functionally with generic class views.
I want to have a page that has an item list and a form to add a new item on the bottom.
I thought that mixin architecture would allow to combine necessary classes but I had no luck yet.
This almost works:
class ResourceListView(ListView, BaseCreateView):
context_object_name = 'resources'
model = Resource
form_class = ResourceForm
But form isn't accessible inside template and the thing crashes on invalid output (when form is valid, it's fine).
This may have to do with multiple inheritance but I'm not really into Python yet so it gets too confusing.
Is there a simple way to combine some of the mixins into a view-and-create View, or do I have to roll out my own?
A:
Note: I no longer advocate this solution, as this is a much cleaner one.
By trial and error (and looking at Django source), I wrote this:
class ListCreateView(ListView, BaseCreateView):
def get_context_data(self, **kwargs):
self.object = None
self.object_list = self.get_queryset()
form_class = self.get_form_class()
form = self.get_form(form_class)
kwargs.update({'object_list': self.object_list, 'form': form})
context = super(ListCreateView, self).get_context_data(**kwargs)
return context
Works fine both for creating and listing (although it may issue a few extra database calls, not sure).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Environment.getExternalStorageDirectory() on the emulator I want to read and write images to the external storage in my app. From what I read the following is the correct way to get a handle on the directory.
File externalStorageDir = Environment.getExternalStorageDirectory();
File picturesDir = new File(externalStorageDir, "Pictures");
However ...
picturesDir.exists(); // == null
picturesDir.mkdir(); // == false
Is this because I'm using the emulator?
A: You might want to make sure you have external storage enabled:
In Eclipse, go to Window > Android SDK and AVD Manager. Select the appropriate AVD and then click Edit.
Make sure you have SD card support enabled. If you do not, click the "New" button and select the "SD Card Support" option.
EDIT: Also need to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
to the manifest.
A: By default, the emulator will be launched without a sd card.
You should create a sd card image first by using the mksdcard command in console.
See SDK document:https://developer.android.com/studio/command-line/mksdcard.html
Hence, in the console, type the command to launch an emulator with that sd card:
emulator -avd <emulator name> -sdcard <sdcard image name>
For better performance, I strongly suggest you debug your app via a real device.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: BeautifulSoup: AttributeError: 'NavigableString' object has no attribute 'name' Do you know why the first example in BeautifulSoup tutorial http://www.crummy.com/software/BeautifulSoup/documentation.html#QuickStart gives AttributeError: 'NavigableString' object has no attribute 'name'? According to this answer the space characters in the HTML causes the problem. I tried with sources of a few pages and 1 worked the others gave the same error (I removed spaces). Can you explain what does "name" refer to and why this error happens? Thanks.
A: You can use try catch to eliminate the cases when Navigable String is being parsed in the loop, like this:
for j in soup.find_all(...)
try:
print j.find(...)
except NavigableString:
pass
A: Just ignore NavigableString objects while iterating through the tree:
from bs4 import BeautifulSoup, NavigableString, Tag
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for body_child in soup.body.children:
if isinstance(body_child, NavigableString):
continue
if isinstance(body_child, Tag):
print(body_child.name)
A: name will refer to the name of the tag if the object is a Tag object (ie: <html> name = "html")
if you have spaces in your markup in between nodes BeautifulSoup will turn those into NavigableString's. So if you use the index of the contents to grab nodes, you might grab a NavigableString instead of the next Tag.
To avoid this, query for the node you are looking for: Searching the Parse Tree
or if you know the name of the next tag you would like, you can use that name as the property and it will return the first Tag with that name or None if no children with that name exist: Using Tag Names as Members
If you wanna use the contents you have to check the objects you are working with. The error you are getting just means you are trying to access the name property because the code assumes it's a Tag
A: This is the latest working code to obtain the name of the tags in soup.
from bs4 import BeautifulSoup, Tag
res = requests.get(url).content
soup = BeautifulSoup(res, 'lxml')
for child in soup.body.children:
if isinstance(body_child, Tag):
print(child.name)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
}
|
Q: Tests are not started after db creation by liquibase I'm testing datasource layer using dbunit, junit, liquibase, hsqldb.
I'm using in memory-state of hsqldb.
Each time I start test, I create db structure using liquibase via command line:
@BeforeClass
public static void setupDatabase() throws Exception
{
...
try{
Main.main( new String[]{
"--defaultsFile=db/properties/db.test.properties",
"--logLevel=debug",
"update"}
);
}catch(Exception e){
System.out.println( e );
}
System.out.println( "QQQQ" );
...
}
In the output I can see, that sql scripts are executed successfully:
Connected to SA@jdbc:hsqldb:mem:datasourcedb
...
Successfully released change log lock
Liquibase Update Successful
But for some reason I can not see the output from System.out.println. I develop in IDEA. I see Process finished with exit code 0. in debug window, but at the same time I see that
test has not been terminated. I suppose the first message is related to the "main" function.
Any Idea?
A: I'm going to hazard a wild guess, but if you're using liquibase.integration.commandline.Main.main(String[]) to run your Liquibase update scripts then you shouldn't be—that method exits with System.exit(0).
Instead, take a look at this forum post which describes how to run Liquibase updates programmatically, specifically for use in unit tests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cannot display image in PHP here's my code for image display -
$username = "xxxxxxxx";
$password = "xxxxxxxx";
$host = "000.001.000.000";
$database = "xxxxxxxx";
@mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
@mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$query = mysql_query("SELECT mimetype, Image FROM table ORDER BY id DESC LIMIT 0,1");
$row = mysql_fetch_array($query);
$content = $row['Image'];
header('Content-type: image/jpg');
echo $content;
This is the error i'm getting
The image “http://www....” cannot be displayed because it contains errors.
what is wrong? The datatype of field in mysql is mediumblob
A: OK, first test, to see what is happening:
$username = "xxxxxxxx";
$password = "xxxxxxxx";
$host = "000.001.000.000";
$database = "xxxxxxxx";
if( !mysql_connect($host, $username, $password) )
die( 'Unable to connect to Server: '.mysql_error() );
if( !mysql_select_db($database) )
die( 'Can not select the Database: '.mysql_error() );
$query = mysql_query( "SELECT mimetype, Image FROM table ORDER BY id DESC LIMIT 0,1" );
if( !$query )
die( 'Query Failed: '.mysql_error() );
if( mysql_num_rows( $query )==0 )
die( 'Query Returned No Records' );
$row = mysql_fetch_array($query);
echo '<pre>';
var_dump( $row );
echo '</pre>';
That should either show you the results from the database, or an error message. If you see an error message, correct whatever is causing it...
After the above just returns the Database row contents:
$username = "xxxxxxxx";
$password = "xxxxxxxx";
$host = "000.001.000.000";
$database = "xxxxxxxx";
if( !mysql_connect($host, $username, $password) )
die( 'Unable to connect to Server: '.mysql_error() );
if( !mysql_select_db($database) )
die( 'Can not select the Database: '.mysql_error() );
$query = mysql_query( "SELECT mimetype, Image FROM table ORDER BY id DESC LIMIT 0,1" );
if( !$query )
die( 'Query Failed: '.mysql_error() );
if( mysql_num_rows( $query )==0 )
die( 'Query Returned No Records' );
$row = mysql_fetch_array($query);
header( 'Content-type: '.$row['mimetype'] );
echo $row['Image'];
(assuming that the mimetype field is something like "image/jpg")
A: I'd suggest adding a content-length header before your output:
header("Content-length: " . strlen($content))
A: I'd suggest to change the header to make it dynamic depend on the image mime-type:
header('Content-type: '.$row['mimetype']);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP regular expression to replace values in a config file I need to use php to find and replace the database in a config file:
$cfg['database'] = 'my_database_name';
Basically, I'm trying to figure out a regular expression that would find everything between
$cfg['database'] =
and
;
then replace it with the actual database name. I think I would need to use preg_replace and then use the matches array, but I'm having a hard time trying to make it work.
Can someone give me an idea of how to go about this, or point me to a good resource that would address this specific type of replacement situation?
A: preg_replace('/(\$cfg\[\s*\'database\'\s*]\s*=\s*\').*(\'\s*;)', '$1' . $dbName . '$2', $text);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Persistence of custom headers within an email thread I this is probably a strange question, but I thought I'd go ahead and ask. Say, I send an email, using IMAP SMTP, through a special client. This client adds a few custom headers to the email message before sending it on its way. The recipient receives this email and responds to me directly (and maybe CC's a few people as well).
My question is this: Given the above example, would these X-headers persist throughout all the new messages within the thread?
One thing I can think of is the client would be aware of the original email message it sent. All subsequent responses to this email would have a "Reply-To" header whose value equals the "Message-Id" of the previous email. I don't see why I couldn't crawl up these thread of replies until I get to the original message sent by the client, thereby deriving the original custom headers.
Maybe I'm over-thinking this. Any suggestions? :)
A: As far as I know, there's no reason to think any email client would propagate any header lines it doesn't understand. Most will preserve the subject (usually adding "Re: " if necessary) and derive their "To: " and "Cc: " lines from the previous message's headers, but that's about it. I suppose some (but not all) will generate an "In-Reply-To" line, but that's as far as it goes.
Your idea of having a client crawl back through the thread looking for specific headers sounds like it might be do-able, but you'd have to write your own email client if you want that feature, and you'd still be blocked by the fact that not all email clients preserve message threading in any way.
A: A message reply does not necessarily contain anything of the original message. The MUA is likely to suggest a modified (e.g. prepended with "Re:") version of the original subject, and obviously the addresses are utilised for appropriate defaults as well. None of the other content of the message forms part of the reply (unless the sender deliberately includes it, as with quoting or forwarding). Any X- headers that you have in your message will certainly not be included in the reply (unless you have control over that MUA).
However, your plan of tracking the original message is certainly feasible: see Section 3.6.4 of RFC 5322. Every message should (not must) have a Message-ID header, and should have In-Reply-To and References headers when appropriate.
The "Message-ID:" field contains a single unique message identifier. The "References:" and "In-Reply-To:" fields each contain one or more unique message identifiers, optionally separated by [whitespace].
In-Reply-To is mention to identify the message (or messages) that is (are) being replied to, while References identifies the entire thread of conversation. The References header is meant to contain the entire contents of the References header of the message being replied to, so you only need the last message to identify the entire thread.
Note that In-Reply-To and Reply-To are not the same thing (the latter specifies the address that the sender wishes replies to be sent to).
Assuming that you have the original message, then you should be able to use the References header of any reply to identify the original message. Not every MUA will handle References or In-Reply-To correctly, but most will.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Php least number can any one help me about how to find the least number of five inputs like 1,2,3,4,5
where the least is 1...
and find the 2nd least number where it is 2
then 3rd least number where it is 3
and 4th least numb where it is 4
and the largest number where it is 5..
<input type ="text" name ="num1">
<input type ="text" name ="num2">
<input type ="text" name ="num3">
<input type ="text" name ="num4">
<input type ="text" name ="answer">
A: You would sort() the numbers and then echo them back into the value attribute of your answer element.
A: $values = array($_POST["num1"],$_POST["num2"],$_POST["num3"],$_POST["num4"]);
sort($values);
var_dump($values);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android + ListView background sets background while scrolling? I have a ListView that's populated via an ArrayAdapter. Within the adapter, i set the view background color dependent on a conditional. It works, but while scrolling the remaining rows adopt this color. Here's some code:
class DateAdapter extends ArrayAdapter<DateVO> {
private ArrayList<DateVO> items;
public ViewGroup listViewItem;
//constructor
public DateAdapter(Context context, int textViewResourceId, ArrayList<DateVO> items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (view == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.row, null);
}
final DateVO dateItem = items.get(position);
if (dateItem != null) {
//is this my issue here? does position change while scrolling?
if(items.get(position).getField().equals("home")){
view.setBackgroundResource(R.drawable.list_bg_home);
}
...
}
}catch (Exception e) {
Log.i(ArrayAdapter.class.toString(), e.getMessage());
}
return view;
}
}
A: That is the default behavior of a ListView. It can be overridden by setting the cacheColorHint to transparent.
Just add,
android:cacheColorHint="#00000000"
in your xml file.
For more details you can go through the ListView Backgrounds article.
Here is an excerpt:
To fix this issue, all you have to do is either disable the cache color hint optimization, if you use a non-solid color background, or set the hint to the appropriate solid color value. You can do this from code (see setCacheColorHint(int)) or preferably from XML, by using the android:cacheColorHint attribute. To disable the optimization, simply use the transparent color #00000000. The following screenshot shows a list with android:cacheColorHint="#00000000" set in the XML layout file
EDIT : The view passed as convertView is essentially a view which is a part of the list view, but isn't visible anymore (due to scrolling). So it is actually a view you had created, and might be a view for which you had set the custom background. To solve this just make sure that you reset the background if the condition is not satisfied. Something like this :
if(condition_satisfied) {
//set custom background for view
}
else {
//set default background for view
convertView.setBackgroundResource(android.R.drawable.list_selector_background);
}
Essentially if your condition is not satisfied you will have to undo whatever customisations you are doing when your condition is satisfied, because you might have received an old customised view as convertView.
That should solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How is SkypeKit different from programming with the Skype API? I have a lot of experience writing Delphi 6 Pro apps using the Skype API. I don't use the COM object but instead I interface directly with the Skype client using the SendMessage() system. My current application acts as a full duplex audio proxy with video transmit. To transport audio I use ALTER CALL with the PORT parameter to establish a duplex audio connection with the Skype client via a pair of sockets. For sending video I have a DSPACK based DirectX filter that I instruct the Skype client to select as the chosen video device. This works fine but since it's the Skype API I have the awkwardness of interfacing with the Skype client as a separate entity.
Now along comes SkypeKit which apparently allows a developer to integrate Skype in a much more integrated manner. I'm about to dive into it and I wanted to hear from any developers out there that switched over from the Skype API to SkypeKit. Some questions:
*
*Was there anything missing from SkypeKit that is offered via the Skype API that made your app conversion difficult if not impossible?
*Do you have any tips on making the transition as smooth as possible, especially when it comes to avoiding any design choices that can really come back to haunt you when you get far down the SkypeKit path?
*Did you find any web resources or documentation from other developers that were really helpful in saving you time or trouble? (Please share links if so).
A: I am using SkypeKit in my chat-centric Java application so I haven't dealt with A/V.
SkypeKit is just a “black box” program that interacts with Skype protocol by iteslf. It is an executable that starts a process which listens on local port. The process is lightweight, only 20mB on my Windows-based developer machine. It runs completely in background, there are no any notifications at startup/messaging/shutdown.
Your client program interacts with it by sending byte structures via local SSL tunnel. These structures are wrapped by API for C++, Java and Pyton. Java API is easy. You start the process, create new Skype() object and login with your Skype account credentials and get your program callbacks execution when some events happen.
So @Whiler is not completely right, you always need a host application, but in this case this one is small and fast.
I don't know how hardware-based kit works but I think it is a more low-level way.
You can read the Java API here, C++ API (with examples) here, and Python (with examples) here.
Oh, and at least one small difference between desktop API and kit-based one: you can post XML text in the chat.
A: SkypeKit is no longer supported - https://support.skype.com/en/faq/FA12322/is-skypekit-being-discontinued
Disclosure: I used work for Microsoft/Skype
A: The main difference between SkypeKit and the other solutions (sendmessage, COM) is that the Skype client application is not needed... you can directly interact with the skype network...
I haven't dig this solution as the access is not free (not expensive, but without real projet, this was a no go for me...).
So this can be very useful if you plan to replace the real skype client with your own software on final machine... but if you just want to interact with an existing one, I'm not so sure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: ORA-00942: Can select from "schema.table" but not "table"? I experienced an ORA-00942 ("table or view does not exist") when executing
select * from brunch
However, no such problem when executing
select * from joe.brunch
May i know what is the issue here?
A: There are several possible causes
1) there is more than one object (table,view, procedure, etc) called brunch. Oracle does not know which one you are referring to.
2) most likely cause: the table exists in the joe schema but you are connecting as another user who has not been granted select on the joe.brunch object
Try
Grant select on joe.brunch to your_user
and try this and see how many objects match the name brunch
select *
from all_objects
where object_type in (‘TABLE’,'VIEW’)
and object_name = ‘brunch‘;
A: Unqualified, BRUNCH refers to a different object than JOE.BRUNCH in your current session. You've got a couple of options to fix that.
*
*Create a public synonym. This will allow any user that has privileges on the JOE.BRUNCH table to access it by querying BRUNCH
CREATE PUBLIC SYNONYM brunch
FOR joe.brunch
*Create a private synonym. This will allow just the current user to access the JOE.BRUNCH table by querying BRUNCH
CREATE SYNONYM brunch
FOR joe.brunch
*Change the current schema for the current session to JOE. This will cause all unqualified references in the current session to resolve to the JOE schema rather than to the current user's schema
ALTER SESSION SET current_schema = JOE
A: I found that the table I was referencing (Flyway's schema_version table), was created with double quotes... and thus needed double quotes wherever it was referenced.
Here's what Oracle says:
A quoted identifier begins and ends with double quotation marks (").
If you name a schema object using a quoted identifier, then you must
use the double quotation marks whenever you refer to that object.
In practice, these worked:
SELECT * FROM MYSCHEMA."schema_version";
SELECT * FROM "MYSCHEMA"."schema_version";
When this didn't (-> ORA-00942: table or view does not exist):
SELECT * FROM MYSCHEMA.schema_version;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Intellij IDEA code coverage incorrectly shows less than 100% I have a package with five classes. Each class has 100% code coverage, 100% line coverage bar one (which has 98% line coverage). As a result the package code coverage is 88% and line coverage is 171%. It doesn't really make sense to me (especially the 171% line coverage) and I was wondering if anyone had encountered this before?
A: It's a known issue, try IDEA 11 EAP version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP read, stored php var in text file I'm trying to figure out how to stored php values in a string/file.
I have a text file with "var1=foo&var2=foo2" etc in it, is there a way to read the values?
A: You could use file_get_contents() to open the file and parse_url() to parse the contents into an associative array.
$file = file_get_contents('file.txt');
parse_str($file, $params);
CodePad.
A: Or if you can change it, theres always serialize() and unserialize()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Returning a pointer to an object ( C++ Templates ) Error I've been asked to switch three classes for a university assignment over to templates to make them more generic but I'm having problems when trying to return a pointer to an object from a template function.
Compiler: GCC Version - 3.4.4 ( Cygwin )
Here is the (.h):
namespace node_class
{
template <class Item>
class node
{
public:
// CONSTRUCTOR
node(const Item& initial_data = 0, node* initial_link = NULL);
~node(){}
// MUTATING MEMBER FUNCTIONS
void set_data(const Item& new_data);
void set_link(node* new_link);
// NON-MUTATING MEMBER FUNCTIONS
const node* link(void) const;
node* link(void);
const Item& data(void) const;
Item& data(void);
private:
Item data_field;
node* next_field;
};
}
Here are the two function implementations for returning a pointer to an object:
template<class Item>
const node<Item>::node* node<Item>::link(void) const
{
return(next_field);
}
template<class Item>
node<Item>::node* node<Item>::link(void)
{
return(next_field);
}
Here is the errors I keeps throwing when trying to compile:
$ g++ -Wall node.h
node.h:73: error: expected init-declarator before '*' token
node.h:73: error: expected ';' before '*' token
node.h:79: error: expected constructor, destructor, or type conversion before '*' token
node.h:79: error: expected ';' before '*' token
At the moment, I have a separate (.h) and (.template) with the .template being included by a include directive in the header file; But, I'm still getting these same error messages even when the implementation of the template functions is included in the (.h) like it's supposed to be.
Any help would be great, thank you.
A: node<Item>::node is not a type. Make your return type node<Item>*.
The method declarations should be:
const node<Item>* link(void) const;
node<Item>* link(void);
The definition of these methods should be:
template<class Item>
const node<Item>* node<Item>::link(void) const
{
return(next_field);
}
template<class Item>
node<Item>* node<Item>::link(void)
{
return(next_field);
}
A: The node<Item>::node* should just be a node<Item>*:
template<class Item>
const node<Item>* node<Item>::link(void) const
{
return(next_field);
}
template<class Item>
node<Item>* node<Item>::link(void)
{
return(next_field);
}
Edit
You seem a little confused on how templates work, so I'll give an overview:
The first thing to understand is: there is no class name node. None at all. There is a class template named node. What does this mean? For each type Item which you apply to this template, there is a corresponding class named node<Item>. To repeat: if Item is a type, then node<Item> is a class, but node is never a class.
But you're probably wondering "If node isn't a type, why can I use it like a type?", as in
template<class Item>
class node
{
node* next_field;
};
But here, node is just shorthand for node<Item>. Don't get confused just because it looks like node is a type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Pickup directories: How not to pickup files that are still being written? I have a Python script that checks on a pickup directory and processes any files that it finds, and then deletes them.
How can I make sure not to pickup a file that is still being written by the process that drops files in that directory?
My test case is pretty simple. I copy-paste 300MB of files into the pickup directory, and frequently the script will grab a file that's still being written. It operates on only the partial file, then delete it. This fires off a file operation error in the OS as the file it was writing to disappeared.
*
*I've tried acquiring a lock on the file (using the FileLock module) before I open/process/delete it. But that hasn't helped.
*I've considered checking the modification time on the file to avoid anything within X seconds of now. But that seems clunky.
My test is on OSX, but I'm trying to find a solution that will work across the major platforms.
I see a similar question here (How to check if a file is still being written?), but there was no clear solution.
Thank you
A: As a workaround, you could listen to file modified events (watchdog is cross-platform). The modified event (on OS X at least) isn't fired for each write, it's only fired on close. So when you detect a modified event you can assume all writes are complete.
Of course, if the file is being written in chunks, and being saved after each chunk this won't work.
A: One solution to this problem would be to change the program writing the files to write the files to a temporary file first, and then move that temporary file to the destination when it is done. On most operating systems, when the source and destination are on the same file system, move is atomic.
A: If you have no control over the writing portion, about all you can do is watch the file yourself, and when it stops growing for a certain amount of time, call it good. I have to use that method myself, and found 40 seconds is safe for my conditions.
A: Each OS will have a different solution, because file locking mechanisms are not portable.
*
*On Windows, you can use OS locking.
*On Linux you can have a peek at open files (similarily how lsof does) and if file is open, leave it.
A: Have you tried opening the file before coping it? If the file is still in use, then open() should throw exception.
try:
with open(filename, "rb") as fp:
pass
# Copy the file
except IOError:
# Dont copy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Extracting FOAF information from Jena I'm new here,and i have some problem about FOAF. I use jena create a FOAF like this :
<rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Person"/>
<foaf:phone>12312312312</foaf:phone>
<foaf:nick>L</foaf:nick>
<foaf:name>zhanglu</foaf:name>
But i want to the FOAF shows like this:
<foaf:Person>
<foaf:phone>12312312312</foaf:phone>
<foaf:nick>L</foaf:nick>
<foaf:name>zhanglu</foaf:name>
</foaf:Person>
What can i do?
this is my source code:
Model m = ModelFactory.createDefaultModel();
m.setNsPrefix("foaf", FOAF.NS);
Resource r = m.createResource(NS);
r.addLiteral(FOAF.name, "zhanglu");
r.addProperty(FOAF.nick, "L");
r.addProperty(FOAF.phone, "123123123");
r.addProperty(RDF.type, FOAF.Person);
FileOutputStream f = new FileOutputStream(fileName);
m.write(f);
who can tell me?
thanks
A: First thing to say is that the two forms that you quote have exactly the same meaning to RDF - that is, they produce exactly the same set of triples when parsed into an RDF graph. For this reason, it's generally not worth worrying about the exact syntax of the XML produced by the writer. RDF/XML is, in general, not a friendly syntax to read. If you just want to serialize the Model, so that you can read it in again later, I would suggest Turtle syntax as it's more compact and easier for humans to read and understand.
However, there is one reason you might want to care specifically about the XML serialization, which is if you want the file to be part of an XML processing pipeline (e.g. XSLT or similar). In this case, you can produce the format you want by changing the last line of your example:
m.write( f, "RDF/XML-ABBREV" );
or, equivalently,
m.write( f, FileUtils.langXMLAbbrev );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: asp.net form controls are unreadable when in a jQuery dialog, how do you fix it? I've got a prickly one. I have an asp.net web forms page. In the page I have a div tag that I've set to be used as a jQuery dialog. In the div is some jQuery controls. I get the dialog to open up and clicking on one of the buttons commences postback. When the page was posting back the code-behind hasn't been reading the values in the controls. Of course a little delving into the html reveals that the dialog takes my div and moves it to the bottom of the html page OUTSIDE my asp.net form tag. Urk!
How the hell do I get around this?
Not that it really helps the situation by my dialog code is here:
$("#dialog-copy").dialog({
autoOpen: false,
height: 200,
width: 400,
modal: true,
resizable: false,
buttons: {
'Cancel': function () {
$(this).dialog('close');
},
'Yes': function () {
$(this).dialog('close');
$("[id*=btnCopy]")[0].click();
}
},
open: function () {
$(":button:contains('Yes')").addClass("blue");
}
});
$("[id*=btnCopy]").live('mousedown', function (e) {
e.preventDefault();
$("#dialog-copy").dialog('open');
});
And a typical div tag (that is moved to outside my form tag) is looking like this:
<div id="dialog-copy" style="DISPLAY: none" title="Copy Schedule">
<p>Please enter a schedule number:</p>
<asp:Textbox runat="server" id="txtSchNo"></asp:Textbox>
</div>
Clicking 'Yes' fires the button that calls the postback.
A: It's a known issue, you have to append it to the form like this and your normal .NET controls can postback:
open: function () {
$(this).parent().appendTo("form");
$(":button:contains('Yes')").addClass("blue");
}
UPDATE for newer versions of jQuery:
$('#yourDIv').dialog({
.....,
appendTo: $('form'),
....
});
A: Have your dialog button function add a hidden field to the form with the correct name, i.e., using the input in the dialog itself for reference, before it submits the form.
buttons: {
'Cancel': function () {
$(this).dialog('close');
},
'Yes': function () {
$(this).dialog('close');
$('#dialog-copy').find('input').each( function() {
var $this = $(this);
$('form').append('<input type="hidden" name="'
+ $this.attr('name')
+ '" value="'
+ $this.val() + '" />');
});
$("[id*=btnCopy]")[0].click();
}
},
A: You could try this. Keep a regular html input within the dialog and just before clicking the postback button move the value within the html text input to the asp:TextBox or for that matter even a asp:HiddenInput.
Like:
$("#dialog-copy").dialog({
autoOpen: false,
height: 200,
width: 400,
modal: true,
resizable: false,
buttons: {
'Cancel': function () {
$(this).dialog('close');
},
'Yes': function () {
$(this).dialog('close');
$('input[id$=_txtSchNo').val($('#dummy').val());
$("[id*=btnCopy]")[0].click();
}
},
open: function () {
$(":button:contains('Yes')").addClass("blue");
}
});
$("[id*=btnCopy]").live('mousedown', function (e) {
e.preventDefault();
$("#dialog-copy").dialog('open');
});
And the markup:
<form>
....
<asp:Textbox runat="server" id="txtSchNo"></asp:Textbox>
...
</form>
<div id="dialog-copy" style="DISPLAY: none" title="Copy Schedule">
<p>Please enter a schedule number:</p>
<input type="text" id="dummy" />
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Parse a substring? I'm trying to convert the first two characters of a String using the parseInt method but I cannot. It's supposed to look like this:
String firstChars = IntMessage.substring(0,2);// firstChars is a String that corresponds to the first two characters of the string.
message=ASCII[(Integer.parseInt(firstChar))-32];//The message variable is a String that is supposed to take a firstChars variable and make it an integer so it can be used by the ASCII array in determining which element of the array is to be concatenated to the message String.
For example if the first two characters are 98, I want to take that substring and convert it into an int.
A: Well, other than the fact that your string is called firstChars and you're trying to parse firstChar, that should work fine.
But this is an area where you should either be using a debugger with breakpoints so you can figure out what values are being placed in the variables, or just print them out:
*
*IntMessage before doing the substring (and shouldn't this normally start with a lower case letter if it's an object?).
*firstChars after doing the substring (make sure it's numeric, for example).
*Integer.parseInt(firstChars) after that, making sure it's what you expect.
*Then Integer.parseInt(firstChars) - 32.
*Finally, ASCII[Integer.parseInt(firstChars) - 32].
Then it will be a simple matter of examining all the outputs to see what the problem is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Appcelerator Titanium Calendar Module Issue I have been having a bit of trouble getting this module to work: https://github.com/smontgomerie/Appcelerator-Calendar-Module.
After playing around with my application's tiapp.xml file and the module's manifest file, I have managed to get Titanium to detect the module. However, upon launching my app, I receive a "module not found" error.
I was wondering if anyone has managed to get this module working, and if so - how?
Thanking anyone who can help in advance!
A: Have you tried the alternative calendar module?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: this keyword inside a using block in C# What does this refer to inside of a using block in C#?
A: 1 - this always refers to the object scope you are currently in for example
void myFunc(int sameName)
{
this.sameName += sameName;
}
in this case this.sameName refers to the classes variable called sameName while the one without the this qualifier refers to the local variables (use in case you have local/globals with the same name or for clarity).
2 - Unmanaged resources are sockets, httpservers, connections, filebuffers, etc.... Anything that is IDisposable (that isn't automatically GC'ed like persistent connections or some GUI elements like Modeless forms etc...)
3 - technically yes, if you don't explicity call File.Close() or place it within a using statement then the changes you made to the file may not get flushed back to disc so if you have a file buffer open you should always call Close() on it.
EDIT: You can ignore 2 and 3 since he removed them from the question but I'll leave them here just in case
A: this inside of a using block refers to the same thing as this outside of a using block: the current instance of the class.
A using block should be used with all classes that implement the IDisposable interface. It's an implementation detail of the class if it wraps managed and/or unmanaged resources.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rendering with glDrawRangeElements() not working properly This is a followup to my previous question. All of my questions were answered in my last thread but this is a new error that I am having. When rendering in intermediate mode, everything looks great.
In fact:
http://i.imgur.com/OFV6i.png
Now, I am rendering with the glDrawRangeElements() and look what happens:
http://i.imgur.com/mEmH5.png
Has anyone seen something like this before? It looks as if some of the indices are simply in the middle, which makes no sense at all.
This is the function I am using to render my level.
void WLD::renderIntermediate(GLuint* textures, long curRegion, CFrustum cfrustum)
{
// Iterate through all of the regions in the PVS
for(int i = 0; i < regions[curRegion].visibility.size(); i++)
{
// Grab a visible region
int vis = regions[curRegion].visibility[i];
// Make sure it points to a mesh
if(regions[vis].meshptr == NULL)
continue;
// Make sure it is in our PVS
if(!cfrustum.BoxInFrustum(regions[vis].meshptr->minX, regions[vis].meshptr->minY, regions[vis].meshptr->minZ, regions[vis].meshptr->maxX, regions[vis].meshptr->maxY, regions[vis].meshptr->maxZ))
continue;
// Optional: Only render the region we are in (for testing)
//if(vis != curRegion)
// continue;
// Now find the ID of the zone mesh in the array
int id = regions[vis].meshptr->id;
// Figure out how many calls we will have to do to render it (different textures)
int calls = zmeshes[id].numPolyTex;
int count = 0;
// Render each call in batches
for(int j = 0; j < calls; j++)
{
// Bind the correct texture
glBindTexture(GL_TEXTURE_2D, textures[zmeshes[id].polyTexs[j].texIndex]);
// Set up rendering states
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
errorLog.writeSuccess("Drawing debug: ID: %i - Min: %i - Max: %i - Polys in this call %i - Count: %i - Location: %i", id, zmeshes[id].minmax[j].min, zmeshes[id].minmax[j].max, zmeshes[id].polyTexs[j].polyCount, zmeshes[id].polyTexs[j].polyCount * 3, count);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &zmeshes[id].vertices[0].x);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &zmeshes[id].vertices[0].u);
// Draw
glDrawRangeElements(GL_TRIANGLES, zmeshes[id].minmax[j].min, zmeshes[id].minmax[j].max, zmeshes[id].polyTexs[j].polyCount * 3, GL_UNSIGNED_SHORT, zmeshes[id].indices + count);
// End of rendering - disable states
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// Add the number of indices rendered
count += zmeshes[id].polyTexs[j].polyCount * 3;
}
}
}
I've done a ton of debug information indicating that my min/max values are set up correctly. At this point, I think it might be an error with the indices so I am going to go ahead an look over/rewrite that function.
A: Managed to get it to work. Very thankful that someone on another forum labeled his question accurately where a third vertex was being drawn at the origin.
http://www.gamedev.net/topic/583558-gldrawelements-is-drawing-all-of-my-vertices-with-one-vertex-at-the-origin-solved/page_gopid_4867052#entry4867052
Seems I needed to change my indices datatype from int to short. Works like a charm and I am getting a %1500 increase in FPS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cmake - Link custom library from higher level directory I'm learning about cmake and am finding it very fast to learn. However, documentation is not up to scratch. The tutorials are helpful, but only go so far.
What I have is an existing project that I want to convert to using cmake.
The project structure currently looks like:
obsys/
obsys/client/ {client files}
obsys/server/ {server files}
obsys/utils/include
obsys/utils/src
I've created CMakeLists.txt files at each level.
The top level looks currently like this:
make_minimum_required (VERSION 2.6)
project (osys)
add_subdirectory (server)
add_subdirectory (utils)
Inside utils I have a CMakeLists.txt that contains:
include_directories ("${PROJECT_SOURCE_DIR}/utils/include")
add_subdirectory (src)
and inside the utils src directory the CMakeLists.txt file contains:
add_library(utils myException.cpp)
The server needs to link to utils. It's CMakeLists.txt contains:
make_minimum_required (VERSION 2.6)
project (server)
include_directories ("../utils/include")
add_executable(serv serv.cpp)
add_subdirectory("../utils/src" utils)
target_link_libraries(obbsd utils)
The idea with this layout is I was hoping I could build the whole lot through the top level Makefile. Or, jump into server, or client and build either of them. It's not working out that way. What is the recommended way to do this?
A: Ok, I now have it working.
The problem is that my add_executable line wasn't listing all the source files.
Link seemed to be complaining about something to do with utils which made me think it wasn't finding the library when actually it was.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does removing this index in MySQL speed up my query 100x? I have the following MySQL table (simplified):
CREATE TABLE `track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(256) NOT NULL,
`is_active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `is_active` (`is_active`, `id`)
) ENGINE=MyISAM AUTO_INCREMENT=7495088 DEFAULT CHARSET=utf8
The 'is_active' column marks rows that I want to ignore in most, but not all, of my queries. I have some queries that read chunks out of this table periodically. One of them looks like this:
SELECT id,title from track where (track.is_active=1 and track.id > 5580702) ORDER BY id ASC LIMIT 10;
This query takes over a minute to execute. Here's the execution plan:
> EXPLAIN SELECT id,title from track where (track.is_active=1 and track.id > 5580702) ORDER BY id ASC LIMIT 10;
+----+-------------+-------+------+----------------+--------+---------+-------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+----------------+--------+---------+-------+---------+-------------+
| 1 | SIMPLE | t | ref | PRIMARY,is_active | is_active | 1 | const | 3747543 | Using where |
+----+-------------+-------+------+----------------+--------+---------+-------+---------+-------------+
Now, if I tell MySQL to ignore the 'is_active' index, the query happens instantaneously.
> EXPLAIN SELECT id,title from track IGNORE INDEX(is_active) WHERE (track.is_active=1 AND track.id > 5580702) ORDER BY id ASC LIMIT 10;
+----+-------------+-------+-------+---------------+---------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+---------+-------------+
| 1 | SIMPLE | t | range | PRIMARY | PRIMARY | 4 | NULL | 1597518 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+---------+-------------+
Now, what's really strange is that if I FORCE MySQL to use the 'is_active' index, the query once again happens instantaneously!
+----+-------------+-------+-------+---------------+---------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+---------+-------------+
| 1 | SIMPLE | t | range | is_active |is_active| 5 | NULL | 1866730 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+---------+-------------+
I just don't understand this behavior. In the 'is_active' index, rows should be sorted by is_active, followed by id. I use both the 'is_active' and 'id' columns in my query, so it seems like it should only need to do a few hops around the tree to find the IDs, then use those IDs to retrieve the titles from the table.
What's going on?
EDIT: More info on what I'm doing:
*
*Query cache is disabled
*Running OPTIMIZE TABLE and ANALYZE TABLE had no effect
*6,620,372 rows have 'is_active' set to True. 874,714 rows have 'is_active' set to False.
*Using FORCE INDEX(is_active) once again speeds up the query.
*MySQL version 5.1.54
A: It looks like MySQL is making a poor decision about how to use the index.
From that query plan, it is showing it could have used either the PRIMARY or is_active index, and it has chosen is_active in order to narrow by track.is_active first. However, it is only using the first column of the index (track.is_active). That gets it 3747543 results which then have to be filtered and sorted.
If it had chosen the PRIMARY index, it would be able to narrow down to 1597518 rows using the index, and they would be retrieved in order of track.id already, which should require no further sorting. That would be faster.
New information:
In the third case where you are using FORCE INDEX, MySQL is using the is_active index but now instead of only using the first column, it is using both columns (see key_len). It is therefore now able to narrow by is_active and sort and filter by id using the same index, and since is_active is a single constant, the ORDER BY is satisfied by the second column (ie the rows from a single branch of the index are already in sorted order). This seems to be an even better outcome than using PRIMARY - and probably what you intended in the first place, right?
I don't know why it wasn't using both columns of this index without FORCE INDEX, unless the query has changed in a subtle way in between. If not I'd put it down to MySQL making bad decisions.
A: I think the speedup is due to your where clause. I am assuming that it is only retrieving a small subset of the rows in the entire large table. It is faster to do a table scan of the retrieved data for is_active on the small subset than to do the filtering through a large index file. Traversing a single column index is much faster than traversing a combined index.
A: Few things you could try:
*
*Do an OPTIMIZE and CHECK on your table, so mysql will re-calculate index values
*have a look at http://dev.mysql.com/doc/refman/5.1/en/index-hints.html - you can tell mysql to choose the right index in different cases
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: ajax jquery settings So say I want to import (using ajax) a script which contains both some raw html and a java script:
<p>To comment, please first prove that you are human being</p>
<form method='post' action='../recapatcha_verify.php'>
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=your_public_key">
</script>
<input type='submit'/>
</form>
is there anything wrong with the following function?
function comments(file, id, fs, pn, ln)
{
$("div#commentWrapper").show(function(){
$.ajax({
url: "../commentfiles/" + file,
pid: id,
fs: fs,
pn: pn,
ln: ln,
dataType: script,
success: function(txt)
{
$("div#commentWindow").html(txt);
}
});
});
}
pid fs pn and ln are supposed to be parameters in the url. This works when i use the $.get method, but does it work the same for $.ajax??
I set datatype to "script" so that the javascript would be recognized. But is this correct? I'm not sure I know what I'm doing yet.
Thanks for your help
A: To answer one of your questions, no, $.ajax does not take parameters the same way as $.get. To send parameters, you must use data:
$.ajax({
...
data: {param1: 1, param2: 2, param3: 3},
...
});
Secondly, right now you're setting dataType to the value of a variable named script. You must set it to the string script:
$.ajax({
...
dataType: 'script',
...
});
Some other things:
*
*You may want to explicitly specify it's a GET request using type: 'GET'.
*If it's HTML that contains a script, script is the wrong data type. (script will try to evaluate the HTML as JavaScript, which won't work)
*.html will indeed insert the script tag, but it won't execute it. To get it to execute, you must remove and then re-insert the script tag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to override a collection's mapped order-by clause when paging in NHibernate? I have an entity with a bag collection and I want to page through the entire data set. The collection has an order-by clause. When I try to eager-load the collection, NHibernate is generating SQL that is very very slow because it causes SQL Server to sort on a very non-unique property, and there is a large amount of data in the table.
The code:
var session = NHibernateSessionManager.Instance.GetSession();
session.CreateCriteria<Album>()
.SetFetchMode("Track", FetchMode.Eager)
.SetMaxResults(1000)
.SetFirstResult(1)
.AddOrder(new Order("Id", true))
.List();
The bag mapping (note the order-by attribute):
<bag name="Track" inverse="true" lazy="true" batch-size="1000" cascade="none"
order-by="TrackNumber ASC">
The relevant SQL generated:
OVER(ORDER BY track2_.TrackNumber, this_.Id) as __hibernate_sort_row
If i remove the order-by from the mapping then the SQL changes to this (much better):
OVER(ORDER BY this_.Id) as __hibernate_sort_row
So the question is: is there a way to override or remove the mapped order-by clause?
A: After comments from Thilak Nathen and Firo, it looks like the short answer to the question is: "No you can't do that". The long answer is to remove the order-by attribute from the mapping and add it as needed. The reason it was there is that it's always needed, except for this one unusual situation. Firo suggested overriding the factory configuration which I think will work because this is for reporting. For anyone else who wants to know how to do it, here's the code to remove an order-by from an xml mapping programmatically:
Configuration cfg = new Configuration().Configure();
var albumMapping = cfg.ClassMappings.Where(x => x.DiscriminatorValue == "Foo.Album").First();
var trackProperty = albumMapping.GetProperty("Track");
var bagMapping = ((NHibernate.Mapping.Bag)trackProperty.Value);
bagMapping.OrderBy = "";
sessionFactory = cfg.BuildSessionFactory();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why this code does not compile using MS compiler? This code does compile using the GNU gcc compiler while doesn't if using the Visual Studio 2008 one.
the error sas: "error C2143: syntax error: missing ';' before '*'
Arbol::Nodo* is a pointer to the class inside Arbol that works ok if compiling using codeblocks + gnu gcc compiler.
template <class T>
Arbol<T>::Nodo<T>* Arbol<T>::Alta(Nodo<T>* &nodo,const T d) /////this line is highlited
{
return nodo;
}
It's weird, If I take out that code and compile again, it jumps three functions below it and
throws the same error with this function
template<class T>
Arbol<T>::Nodo<T>* Arbol<T>::BuscarDevolver(const T t)
{
Nodo<T>* nodo = new Nodo<T>;
return nodo;
}
A: Add typename:
template <class T>
typename Arbol<T>::Nodo<T>* Arbol<T>::Alta(Nodo<T>* &nodo,const T d) /////this line is highlited
{
return nodo;
}
You need to mark qualified names that are types explicitly within a template.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Activity Indicator IOS usage question First I would like to thank everyone who attempts to help me with my problem, I am new to iOS development, specifically objective-c, so I apologize if my question is extremely obvious.
I am making an app that loads some new data (parsed from a website but it is NOT a UIWebView) into the same current view every time the user changes a selection on the picker view (UIPickerView). The method that inserts this new data into the current view is called -(IBAction) getNewData: (id) sender.
getNewData is called every time the user makes a new selection with the picker. This is how it is called within the picker method and the picker as well as everything else works fine.
- (void)pickerView:(UIPickerView*)pickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
NSString *choosen;
choosen = [currentLottoNames objectAtIndex:row];
[self getNewData:choosen];
}
I would like to implement an activity indicator (spinner) for the loading time in-between the time the user makes/changes his selection on the scroller to the time the actual data shows up in the view after the user has made his selection on the scroller. How would I go about implementing this?
Thank you.
A: To show the user that you are accessing information via apples built in status bar you use
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
If you would like to display like a pop up message you need to declare in the header a
UIAlertView *load_message;
and then when you would like to show the load_message use
load_message = [[UIAlertView alloc] initWithTitle:@"Loading..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[load_message show];
UIActivityIndicatorView *active = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
active.center = CGPointMake(load_message.bounds.size.width / 2, load_message.bounds.size.height - 40);
[active startAnimating];
[load_message addSubview:active];
and that will show a pop up displayed to the user that you are loading something. This is for locking up the screen showing the user that you are getting some information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linq2Sql query - Pivot data with Grouping I have the following dataset for a TimeTable that needs to be displayed in a gridview. Currently a snippet of the dataset looks like this:
SessionNum TimeStart TimeStop Details
---------- --------- -------- -------
1 08:00 09:00 Math101
1 09:00 10:00 Comp102
1 11:00 12:00 Engn101
2 08:00 09:00 Comp102
2 09:00 10:00 Math101
2 10:00 11:00 Acco103
There are a total of 5 sessions, and I would like for the dataset to look like:
TimeStart TimeStop Session1 Session2 ...
--------- -------- -------- -------- ---
08:00 09:00 Math101 Comp102
09:00 10:00 Comp102 Math101
10:00 11:00 - Acco103
11:00 12:00 Engn101 -
As you will see, there are no aggregate functions required...just grouping, but for the life of me I cannot seem to wrap my head around this one. I have the following LINQ query which generates the first dataset:
List<TimeTable> list = db.TimeTables.OrderBy(o => o.TimeStart).OrderBy(o => o.SessionNum).ToList();
This works fine, and generates the dataset sorted by SessionNum and then TimeStart. My attempt to solve this invlovled the following query:
var result = list.GroupBy(t => t.TimeStart).Select(s => new {
TimeStart = s.Key,
Session1 = s.Where(x => x.SessionNum == 1),
Session2 = s.Where(x => x.SessionNum == 2)
});
This ran, but unfortunately did not work. I know a GroupBy (or a couple) is/are required, but I'm a bit lost from this point forward. I would really appreciate any help towards solving this. Thank you in advance!
A: You can't directly do a pivot query in LINQ. What you can do instead is create a structure like this:
var record = new
{
TimeStart = "10:00",
TimeStop = "11:00",
Sessions = new [] { "-", "Acco103", },
};
When you have a list of these records you must ensure that the Sessions property is array that is the same length as the distinct number of sessions in your entire set of data. Then you can access the session information by indexing into the array.
This should make more sense after looking at the queries.
First, query the database for the required data:
var query =
from s in db.TimeTables
orderby s.TimeStop
orderby s.TimeStart
group s by new { s.TimeStart, s.TimeStop } into gss
select new
{
gss.Key.TimeStart,
gss.Key.TimeStop,
Sessions = gss.ToArray(),
};
Now determine the distinct set of sessions:
var sessionNums =
db.TimeTables
.Select(s => s.SessionNum)
.Distinct()
.OrderBy(n => n)
.ToArray();
Now process this data in memory (note the .ToArray() call on query):
var process =
from q in query.ToArray()
let lookup = q.Sessions
.ToLookup(s => s.SessionNum, s => s.Details)
select new
{
q.TimeStart,
q.TimeStop,
Sessions = sessionNums
.Select(n => String.Join(
", ",
lookup[n].DefaultIfEmpty("-")))
.ToArray(),
};
This is where the hard work is. The lookup creates an easy way to get session detail out for any SessionNum. Calling lookup[n].DefaultIfEmpty("-") ensures that there is at least a single value for each session. The String.Join ensures that if the source data had two sessions for the same session number at the same time that we end up with one value.
This result is safe no matter how many sessions there are as it will just extend the arrays.
The output of the process query looks like this:
Then you can do this query:
var result =
from p in process
select new
{
p.TimeStart,
p.TimeStop,
Session1 = p.Sessions[0],
Session2 = p.Sessions[1],
};
This will effectively "pivot" your results, but you need to explicitly put in each "SessionX" property.
The output of the result query looks like this:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why this behavior when coercing a list to character via as.character()? In the process of (mostly) answering this question, I stumbled across something that I feel like I really should already have seen before. Let's say you've got a list:
l <- list(a = 1:3, b = letters[1:3], c = runif(3))
Attempting to coerce l to various types returns an error:
> as.numeric(l)
Error: (list) object cannot be coerced to type 'double'
> as.logical(l)
Error: (list) object cannot be coerced to type 'logical'
However, I'm apparently allowed to coerce a list to character, I just wasn't expecting this result:
> as.character(l)
[1] "1:3"
[2] "c(\"a\", \"b\", \"c\")"
[3] "c(0.874045701464638, 0.0843329173512757, 0.809434881201014)"
Rather, if I'm allowed to coerce lists to character, I would have thought I'd see behavior more like this:
> as.character(unlist(l))
[1] "1" "2" "3" "a" "b"
[6] "c" "0.874045701464638" "0.0843329173512757" "0.809434881201014"
Note that how I specify the list elements originally affects the output of as.character:
l <- list(a = c(1,2,3), b = letters[1:3], c = runif(3))
> as.character(l)
[1] "c(1, 2, 3)"
[2] "c(\"a\", \"b\", \"c\")"
[3] "c(0.344991483259946, 0.0492411875165999, 0.625746068544686)"
I have two questions:
*
*How is as.character dredging up the information from my original creation of the list l in order to spit out 1:3 versus c(1,2,3).
*In what circumstances would I want to do this, exactly? When would I want to call as.character() on a list and get output of this form?
A: For non-trivial lists, as.character uses deparse to generate the strings.
*
*Only if the vector is integer and 1,2,3,...,n - then it deparses as 1:n.
c(1,2,3) is double whereas 1:3 is integer...
*No idea :-)
...but look at deparse if you want to understand as.character here:
deparse(c(1L, 2L, 3L)) # 1:3
deparse(c(3L, 2L, 1L)) # c(3L, 2L, 1L)
deparse(c(1, 2, 3)) # c(1, 2, 3)
A: The help file does say
For lists it deparses the elements individually, except that it extracts the first element of length-one character vectors.
I'd seen this before in trying to answer a question [not online] about grep. Consider:
> x <- list(letters[1:10],letters[10:19])
> grep("c",x)
[1] 1 2
grep uses as.character on x, with the result that, since both have c( in them, both components match. That took a while to figure out.
On "Why does it do this?", I'd guess that one of the members of R core wanted it to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Getting the text from a NSTextField and setting it to an already defined String Im brand new to Cocoa, and im struggling to find the answer and figure it out.
if I have a NSTextField how can I get the value (stringvalue) of that and save it in a predefined string variable, there after display it in the debug using NSLog()?
Thanks
A: Just use the stringValue method by NSTextField and save it to a NSString
@interface MyClass : NSObject
{
NSTextField *textField;
}
-(IBAction)displayString:(id)sender;
@end
@implementation
-(IBAction)displayString:(id)sender
{
NSString *string = [textField stringValue];
NSLog (@"%@", string);
}
@end
Just connect the displayString method to the NSTextField and it should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML5 Cache Manifest problem I am trying to use it to cache all the static files for my application (images, JS etc.) but I am running into a problem. My cache manifest file can looks like this:
CACHE MANIFEST
CACHE:
templates/v2/css/somecss.css
templates/v2/js/somejs.js
templates/v2/images/someimages.jpg
NETWORK:
*
This does cache those files that I have added to it (a few hundred so I omitted most of them out) but it also caches pages that I don't want (ex. index.php). It dramatically lowers the loadtime of the whole application but I need it not to cache any php files. I am using MultiViews if that makes any difference.
I have also tried adding a list of the files that I don't want cached under network but it still caches them. The full file can be found at https://app.emailsmsmarketing.com/cache.manifest
A: The problem might not be with the manifest itself.
Are you adding the manifest attribute to all your php pages? That could be the issue.
The manifest attribute should be included on every page of your web
application that you want cached. The browser does not cache a page if
it does not contain the manifest attribute (unless it is explicitly
listed in the manifest file itself. This means that any page the user
navigates to that include a manifest will be implicitly added to the
application cache.
http://www.html5rocks.com/en/tutorials/appcache/beginner/#toc-manifest-file-reference
A: You can also specify the .php files which you do not want to be cached in the NETWORK section. WHichever file you specify here will be accessed from the server.
You can make use of wildcard i believe for all php files
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I prevent someone from reading my .htaccess file? I added a .htaccess file to a folder to make it password protected. I would like to prevent all users from being able to read that .htaccess file, because it reveals the location of my .htpasswd (I don't have permissions on this server to put this file outside of the html tree).
I tried the suggestions at http://www.javascriptkit.com/howto/htaccess8.shtml, but I can still read my .htaccess on a web browser. Here is my .htaccess:
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /home/www/users/mylogin/HTML/some_hidden_dir/.htpasswd
AuthGroupFile /dev/null
require valid-user
<Files .htaccess>
order allow,deny
deny from all
</Files>
What am I missing?
A: I've always used this method in my main root HTACCESS file and it works like a charm:
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
More info on this method from one of my bookmarks:
http://perishablepress.com/press/2008/05/20/improve-site-security-by-protecting-htaccess-files/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Javascript + Radio Button / CheckBox Validation In Plain Ole' Javascript, do I NEED to use a loop to loop through the radio buttons/checkboxes to see if they are checked or is there a simpler way of doing this?
A: Yes. It may be most helpful to...
*
*...have them all contained in one element, so you can traverse through its children
*...apply a class name to all of them, to use document.getElementsByClassName
*...use document.getElementsByTagName (though, the tag is the input tag, so you may get other elements as well)
However, that is just getting the elements; but as you've stated, you will still need to iterate through each one to do whatever comparison you like. jQuery will allow you to do this kind of thing more easily, but "Plain Ole' Javascript" cannot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Application Request Limit Reach - How much data is too much? We're getting a lot of "Application request limit reached" exception in our app. Looking at the insights page, it looks like "posts" from the graph API for "Calls access too much data" is the problem (108% right now). I would like to know what "Too much data" mean exactly ? Is it the number of bytes in a single call or the total number of bytes for a set of calls in a given period of time ? Or totally something else ?
Currently, I'm requesting posts one at a time so I can't see the first option being the problem. I don't understand why Facebook don't give any more info about this so if someone know the answer, I would really like to know.
Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does my Clojure import fail? I'm running Clojure 1.3 with contrib 1.1 in IntelliJ. My program consists of a single line
(use 'clojure.contrib.prxml)
I get the following error upon running
Exception in thread "main" java.lang.RuntimeException: java.lang.NoSuchMethodError: clojure.lang.RestFn.<init>(I)V
A:
I'm running Clojure 1.3 with contrib 1.1
There's your problem. Clojure and contrib versions are linked against each other, and are not compatible across versions.
Even more, contrib has been split up into lots of smaller libraries as of 1.3, so there is really no version of "monolithic contrib" that you can use with 1.3.
A: In addition to the answers saying that contrib 1.1 is incompatible with clojure 1.3
Taken from here:
Versions of clojure-contrib are matched to versions of Clojure.
If you are using Clojure 1.0, use clojure-contrib 1.0.
If you are using Clojure 1.1, use clojure-contrib 1.1.
If you are using Clojure 1.2, use clojure-contrib 1.2, or the new modular Contrib libraries.
If you are using Clojure 1.3, use the new modular Contrib libraries.
As of the date of this reply I'm not sure if there is a version of clojure.contrib.prxml that is compatible with clojure-1.3 (Someone please correct me if I'm wrong).
So I would suggest using clojure-1.2.1 and clojure-contrib 1.2.0.
A: Nothing is wrong with the call works with clojure 1.2 and contrib 1.2
If you don't need anything 1.3 specific I would suggest sticking to 1.2 for the time being, use clojure 1.2 and contrib 1.2 until contrib authors properly make the transition to 1.3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How much programmer "assist" does Java normally need for a switch to JIT to a dispatch table? I understand that Java does optimizations across the board and can optimize switches depending on how many cases there are, whether the switch is sparse or dense, and if the code is even hot enough for the JIT to optimize said code. I'm just wondering if I need to further provide "assist" like using bitwise and on the variable being tested or bitwise shift the variable to a "nicer" number, assuming said code is indeed very hot. "nicer" being 0xXX rather than 0xFFXX. Are there hotspot JIT docs that specifically state what's required? Rather than "just keep it along the general programming guidelines of xxx."
A: The decision for either tableswitch or lookupswitch is already done by the javac compiler. I have never heard that the JIT tries to transform a lookupswitch into a tableswitch.
So your first step should be a check into what bytecode javac translated your switch.
A: There is not going to be an easy answer to this.
I would take this question to hotspot-dev - they may be able to provide more information about how this happens.
The other people who may have interesting perspectives on this hang out on the jvm-l mailing list (Charlie Nutter, Remi Forax, John Rose, etc.)
A: Because Java itself runs over a virtual machine, unless I'm missing something here, I don't think there's an easy way to do this.
So with Java, you get a black box of sorts, and to optimize more is risky, IMHO.
For the Hotspot JIT whitepaper, see here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can I call a Python macro in a cell formula in OpenOffice.Org Calc? To extend OpenOffice's capabilities, I've defined some Python macros in a file in the user script directory (~/Library/Application Support/OpenOffice.org/3/user/Scripts/python/, in my case). The macros are visible in the Python macro organizer. However, using the functions in a cell formula results in "#NAME?" (OO.org error 525).
Suppose I've defined the following function :
def pytype(val):
return str(type(val))
How can I call pytype in a cell formula (e.g. =PYTYPE("string"))?
Background
I'm importing some data from Authorize.net into a MySQL database for analysis. MySQL can't parse the date & time format used by Authorize.net into a DATETIME or TIMESTAMP field, so I'm trying to massage the data into a format MySQL can handle before import. OpenOffice also doesn't recognize the data as a date & time and, as far as I've been able to determine, OO.Org doesn't have a generic date parsing function. Thus I'm extending OO.org's capabilities.
There are other approaches to the larger issue. For example, I could also try to fix up the data in MySQL post-import using additional columns. In fact, this is what I did the first time; however, there's now existing data in the table to contend with. Because of that, and because there are other tasks in the future I hope to accomplish by using macros in formulas, for now I'm mostly interested in calling Python macros in formulae.
A: On the old OO.org forums, (super)user Villeroy posted an illustration of how to call Python functions from OO.org Basic, which can then be used in formulae. The key is to use the com.sun.star.script.provider.MasterScriptProviderFactory service as a bridge. Here is an adaptation of his solution, generalized to call arbitrary functions in arbitrary modules:
REM Keep a global reference to the ScriptProvider, since this stuff may be called many times:
Global g_MasterScriptProvider as Object
REM Specify location of Python script, providing cell functions:
Const URL_Main as String = "vnd.sun.star.script:"
Const URL_Args as String = "?language=Python&location=user"
Function invokePyFunc(file AS String, func As String, args As Array, outIdxs As Array, outArgs As Array)
sURL = URL_Main & file & ".py$" & func & URL_Args
oMSP = getMasterScriptProvider()
On Local Error GoTo ErrorHandler
oScript = oMSP.getScript(sURL)
invokePyFunc = oScript.invoke(args, outIdxs, outArgs)
Exit Function
ErrorHandler:
Dim msg As String, toFix As String
msg = Error$
toFix = ""
If 1 = Err AND InStr(Error$, "an error occurred during file opening") Then
msg = "Couldn' open the script file."
toFix = "Make sure the 'python' folder exists in the user's Scripts folder, and that the former contains " & file & ".py."
End If
MsgBox msg & chr(13) & toFix, 16, "Error " & Err & " calling " & func
end Function
Function getMasterScriptProvider()
if isNull(g_MasterScriptProvider) then
oMasterScriptProviderFactory = createUnoService("com.sun.star.script.provider.MasterScriptProviderFactory")
g_MasterScriptProvider = oMasterScriptProviderFactory.createScriptProvider("")
endif
getMasterScriptProvider = g_MasterScriptProvider
End Function
This can then be used to create a OO.org Basic function callable in a formula. Using the example pytype:
Const libfile as String = "util" REM functions live in util.py
Function pytype(value)
pytype = invokePyFunc(libfile, "pytype", Array(value), Array(), Array())
End Function
Another potential implementation is to create a Python add-in. However, this is a much heavier option as it requires installing the OpenOffice SDK, and it isn't obvious to me whether this approach would work for free functions or only works for classes.
A: outis - thanks for your awesome answer. If it weren't for you I'd be mad by now still writing basic macros!
I just have some remarks, though:
Last 2 arguments to invokePyFunc are always empty - just use this:
const filename = "your_file"
Function pyFunc(func as String, args as Array)
pyFunc = invokePyFunc(filename, func, args, Array(), Array())
End Function
Multi-dimensional arrays are tricky to return. If you return ((1,2,3), (4,5,6)) calc treats that as 2 cells in a row containing unknown objects.
This is because basic and python treat multi-dimensional arrays differently.
If you return such structure to basic, you have to access it like data(row)(col) and calc expects data(row, col) for multi-dimensional arrays.
Because of that you need to use a converter function for return values:
' Converts python multidimensional arrays to basic arrays.
function convPy2Basic(pyvalue)
if isarray(pyvalue) then
dim lastRow as integer
lastRow = ubound(pyvalue)
if lastRow = -1 then
' empty array
convPy2Basic = ""
else
if isarray(pyvalue(0)) then
' Multi-dimensional array
dim maxCols as integer, lastCol as integer
maxCols = ubound(pyvalue(0))
dim res(lastRow, maxCols)
for rowIndex = 0 to lastRow
lastCol = ubound(pyvalue(rowIndex))
' Expand array if needed.
if lastCol > maxCols then
maxCols = lastCol
redim preserve res(lastRow, maxCols)
end if
for colIndex = 0 to lastCol
res(rowIndex, colIndex) = pyvalue(rowIndex)(colIndex)
next colIndex
next rowIndex
convPy2Basic = res
else
' Single-dimensional array - this is supported by libreoffice
convPy2Basic = pyvalue
end if
end if
else
convPy2Basic = pyvalue
end if
end function
Function invokeScriptFunc(file AS String, lang, ext, func As String, args As Array, outIdxs As Array, outArgs As Array)
sURL = URL_Main & file & "." & ext & "$" & func & "?language=" & lang & "&location=user"
oMSP = getMasterScriptProvider()
oScript = oMSP.getScript(sURL)
invokeScriptFunc = oScript.invoke(args, outIdxs, outArgs)
end Function
Function invokePyFunc(file AS String, func As String, args As Array, outIdxs As Array, outArgs As Array)
res = invokeScriptFunc(file, "Python", "py", func, args, outIdxs, outArgs)
invokePyFunc = convPy2Basic(res)
end Function
So my python-basic macro bridge looks like this:
' Keep a global reference to the ScriptProvider, since this stuff may be called many times:
Global g_MasterScriptProvider as Object
' Specify location of Python script, providing cell functions:
Const URL_Main as String = "vnd.sun.star.script:"
' Converts python multidimensional arrays to basic arrays.
function convPy2Basic(pyvalue)
if isarray(pyvalue) then
dim lastRow as integer
lastRow = ubound(pyvalue)
if lastRow = -1 then
' empty array
convPy2Basic = ""
else
if isarray(pyvalue(0)) then
' Multi-dimensional array
dim maxCols as integer, lastCol as integer
maxCols = ubound(pyvalue(0))
dim res(lastRow, maxCols)
for rowIndex = 0 to lastRow
lastCol = ubound(pyvalue(rowIndex))
' Expand array if needed.
if lastCol > maxCols then
maxCols = lastCol
redim preserve res(lastRow, maxCols)
end if
for colIndex = 0 to lastCol
res(rowIndex, colIndex) = pyvalue(rowIndex)(colIndex)
next colIndex
next rowIndex
convPy2Basic = res
else
' Single-dimensional array - this is supported by libreoffice
convPy2Basic = pyvalue
end if
end if
else
convPy2Basic = pyvalue
end if
end function
Function invokeScriptFunc(file AS String, lang, ext, func As String, args As Array, outIdxs As Array, outArgs As Array)
sURL = URL_Main & file & "." & ext & "$" & func & "?language=" & lang & "&location=user"
oMSP = getMasterScriptProvider()
oScript = oMSP.getScript(sURL)
invokeScriptFunc = oScript.invoke(args, outIdxs, outArgs)
end Function
Function invokePyFunc(file AS String, func As String, args As Array, outIdxs As Array, outArgs As Array)
res = invokeScriptFunc(file, "Python", "py", func, args, outIdxs, outArgs)
invokePyFunc = convPy2Basic(res)
end Function
Function getMasterScriptProvider()
if isNull(g_MasterScriptProvider) then
oMasterScriptProviderFactory = createUnoService("com.sun.star.script.provider.MasterScriptProviderFactory")
g_MasterScriptProvider = oMasterScriptProviderFactory.createScriptProvider("")
endif
getMasterScriptProvider = g_MasterScriptProvider
End Function
const filename = "skaiciuokle"
Function pyFunc(func as String, args as Array)
pyFunc = invokePyFunc(filename, func, args, Array(), Array())
End Function
And is used like this:
function DamageToArmor(data, damageType as String, armorType as String, dmgPerGun as Integer, guns as Integer)
DamageToArmor = pyFunc("dmg2armor", Array(data, damageType, armorType, dmgPerGun, guns))
end function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: MacOSX Socket Programming without run loop Currently there is a CSNetwork class and a stream class with a run loop to recieve.
Due to some reason I do not wish to have callbacks in my socket class code.
I am looking for the following
- simple connect API
- simple send API
- simple recv API
- simple getHostbyName equivalent without a callback
Can someone help
A: In short, don't do that unless you really need the code to be portable. If you do, then use the pure POSIX APIs, of which there are about a zillion examples and sites available for reference.
You'll be far better off sticking with the higher level, callback based, APIs using run loops and/or queues. Less code. Easier to maintain. More efficient (in that it is better integrated with the platform).
If you still think you need to go the route of no callbacks, explain why. Keep in mind that synchronous code is just asynchronous code that blocks waiting for a callback....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Async CTP call a wcf ria service method that returns a string value I'm trying to implement the following into my silverlight wcf ria services project.
http://blogs.msdn.com/b/kylemc/archive/2010/11/02/using-the-visual-studio-async-ctp-with-ria-services.aspx
It is working fine for entities. However I'm trying to write a custom method that returns a string and throws an error.
Custom method
public string GetHello(string str)
{
return ("Hello " + str);
}
Calling from Client
String str;
str = await context.LoadAsync(context.GetHello("Sam")).ToString();
Error:
The 'await' operator requires that its operand
'System.ServiceModel.DomainServices.Client.InvokeOperation'
have a suitable public GetAwaiter method
A: You need to call AsTask to convert the InvokeOperation to a Task.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pop up dialog in Android home screen Is it possible to show pop up dialog (AlertDialog) in home screen on the android device via services?
A: Does anyone needs option, "android:launchMode="singleInstance", when pop activity in the broadcast receiver or Service??
Without this option, my app started automatically and pop MyDialogActivity above it.
And then, something happened wrong. (My app has the Main Activity with auto-login function. When the other new Activity started automatically, MyDialogActivity is hided by it.)
So, this is my sample xml code.
<activity
android:name=".MyDialogActivity"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Dialog" />
<activity
I hope someone needs my comments. :)
A: You can not create dialog from service but we have one alternative solution is that You can create dialog activity and start that activity from your service
You can set Theme of activity as dialog by below way
<activity android:name=".MyDialogActivity" android:theme="@android:style/Theme.Dialog"
android:label="@string/app_name">
</activity>
A: You could create an Activity with the Theme.Dialog theme. In your AndroidManifest.xml file add the theme to the activity, like this:
<activity android:name=".DialogActivity" android:theme="@android:style/Theme.Dialog"></activity>
From your service simply start this Activity. You will have to start the activity with the Intent.FLAG_ACTIVITY_NEW_TASK flag. See How to start an Activity from a Service
A: Create CustomDialog As Activity
add to manifest
<activity android:name=".view.activity.CustomDialog"
android:launchMode="singleInstance"
android:screenOrientation="fullSensor"
android:theme="@style/AlertDialogTheme"
/>
add Style AlertDialogTheme to style.xml
<style name="AlertDialogTheme" parent="Theme.MaterialComponents.Light.Dialog.Alert.Bridge">
</style>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Get last created ID with auto-increment in MySQL I have a primary index on column URL but at the same time I need to have records with URL left blank which won't be permitted by the index.
I thought of a solution which is to add a new column called ID and make it auto-increment.
So I need to get the ID created with auto-increment on INSERT so that I stick it to column URL too. How can I do this?
If you can think of a better solution please tell
thanks
A: It is almost certainly better to use the mysql wrapper in your scripting language of choice to acquire the last insert id, but you can SELECT LAST_INSERT_ID(); to get it with mysql itself.
A: The solution may depend on what other columns you have on your table. It will be hard for you to add an auto_increment column to a table that already has data. The process will be to create a new table with the new column added and add the data from the old table and then drop the old table and re-name the new one to the matching name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implementing Request Response design I am trying to implement a request/response client. Here is the basic implementation for it.
Class Request
{
prepareRequest1();
prepareRequest2();
}
Class Response
{
processResponse1();
processResponse2();
}
Class Client
{
connect();
sendRequest();
}
myrequest = new Request();
client = new Client (myserver);
my $rawResponse1 = client.sendRequest (myrequest.prepareRequest1());
myresponse = new Response();
myresponse.processResponse1 ($rawResponse1);
I have three classes namely - Request, Response and Client. Request class contains a function specific to a request. These request are the XML requests. There XML request does not have anything in common except few initial tags (e.g. sessionid etc). All other XML parameters are specific to the type of request. So, Currently I am handing it by creating a separate function for each request. I understand that it has a scalability issue, but please suggest me some other best approach I can apply here.
Similar to the request, the response to each request require a specific treatment. so I have a separate function specific to each type of response I am expecting. Generally you can assume that there is a 1:1 mapping between request and response.
Last is the Client class which hands for connection.
I have almost 50+ such request and response, and I am planning to implement with this approach. As I am in initial stage of development, please suggest me some improvement/best practices to implement such request/response.
A: Its best if you keep the mapping of the request and response outside of your code. Easier to manage. Keep an xml config file that stores the class names of your request and response tied to a particular type of xml message. You can then obtain the class names and go to that class to process your request and response. Its best to have separate classes to handles these messages rather than separate methods. Thats more scalable. Ensure you have interface for all your request classes and the same for your response classes. This will make it easy to swap your request responses classes easily by modifying the xml config file..
Hope you got it :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WCF Broadcast through a proxy I am using WCF Broadcast, WCF client directly connects to WCF Server and server broadcasts data to client. I don't know WCF connection have a proxy support or not? WCF Client will connect to WCF Server through a proxy, and WCF Server will broadcast data to WCF Client through this proxy.
If yes, please help me how to deploy. Thanks.
A: You set the proxy settings in your bindings like so:
<defaultProxy useDefaultCredentials="true">
<proxy bypassonlocal="True" proxyaddress="http://..." />
</defaultProxy>
*
*UseDefaultWebProxy - if set to true, will use the global value HttpWebRequest.DefaultProxy as your proxy.
*ProxyAddress - to specify your proxy directly, you will need to set UseDefaultWebProxy to false as well
*BypassProxyOnLocal - lets local connections bypass the proxy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R how to convert the data.frame into time series one by one I have a series of data.frame like
r t
1 x 2
2 y 3
3 z 4
but I want to convert these three into time series, like
q = xts(as.matrix(data[1,]), order.by = "2011-09-28")
qq = xts(as.matrix(data[2,]), order.by = "2011-09-28")
qqq = xts(as.matrix(data[3,]), order.by = "2011-09-28")
My question is that since each time I only change rownames (1,2,3) and the names q qq qqq, may I sum them up into only one comment? like implement some functions?
A: df=data.frame(list(r=c("x","y","z"),t=c(2,3,4)))
dfx=as.xts(df,order.by=rep(as.POSIXct("2011-09-28"),nrow(df)))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do arrays work, behind the scenes? I'm trying to use basic operators to create my own custom array in JavaScript, I guess.
This book I'm reading, "Eloquent JavaScript", has an exercise in Chapter 1 that asks me to make a pyramid using the "print" function. There's no print function in any of my interpreters, and it doesn't say how to make a print function. So, I don't have a print function, and I'm using alerts.
Here's the code.
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
print(line);
counter = counter + 1;
}
So, I was trying to use alerts, instead:
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
alert(line);
counter = counter + 1;
}
But the alert isn't a triangle. It's a bunch of boxes where the number of pound signs grows each time.
I want to create a string concatenation and then print out the entire result.
This is what I came up with:
string = "";
counter = 0;
signs = "#";
while (counter < 10){
string = string + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(string);
So, I am just wondering, is there a better way to create arrays without knowing how to create array variable?
A: Your first pound-sign (tip of pyramid) should be spaced half the length of your base of your pyramid. So, if your base is 10 # signs long, then the top of your pyramid should be spaced out to 4 spaces then print the # sign.
Second, to make a true pyramid, you'll need to print top to bottom so your second row is progressively getting larger. Think in odd numbers:
// Example
Tip: 1 char
2nd row: 3 chars
3rd row: 5 chars
4th row: 7 chars
5th row: 9 chars
6th row: 11 chars
etc
Your newline character is wrong. It should be a \n. If printing to HTML, then use <BR>.
Alternatively, you can use console.log to print your characters.
A: This should work
var stringBuilder = "";
counter = 0;
signs = "#";
while (counter < 10){
stringBuilder = stringBuilder + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(stringBuilder);
*
*Newline is backslash and "n"
*You need only one newline character that is within the loop
A: The following code should work:
string = "";
counter = 0;
signs = "#";
while (counter < 10){
string = string + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(string);
The major differences are as follows:
*
*You can't include the newline character in the string you are building, otherwise newlines from previous iterations will still be included in subsequent iterations.
*The newline character is \n and not /n.
*string can start off as being empty, since you will be appending a "#" each time.
A: The newline character is "\n" not "/n". (The "escape" character in general is backslash not forward slash.)
Also, you have a typo that you said sings = ... instead of signs = ...
EDIT: OK, so you've updated your question to correct both of those problems. Regarding your new question:
So, I am just wondering, is there a better way to create arrays
without knowing how to create array variable?
It sounds like you don't really understand what an array variable is: an array is a data structure that allows you to store data items that are selected by indices. Why do you think you need an array for this "pyramid" functionality?
As an aside, your code could be improved using += and ++:
*
*a = a + b; can be abbreviated as a += b;
*a = a + 1; can be abbreviated as a++;
A: This would be another way to do it:
<script>
string = ""; height = 10;
for(i = 1; i <= height; i++){
string += Array(i).join('#') + '<br>';
}
document.write(string);
</script>
Output:
#
##
###
####
#####
######
#######
########
#########
Now with some more modification:
<script>
string = ""; height = 10;
for(i = 1; i <= height; i++){
string += Array(height-i+1).join(' ') + Array(2*i).join('#') + '<br>';
}
document.write(string);
</script>
<style>body{font-family:monospace;}</style>
You get this:
#
###
#####
#######
#########
###########
#############
###############
#################
###################
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Youtube API: losing data via curl in PHP? I'm sure that this is likely a simple solution, but I can't see my error. I'm making an API call to youtube to get some basic information on a youtube video using the video's ID; specifically what I want is the (1) title, (2) description, (3) tags, and (4) thumbnail.
When I load an API url via my web browser, I see all the data. I don't want to paste the entire response in this question, but paste the following url in your browser and you'll see what I see: http://gdata.youtube.com/feeds/api/videos/_83A00a5mG4
If you look closely you'll see media:thumbnail, media:keywords, content, etc. Everything I want is there. Now the troubles...
When I load this same url through the following functions (which I copied from the Vimeo api...), the thumbnail and keywords simply aren't there.
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
// youtube_get_ID is defined elsewhere...
$request_url = "http://gdata.youtube.com/feeds/api/videos/" . youtube_get_ID($url);
$video_data = simplexml_load_string(curl_get($request_url));
These functions do give me a response with some data, but the keywords and thumbnail are missing. Could anyone please tell me why my thumbnail and keywords are missing? Thank you for any help!
A: Here's the link for documentation on this.
Here's a function I wrote:
function get_youtube_videos($max_number, $user_name) {
$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/' . $user_name . '/uploads?max-results=' . $max_number);
$server_time = $xml->updated;
$return = array();
foreach ($xml->entry as $video) {
$vid = array();
$vid['id'] = substr($video->id,42);
$vid['title'] = $video->title;
$vid['date'] = $video->published;
//$vid['desc'] = $video->content;
// get nodes in media: namespace for media information
$media = $video->children('http://search.yahoo.com/mrss/');
// get the video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$vid['length'] = $attrs['seconds'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$vid['thumb'] = $attrs['url'];
// get <yt:stats> node for viewer statistics
$yt = $video->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$vid['views'] = $attrs['viewCount'];
array_push($return, $vid);
}
return $return;
}
And here's the implementation:
$max_videos = 9;
$videos = get_youtube_videos($max_videos, 'thelonelyisland');
foreach($videos as $video) {
echo $video['title'] . '<br/>';
echo $video['id'] . '<br/>';
echo $video['date'] . '<br/>';
echo $video['views'] . '<br/>';
echo $video['thumb'] . '<br/>';
echo $video['length'] . '<br/>';
echo '<hr/>';
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: OpenCV find biggest contours? I have an image, on which I used cvFindContours () on- I stored the result in imageContours. I am then trying to find the two biggest contours and display ONLY them. But for some reason its showing way more than 2 contours. What's wrong with my algorithm? Thanks
EDIT: Oh and also, in console, I keep getting the "Error" message, that I programmed below if none of the options are true. Anyone know why?
cvFindContours (binMask, imageContoursMem, &imageContours, sizeof (CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //find the contours in binMask, and store results in ImageContours
//following conditions used to set f_handContour to the bigger contour for the first time, and s_handContour to the smaller contour for the first time
if ( (cvContourArea (imageContours, CV_WHOLE_SEQ)) > (cvContourArea((imageContours -> h_next), CV_WHOLE_SEQ)))
{ //begin first contour bigger condition
f_handContour = imageContours;
s_handContour = (imageContours -> h_next);
} //end second contour bigger condition
else if ( (cvContourArea (imageContours, CV_WHOLE_SEQ)) < (cvContourArea((imageContours -> h_next), CV_WHOLE_SEQ)))
{ //begin second contour bigger condition
f_handContour = (imageContours -> h_next);
s_handContour = imageContours;
} //begin second contour biggger condition
else if ( (cvContourArea (imageContours, CV_WHOLE_SEQ)) == (cvContourArea((imageContours -> h_next), CV_WHOLE_SEQ)))
{ //begin contours equal condition
f_handContour = imageContours; //if contours equal assignment of contours doesn't matter
s_handContour = (imageContours -> h_next);
} //end contours equal condition
else
{ //begin error condition
cout<<"Error";
} //end error condition
while ((imageContours -> h_next) != NULL)
{ //start of biggest/second biggest contour recognition loop
imageContours = (imageContours -> h_next);
if ( cvContourArea (f_handContour, CV_WHOLE_SEQ) < cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //start of next contour bigger than f_handContour condition
s_handContour = f_handContour;
f_handContour = imageContours;
} //end start of next contour bigger than f_handContour condition
else if ( cvContourArea (f_handContour, CV_WHOLE_SEQ) > cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //start of next contour smaller than f_handContour condition
if ( cvContourArea (s_handContour, CV_WHOLE_SEQ) < cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //startof next contour bigger than s_handContour condition
s_handContour = imageContours;
} //end of next contour bigger than s_handContour condition
else if ( cvContourArea (s_handContour, CV_WHOLE_SEQ) > cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //start of next contour smaller than s_handContour condition
//just pass on contour
} //end of next contour smaller than s_handContour condition
else if ( cvContourArea (s_handContour, CV_WHOLE_SEQ) == cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //start of next contour equal to s_handContour condition
//just pass on contour
} // end of next contour equal to s_handContour condition
else
{ //start of error condition
cout<<"Error";
} //end of error condition
} //end of next contour smaller than f_handContour Condition
else if ( cvContourArea (f_handContour, CV_WHOLE_SEQ) == cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //start of next contour equal to f_handContour condition
if ( cvContourArea (s_handContour, CV_WHOLE_SEQ) < cvContourArea (imageContours, CV_WHOLE_SEQ))
{ //startof next contour bigger than s_handContour condition
s_handContour = imageContours;
} //end of next contour bigger than s_handContour condition
else
{ //start of error condition
cout<<"Error";
} //end of error condition
} //end of next contour equal to f_handContour condition
else
{ //start of error condition
cout<<"Error";
} //end of error condition
} //end of biggest/second biggest contour recognition loop
cvDrawContours (output, f_handContour, cvScalar (0,255,0), cvScalar (0,255,255), 1, 3,8, cvPoint (0,0)); //draws the first hand contour derived from binMask on ouput
cvDrawContours (output, s_handContour, cvScalar (0,255,0), cvScalar (0,255,255), 1, 3,8, cvPoint (0,0)); //draws the second hand contour derived from binMask on ouput
A: CV_RETR_EXTERNAL retrieves only the extreme outer contours.
For your algorithm you should use CV_RETR_LIST.
Try using as max_level for the cvDrawContours function the value 0, as value 1 draws the current contour and all the others that are on the same level with it.
Also you can optimize your conditions a lot (it's kind of a mess) and also store the areas in some local variables as to not call cvContourArea so much.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Which Database should I use for small network application I have an application (currently in foxpro) that uses about 12 tables that can be networked.
The tables are related in various ways, but not unduely complex - more like a customer ordering system
I want to rewrite it in C# using MS Visual Studio.
The Application is desktop only but with up to 5 users able to access it at any given time.
The question is which DB should I use?
It needs to be:
*
*Easy to install with the application.
*Support sharing from up to 3 or 4 computers
I have looked at SQL Express but the sharing issue looks to be fairly complex and installation for SQL on a server computer is required.
DB4O seems to be for more media rich applications.
I am fairly new to C# (and now getting long in the tooth as well) so I need this to be a reasonably painless way to achieve what I already have in Foxpro.
Some may ask why change - well, there are things that we want to be able to add in the future that would stretch Foxpro too far.
I have spent a couple of weeks researching this and now would really appreciate any help that people could offer.
A: My policy: If the job can be handled by SQLite (for .NET one option is System.Data.SQLite), use that. On the surface, it sounds like this can.
SQLite is [...] a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain.
A: Just to stir the pot a bit, if you're connected to the internet you could give a SQL Azure Database a whirl.
No server required; multiple connections not a problem; scalable; maintainable; etc. Synch it with a local database later if you change your mind. MS has a 90 day trial run which would probably suit your investigative purposes.
Downsides are well-covered elsewhere, but mainly it's that internet outage renders your app offline.
It's actually not a bad option if you're looking to get your upgrade up and running quickly.
A: try MySQL, i think there is an easy way to make the database shared along the network (i think it's in the installation process)
A: mysql... use this driver ODBC drive so that your .NET applications can connect to mysql mysql odbc driver
A: SQL Server Compact Edition supports multiple clients on the same machine. If you need to connect to the database from multiple computers, you should probably stick with Express Edition.
A: Have you considered using a Document Database rather than the typical Releationl Databases being discussed here?
One that is very friendly in the .Net space is RavendDB.
Work through this simple "Hello World" tutorial (shows some basic CRUD coding) in Visual Studio to get a feel for how it works: http://ravendb.net/tutorials/hello-world
A: LocalDB would be a good solution
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I get ExtJS 4 to work in Rails 3.1? I copied the ExtJS4 directory in the assets folder. I then included it like:
<%= stylesheet_link_tag "application", "ext-4.0.2a/resources/css/ext-all" %>
<%= javascript_include_tag "application", "ext-4.0.2a/ext-all-debug" %>
I get the following error:
Sprockets::EncodingError in Welcome#index
/Users/cbmeeks/Dropbox/Projects/myapp/app/assets/javascripts/ext-4.0.2a/locale/ext-lang-en_GB.js has a invalid UTF-8 byte sequence
Any ideas?
Is there a better way to include ExtJS in Rails 3.1?
Thanks
A: To avoid activating Sprockets and get the files straight from app's public folder, put the leading slash:
<%= stylesheet_link_tag "application", "/ext-4.0.2a/resources/css/ext-all" %>
<%= javascript_include_tag "application", "/ext-4.0.2a/ext-all-debug" %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I'm in trouble with creating new object in C++ I'm new to C++ and I'm having a trouble with it.
I've tried to create new object without (*), so Animal a1; but it didn't work.
So now I'm using Animal* a1;, and it works, but the problem is that it says it has to be initialised.
I made a default constructor, so doesn't it mean that it initialises automatically or should I initialise it again?
These are my code:
Animal.cpp:
#include "Animal.h"
using namespace std;
Animal::Animal(int newid, double newweight, int yy, int mm, int dd, double newaccDose, char newsex)
{
id = newid;
weight = newweight;
yy = yy;
mm = mm;
dd = dd;
dose = newaccDose;
sex = newsex;
}
Animal::Animal()
{
id = 0;
weight = 0;
yy = 0;
mm = 0;
dd = 0;
dose = 0;
sex = ' ';
}
Animal::~Animal(){}
double Animal::getDaysDifference(){
jdate dateOfBirth(dd,mm,yy);
jdate now;
double diff = now-dateOfBirth;
return diff;
}
void Animal::addAnimal(){
int select=0;
while(select==1 || select==2){
cout << "1. Cattle 2. Sheep" << endl;
cout << "Select a type of animal: ";
cin >> select;
cout << "Invalid number please try again" << endl;
}
}
Animal.h
#ifndef ANI_H
#define ANI_H
#include <vector>
#include "Treatment.h"
#include "jdate.h"
class Animal{
protected:
int id;
double weight;
int yy;
int mm;
int dd;
double dose;
char sex;
//Treatment treatArray[];
public:
Animal();
Animal(int newid, double newweight, int yy, int mm, int dd, double newdose, char newsex);
~Animal();
virtual double calcDose() = 0;
void addAnimal();
void questions(); // ask questions like id,weight, and so on
double getDaysDifference();
};
#endif
DrugAdmin.cpp
//Main function
#include <iostream>
#include "Animal.h"
#include "Cattle.h"
using namespace std;
int main(){
Animal* a1;
a1->addAnimal();
}
I just did it to check if the addAnimal() function is working but apparently it's not.
Can you please give me a piece of advice?
Cheers
A: When you declare
Animal* a1;
a1 doesn't point to anything: it's an uninitialised variable, which has an undefined value. Calling a method on it has undefined behaviour. If you have a default constructor, you can create a default-constructed local Animal like so:
Animal a1;
This Animal will exist till the end of the scope in which it's defined. If you need an Animal that should live beyond the end of a function, you can allocate it dynamically with new, which gives you an Animal* (pointer to Animal) that you must later delete:
Animal* make_animal() {
return new Animal();
}
int main(int argc, char** argv) {
Animal* a1 = make_animal();
delete a1;
}
You should avoid using new and delete unless it's really necessary, of course. There are loads of good answers here on StackOverflow that cover similar ground. Search for them.
A: I think:
while(select==1 || select==2){
in addAnimal() should be:
while ((select != 1) && (select !=2)) {
The way you currently have it, it will never enter the loop because select is initialised to 0, which is neither 1 nor 2. That's because it means "run this loop while the value is either 1 or 2". The latter means "run this loop while it's neither 1 nor 2".
Hence, if by some bizarre sunspot--or-thermonuclear-explosion-induced error it did enter that loop, it would stay in there until you entered an invalid value rather than a valid one.
You also want to examine the line:
cout << "Invalid number please try again" << endl;
since it will output that string even if you enter a valid value (easiest solution is probably to wrap an if around it).
A: You are not actually calling the default construct nor are you creating Animal object when you say Animal* a1 it just allocates enough space for a pointer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: web2py: cannot marshal class 'gluon.dal.Reference' objects I'm using web2py v1.98.2. with xml-rpc service. In the service.py controller I have:
@service.xmlrpc
def save_account(acct):
id = db.account.insert(code=acct['code'], name=acct['name'],
parent_id=acct['parent_id'])
acct['id'] = id
return dict(save_account=acct)
where account table is self-referencing table. This code throws "cannot marshal class 'gluon.dal.Reference' objects" error. After some test I found that it is related to id.
I thought id is integer, but documentation tells that it is an object. Then how can I convert it to integer? I want auto-incremented id back to the client.
A: Okay, this was simple. id object had _int_() method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does computer going to sleep mess up my WPF program and what to do about it I have a WPF program that communicates with a specialized USB stick that is collecting data (in fact an ANT USB dongle). I noticed that the data collection simply stopped after a few hours. The reason was evident in the windows logs (system) where at the exact time the program stopped getting data, I see:
The system is entering sleep
Sleep Reason: System Idle
Questions
*
*How do I programmatically prevent Windows from going to sleep so that I can continue to gather data?
2. Stepping backwards for the big picuture view... What's going on? Why does the computer going to sleep affect my program? Or is it just affecting the USB stick? Is it necessary to prevent sleep or should I do something else instead?
Einstein's answer is tantalizingly close. I just can't seem to get SetThreadExecutionState working in my C#/WPF program and can't find a lot of examples or discussions of it. Does it need to be called more than once? If so how? Is there a event that I receive that tell me to call it or should I call it every so often (5 minutes?) as suggested in:http://stackoverflow.com/questions/5870280/setthreadexecutionstate-is-not-working-when-called-from-windows-service
For now, I'm just going into ctrl panel -> power options and preventing sleep but it would sure be nice to have an elegant solution. Even on my own computer, I don't want to mess with the sleep settings. It's too hard to remember to set them back again!
A: You can prevent the computer from entering low power modes (sleep/suspend) by using the SetThreadExecutionState function.
As far as why going into low power mode is interrupting your data collection - well Windows suspends all processes in these modes and USB ports enter low power mode which likely means your USB device will not have power either. It's by design. After all, the whole reason we want our computers to go to sleep is so that the battery is not drained.
A: You can apply the above responses, o simply you can go in Control Panel -> Power Options and modify the settings, so your system never goes to sleep.
A: To 1): You can use SystemParametersInfo with one of the power related values on Windows versions less than Vista to turn on/off power savings settings. Starting with Vista, you should register for one of the power events instead, and the OS will notify you when it needs to for the event you request.
To 2): If the OS shuts down, the hardware it's managing shuts down. What else would you expect to happen? If the OS runs the USB device driver, which runs the USB device, what would you think would happen if the OS goes to sleep? The USB device begins running itself instead without the driver?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it more efficient to have a map of maps, or a very large map? I am storing some objects in map (hashed by strings), but the objects are categoriseable by another string.
I could therefore make a map of these categories, and for each category keep another map of the objects in that category.
I will always know the category whenever I make an insertion or a get request from this data structure.
Is this more efficient? It seems like it would be, except the lookup time of a map is log(n) I beleive, so what would the overall benefits be?
A: Just test what's faster using real data.
Statements like "lookup time of a map is log(n)" can be misleading. There's still an arbitrary asymptotic constant at play. Plus if you have data or data accesses distributed in a non uniform-random manner, as is often the case, statements about "best" get even more complicated.
When it comes to performance, few things work better than actual measurements using real data.
A: "Is this more efficient? It seems like it would be"
My gut says that in the average case it will be less efficient for two reasons.
First, you are adding more keys. You have n1 objects you need to search. You also have n2 categories the objects are divided into. You now have n1 + n2 keys instead of n1.
Second, std::map is usually implemented as a balanced binary tree. The balanced part is critical to ensure that the worst case lookup time is O(log n) rather than O(n). By moving to a two layer structure you may be preventing the tree from being balanced. If your access to objects is uniform random, an unbalanced tree will have worse performance than a balanced one.
To illustrate a perfectly balanced tree follows. Worst case 3 comparisons.
d
/ \
b f
/ \ / \
a c e g
An unbalanced tree with the same data. Worst case 4 comparisons.
b
/ \
a e
/ \
d f
/ \
c g
That said, an unbalanced tree can be faster if what you are searching for is near the top of the tree. Which is why you should listen to @nsanders when he says to profile.
A: Doing the arithmetic, if you have n elements lookup time would be O(log(n)). If you split the map into m1 maps containing maps of size m2, then you need O(log(m1)) to lookup in the first map, then O(log(m2)) to do a lookup on the second map. But since
log(m1) + log(m2) = log(m1*m2) = log(n)
You aren't buying much either way and you should probably code it whatever way best reveals your intentions.
As far as the actual performance, you should profile it and see if it makes a difference. It's possible that the two maps will be faster since each map will have a simpler comparator functions (they will each do one string comparison while the comparator for the monolithic map will have to do two for some pairs objects). Also, if in your application you are likely to be not finding a match on the first string for a lot of your lookups then you will doing just first lookup which might save some time.
On the other hand, if the sizes of the secondary maps are not uniform, then you could be effectively be doing two lookups. As a worst-case consider that half the keys have identical first strings, and the other keys all have district strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CSS styling for multiple divs and a media player I'm trying to style the following page:
http://www.davedaranjo.com/media.html
The problem I'm having is that I really need to center div left and div right on the page with the header. Can someone suggest an style or attribute that would just move the whole section under the header over to the middle of the page?
Thank you!
A: Couple of points.
*
*You shouldn't use tables for layouts.
*The music player is not part of your div#right, the JavaScript inserts it after your <div align="center">.
But, if you want to stick with the site as it is, the following will center all of the components for you:
<body style="width: 1024px; margin: 0 auto;">
Note, the CSS should be stored in a file external to your HTML. If you use a separate file add the following to it:
body { width: 1024px; margin: 0 auto; }
A: One thing you can do is make it so that the div under the body that's aligned to center also contains the div with the class ttw-music-player.
Side note: I'm not sure if you know this, but the ttw-music-player div is the actual content on the right. The div that has the id of 'right' doesn't have anything in it, since the javascript in there doesn't actually put anything on the page.
Once you do that, you can set the centering div so it has a specific width and also set it to margin: auto; instead of align: center;. This will wrangle the header and the left and right content divs into the container. After that, specify fixed widths on the left and right divs so that they take up an equal amount of space that adds up to exactly the width of the container div. Then float one left and the other right. You may need to play with the width, padding, and/or margin to get everything pixel-perfect.
Also, I'd suggest not using tables for anything except actual tables of data, and use CSS files in the <head> for all your styling. Generally, you should stay away from inline styles that occur inside the html file itself, and just use JavaScript to add or remove CSS classes on elements, triggering inline styles from your JavaScript only if absolutely necessary. It's much easier to maintain this way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Running plink in winpexpect I'm trying to use plink in winpexpect to connect to a remote Linux server. I'm using the following code:
child = winpexpect.winspawn('plink root@hostname')
child.logfile = sys.stdout
i = child.expect(['Password:')
child.expect('Password:')
child.sendline('password')
The output I get on stdout is:
Using keyboard-interactive authentication.
Password: password
Using keyboard-interactive authentication.
Password:
Using keyboard-interactive authentication.
Password: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...in expect_loop
raise TIMEOUT (str(e) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
...
command: plink
args: ['plink', 'root@hostname']
buffer (last 100 chars): yboard-interactive authentication.
Password:
Using keyboard-interactive authentication.
Password:
before (last 100 chars): yboard-interactive authentication.
Password:
Using keyboard-interactive authentication.
Password:
after: <class 'pexpect.TIMEOUT'>
...
The equivalent code works in pexpect under Linux (replacing the winpexpect module with pexpect, and the plink call with ssh), so I know that the expect() matching is correct. It looks like winpexpect is writing to the screen, and plink is not registering that as being text entered into the password field.
Can anyone spot the problem here?
A: Here is a forked winexpect project with bug fix: https://bitbucket.org/weyou/winpexpect
You can try it.
A: I ran in to a similar issue with winpexpect and plink. This question had a solution that worked for me. The device attached to my serial interface was echoing things locally and confusing winpexpect. Replacing the sendline() with a function that does:
child.send(cmd)
child.pexpect(cmd)
child.send('\n')
for each call fixed it for me. the child.pexpect(cmd) eats the locally echoed characters before the target seed the \n and starts responding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SQL SELECT rows with numbers on column? Possible Duplicate: How to only select numeric data from mysql?
I have a column which actually houses strings (type varchar) is there a way to select rows that only hold numbers in them?
E.G:
COLUMN1 COLUMN2 COLUMN3
1234 dassa dasasfa
aaaa fdsa dsfa
4dsf4 dfssa aaddss
The query should return
1234 dassa dasasfa
A: SELECT * FROM `table` WHERE `COLUMN1` REGEXP '^[[:digit:]]+$'
See http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
A: Use regular expression matching with REGEXP()
SELECT COLUMN1, COLUMN2, COLUMN3
FROM tbl
WHERE COLUMN1 REGEXP '^[0-9]+$';
A: where column1 regexp '^[[:digit:]]+$'
I think should do it.
Another idea:
where case(round(column,0) as char) = column1
A: You can do it by this query in mysql
select * from st where COLUMN1 REGEXP '^[0-9]+$';
the result will be
COLUMN1 COLUMN2 COLUMN3
1234 dassa dasasfa
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL - Date Between (xxxx-06-21 and xxxx-09-21) How is it possible to use the BETWEEN function in MySQL, to search for dates in any year but between a specific day/month to a specific day/month? Or if it's not possible using BETWEEN, how else could I accomplish it?
To be more descriptive, I am trying to add a seasonal search to my photo archive website. So if a user chose to search for "summer" photos, it would search photos taken between 21 June and 21 September, but from any year.
If Carlsberg made SQL, I think it would be :)
WHERE date BETWEEN 'xxxx-06-21' AND 'xxxx-09-21'
Many thanks
A: I'd think the easy way is to take the dates, turn them into strings, take the postfix, and run it through the BETWEEN:
WHERE date.MONTH() || date.DAY() BETWEEN '0621' AND '0921'
A: The solution given elsewhere, WHERE date.MONTH() || date.DAY() BETWEEN '0621' AND '0921', is a good one (and it's well worth upvoting since it's fine for most MySQL databases) but I'd like to point out that it (and most queries that involve per-row functions) won't scale that well to large tables.
Granted, my experience is that MySQL is not used that often for the sizes where it would make a huge difference but, in case it is, you should also consider the following.
A trick we've used in the past is to combine extra columns with insert/update triggers so that the cost of calculation is only incurred when necessary (when the data changes), rather than on every select.
Since the vast majority of databases are read far more often than written, this amortises that cost over all selects.
For example, add a new column CHAR(4) called MMDD and whack an index on it. Then set up insert/update triggers on the table so that the date column is used to set this new one, based on the formula already provided, date.MONTH() || date.DAY().
Then, when doing your query, skip the per-row functions and instead use:
WHERE MMDD BETWEEN '0621' AND '0921'
The fact that it's indexed will keep the speed blindingly fast, at the small cost of a trigger during insert/update and an extra column.
The cost of the trigger is irrelevant since it's less than the cost of doing it for every select operation. The extra storage required for a column is a downside but, if you examine all the questions people ask about databases, the ratio of speed problems to storage problems is rather high :-)
And, though this technically "breaks" 3NF in that you duplicate data, it's a time honoured tradition to do so for performance reasons, if you know what you're doing (ie, the triggers mitigate the "damage").
A: the RIGHT function may help
select
current_date,
right(current_date,5),
right(current_date,5) between '06-21' and '09-21' `IsTodaySummer?`,
'09-21' between '06-21' and '09-21' `Is 09-21 Summer?`;
+--------------+-----------------------+-----------------+-------------------+
| current_date | right(current_date,5) | IsTodaySummer? | Is 09-21 Summer? |
+--------------+-----------------------+-----------------+-------------------+
| 2011-09-29 | 09-29 | 0 | 1 |
+--------------+-----------------------+-----------------+-------------------+
but as ajeal said, add another column is better to use index.
A: If you really need to have this format of search,
I guess is better to break the date column into two,
*
*year int(4) unsigned (which is the year)
*month_day int(4) unsigned (which is mmdd)
build a composite index on month_day, year,
the idea is make index work better
example query like
where month_day between 621 and 921 -- make use on index
another example
where year=2011 and month_day between 900 and 930 -- make use on index too
A: There should be an equivalent of Oracle's to_date() function in MySQL.
A: You could pull the dates apart with the month and day functions:
where month(date_column) between 6 and 9
and if(month(date_column) = 6 and day(date_column) < 21, 0, 1)
and if(month(date_column) = 9 and day(date_column) > 21, 0, 1)
The if stuff is only needed because your boundaries don't line up nicely with the months.
If you're going to be doing a lot of this sort of thing then you might be better off precomputed the month-day version of the full date so that you can index it.
A: Since you don't need the year, subtract it from the date.
In MySQL, you can do something like this:
select * from some_table
where date_sub(date_col, interval year(date_col) year)
between '0000-06-21' and '0000-09-21';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to publish code to local phusion passenger install from development folder? On my local dev machine I am coding on (ubuntu), I am using the built in rails server (webrick):
rails s
I want to sometimes test things out on a local copy of phusion passenger that I am going to install.
How can I automate pushing the files to my phusion passenger server?
Would a simple script that copies the contents of the folder suffice?
Is it easier to setup capistrano?
A: Copying the folder would suffice (assuming all of your environment details are the same).
Personally I would just clone my git repository (not sure if you are using source control) into the appropriate folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Designing a secure auto login cookie system in PHP I want to have an auto login option check for a user. Basically that means a cookie will be stored on the client side.
Now the question is, how do I make it secure so the cookie will can not be spoofed/modified.
One of my friends suggest having a db table that stores the session_id, user's ip, browser info, etc and then compare it all that information once a user goes to the website again.
I feel like having a separate table for that is a bit too much trouble. Is there another way to do it? Maybe with tokens or something like that?
A: For most auto-logins I know, there is a separate table to store logged-in sessions. Each auto-login session is assigned a hashed key as an identifier, the key is considerably long and virtually not possible to spoof. If you don't want users to be logged in cross-ip even with a valid code, try this.
function gen_uniqueIdent($length=32){
$alphabet = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789');
$key = '';
for($loop=0;$loop<$length;$loop++){
$i = mt_rand(0,count($alphabet)-1);
$key.= $alphabet[$i];
}
return $key;
}
Assign this value to the user cookie upon login. Then store this into the db:
function save_ident($identFromFunctionAbove,$authenticated_user_id){
//hash this with something unique to the user's machine
$hashed = md5($identFromFunctionAbove . $_SERVER['REMOTE_ADDR']);
/** Some actions to remember this hash **/
}
save that into a database correspinding with a user identity like user_id.
Now upon validation of the user cookie, you can simply:
function validateCookie(){
$ident = $_COOKIE['yourCookieName'];
$hashed = md5($ident . $_SERVER['REMOTE_ADDR']);
/** Check if this hashed value exists in db, if it does, authenticate user **/
}
You'll also need to remove the sessions after they expire or the user explicitly logs out.
Of course this is very simple, and doesn't account for md5 or ident collisions. Still, getting two 32-character random generated string to be the same as one previously generated is pretty slim a chance.
A: The more secure you want this infamous cookie, the more trouble it's going to be for you. If your users should be particularly secure, you will have to go with the most troublesome approach.
You should only accept this cookie with https if you want to be as secure as possible. If the cookie is accepted over http, it can be sniffed and stolen.
I would recommend that the cookie have no user data at all (a token, as you suggested). This will, unfortunately, require another table. When a user logs in and chooses "keep login," create an entry in this table. The entry can be any meaningless value (such as md5(uniqid('', true));. This token can be unique in the DB and mapped to a user's ID.
When a user visits your website, you can check the value of that cookie and get the user it belongs to and log them in. At this point, you destroy the old token and create a new one. "Destroy" can mean many things. You can delete it from the DB entirely or have a flag that disables the token. You may want to allow the same token to be used multiple times in case the cookie is received but the authentication doesn't go through for some reason, but I think this is insecure. You may also want to store the timestamp of the token and only accept it if it's been some limited period of time (30 days for example).
As your friend points out, you can store other information such as user agent, IP address, etc., but these may change even with the same browser being used (especially with mobile) and if a user's persistent login is not accepted because of this, it could be jarring and inconvenient to them.
If you really don't want to create another table, then you will have to store some way to acquire the user's ID from the cookie value. This is less secure.
A: The way I have previously done this is storing the MD5 hash of the password not the actual password.
On the server side you need to check if the login is coming from a cookie and then check if the hash is the same as the password in your database after its been hashed through MD5
That way if someone hacks the users computer they can never know the value of the password however the can still use that cookie to authenticate to only your server.
You can make this more secure by making the cookie expire after x days so if the cookie is stolen the theif can only get access for that period.
At the end of the day the most and only? secure method is make the user login each time
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Javascript regex urls that are not image extensions I've got the following JavaScript which matches and replaces URLS with html links, however I need this to exclude urls which end in .png|.jpg|.jpeg|.gif
text = text.replace(
/(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim,
'<a href="$1" class="autolink" target="_blank">$1</a>'
);
A: You could just to a test before:
if (!text.match(/\.(png|jpg|jpeg|gif)$/) {
text = text.replace(
/(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim,
'<a href="$1" class="autolink" target="_blank">$1</a>'
);
}
If you need to do multiple replacements, then you could use a custom replace function that checks the match against the image endings and acts accordingly. That would work like this:
var imageRegex = /\.(png|jpg|jpeg|gif)$/;
text = text.replace(/(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim,
function(str) {
if (str.match(imageRegex)) {
return(str);
} else {
return('<a href="' + str + '" class="autolink" target="_blank">' + str + '</a>');
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Satchmo: Specify delivery date/shipping date for an order I working on e-commerce website using Satchmo. However, there are few customization required for my store.
*
*While ordering a product I should be able to specify a delivery date (shipping date).
*There can be only 20 (max_num_delievries) deliveries possible per day for a product. If number of deliveries for a particular date for a particular product exceeds 'max_num_delievries', user should not be able to select that date while ordering the product.
Can someone please help in this and guide me how to achieve this using Satchmo?
Thanks in advance..
A: I would try something like this:
1) create a local app (eg. delivery_date) with a model like "DeliveryDate" or so. For example localsite/delivery_date/models.py:
class DeliveryDate(models.Model):
product = models.ForeignKey(Product)
date = models.DateField()
order = models.ManyToManyField(Order)
class Meta:
unique_together = ("product", "date")
2) the validation of the max 20 existing orders... mhh, good question, maybe the best would be, to do it on the form? Override the clean method and check if this delivery date is associated with 20 orders already... maybe something like localsite/delivery_date/forms.py
class DeliveryDateForm(forms.ModelForm):
class Meta:
model = DeliveryDate
def clean(self):
super(DeliveryDateForm, self).clean()
... check here the order_set count
... but maybe the form isn't the best place to do this.
You also probably want to hide and auto-set the initial values for product and order yourself, and the user only being supposed to select a date.
3) Regarding satchmo... I would use signals to react after a product has been added to the cart (there is a signal just for this case), and add a listener which redirects the user to a view where he can select the date for this product. Look at the example here with the signal "cart_add_view": http://www.facebook.com/note.php?note_id=101466134049
Maybe ajax would be a good option here. With a hidden container in your page... which shows up after adding a product to the cart (only if the product hasn't already a DeliveryDate associated to this order/product), and asking the user to select a date.
This whole stuff would be on the listener: check if the product needs a delivery date, and if yes, send an ajax response to pop-up the window, and put in the repsonse-context the form, with the initial product and order hidden fields.
And to save the delivery-date you will need another ajax-view.
Well it's merely an idea how I would try to do it ;-) It will probably need adjustments here and there, of course. But hopefully it helps you further.
Regards,
Andrea
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $this->class->function(): how does it work? I've been programming in PHP for several years and I've only just recently begun to look at object oriented code. Now I understand classes and such:
class Myclass {
public function __construct() {
}
}
and all that good stuff... I also understand creating functions and calling in my index.php:
$someVar = new Myclass;
One thing I've been trying to understand, being that i've recently looked at codeigniter and I like one thing about it and want to try and accomplish the same thing without actually using codeigniter.
in code igniter they have the variable $this appear to be their class variable. But by using that, you're able to call from multiple classes all at once.. such as:
$this->load->module(); which is in one class file..
$this->db->query(); which is in another class file.
I've searched google for the last few days trying to figure out how to do this same thing where each class would have the correlation between them all allowing me to run $this->class_name->function_name in my projects instead of creating a new variable for each class or for the sake of a clean index file, having every function in a single class file.
Any information (aside from buy this book - as that isn't an option for me) is greatly appreciated and I will thank you now (and will probably thank you again later just for good measure).
A: The load and db references are class properties which are themselves other objects with public module() and query() methods respectively. For example
class MyClass
{
/**
* @var CI_DB
*/
private $db;
/**
* @var Loader
*/
private $load;
public function __construct(CI_DB $db, Loader $load)
{
$this->db = $db;
$this->load = $load;
// PHP also allows you to add arbitrary object properties
// that receive a "public" visibility
// Please note, this is not a good practice
$this->foo = new Foo;
}
public function someMethod()
{
$this->load->module();
$this->db->query();
// You can also use foo even though it is not defined
// in the class properties
$this->foo->something();
}
}
See http://www.php.net/manual/en/language.oop5.properties.php
Adding the foo property like we did is dangerous. Because it receives the public visibility, it may be altered externally to the class.
$class = new MyClass($db, $load);
$class->foo = new Bar;
$class->someMethod(); // will break if Bar does not contain a something() method
A: I've been reading you and Phil's comments. First off, you can't use $this on index.php. $this can only be used in the context of an object. So you could do,
$someVar = new Myclass;
...
$someVar->db->something();
...instead.
I'm not entirely sure what you mean by "read classes," but you can assign members to MyClass exactly as Phil indicates:
class MyClass {
private $inj;
function __construct(Injected $inj) {
$this->injected = $inj;
}
}
Note that the private $inj declaration is not mandatory, but skipping it is dangerous. Any non-declared members added are automatically public, and this can potentially screw with you if you rely on magical get. I would declare the properties you need.
Finally, you either need to include all class definitions you will use, use a function like load_class(), or use autoloading. If Injected above is not a declared class, you will get an error when trying to create one. load_class() almost certainly includes the class definition somehow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making Twitter, Tastypie, Django, XAuth and iOS work to Build Django-based Access Permissions I will build an iOS application whose functionality will be based on access permissions provided by a Django REST application.
Django manages the permissions for the activities in the iOS app. User A can do Work A if he/she is permitted. Permissions will be queried via ASIHTTPRequest to a REST API served by Django Tastypie.
There is no registration. Users will just be able to login via Twitter. XAuth will be used to present a login screen for users.
There are 2 types of users. For example purposes, there will be Type 1 and Type 2. Type 1 will be ordinary user who can only browse data in the iOS app.
Type 2 user can submit/edit data.
That's it theoretically. However...I don't know where to start!!
The biggest roadblock:
How can I hook Twitter XAuth with Django's user backend via Tastypie?
If I know this then I can query the necessary permissions.
Thanks in advance!
A: I've done something similar with django + tastypie and facebook login for iOS.
Authentication
*
*Log the user in using whatever means you will, get the access_token.
*Create a GET request tastypie endpoint to which you will pass the accesstoken as a query string.
*On the server side validate etc... and then create your own internal "tastypie" token and return that in the response to the get request e.g:
class GetToken(ModelResource):
"""
Authenticates the user via facebook and returns an APIToken for them.
"""
class Meta(object):
queryset = ApiKey.objects.all()
resource_name = 'authenticate'
fields = ['user', 'key']
allowed_methods = ['get']
authorization = Authorization()
authentication = FacebookAuthentication()
def prepend_urls(self):
"""We override this to change default behavior
for the API when using GET to actually "create" a resource,
in this case a new session/token."""
return [
url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()),
self.wrap_view('_create_token'), name="api_get_token"),
]
def _create_token(self, request, **kwargs):
"""Validate using FacebookAuthentication, and create Api Token if authenticated"""
self.method_check(request, allowed=['get'])
# This checks that the user is authenticated on facebook and also creates the user
# if they have not been created.
self.is_authenticated(request)
self.throttle_check(request)
bundle = self.build_bundle(obj=None, request=request)
bundle = self.obj_create(bundle, request, **kwargs)
bundle = self.full_dehydrate(bundle)
self.log_throttled_access(request)
return self.create_response(request, bundle.data)
def obj_create(self, bundle, request=None, **kwargs):
"""Create a new token for the session"""
bundle.obj, created = ApiKey.objects.get_or_create(user=request.user)
return bundle
*
*Pass the returned API key on all subsequent calls, can either be as a query string param again or I set it on the Authorisation header for every call.
*Make sure ALL the other resources you want to have authentication on have ApiKeyAuthentication() set in the Meta.
class ThingResource(ModelResource):
class Meta:
queryset = Thing.objects.all()
resource_name = 'thing'
authentication = ApiKeyAuthentication()
Authorisation
So now you know on the server side that the user is who they say they are, what is this user allowed to do? Thats what the authorisation meta is all about.
You probably want Django Authorisation in which case you can just use the normal permissioning schemes for users, or you could roll your own. It's pretty simple.
A: amrox has a nice example on how to hook a custom fork of django-oauth-plus that supports xAuth into tastypie. I imagine it can be tweaked to suit your purposes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Returned hashmap values are null I am restricting myself to just to the part of the question where I am going wrong. I have an array of double values; I put all the values of the array which are non zero into the hash map but when I am trying to display the values in my hashmap I get null values.
Help needed.I have not been able to figure out if this has got something to with Java Collections.
The Map is created outside the for loop.
for(int i=0;i<aray.length;i++) {
if(aray[i]!=0) {
//non zero array values get divided by some random number not too big number.
aray[i]=aray[i]/somenumber;
hashmap.put(i,aray[i]);
System.out.println(hashmap.get(i));
//if I display aray[i] its a non zero number but hashmap.get(i) is returning null values.
}
}
A: Works for me.
Program
class Test
{
public static void main(String ... args)
{
final Integer somenumber = 2;
final Integer[] aray = {5, 4, 3, 2, 1, 0, -1, -2, 42,};
final java.util.HashMap<Integer, Integer> hashmap = new java.util.HashMap<Integer, Integer>();
for(Integer i=0;i<aray.length;i++) {
if(aray[i]!=0) {
//non zero array values get divided by some random number not too big number.
aray[i]=aray[i]/somenumber;
hashmap.put(i,aray[i]);
System.out.println(hashmap.get(i));
//if I display aray[i] its a non zero number but hashmap.get(i) is returning null values.
}
}
}
}
Output
user@host:/tmp$ javac -version
javac 1.6.0_20
user@host:/tmp$ javac Test.java
user@host:/tmp$ java Test
2
2
1
1
0
0
-1
21
No null values anywhere, as expected. I don't see any way the map would be returning nulls, since you've just added the value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.