text stringlengths 8 267k | meta dict |
|---|---|
Q: Validate account number SQL table I'd like to select data from a table with the following rule, but I'm having trouble writing the query. I'm using PostgreSQL and I can't create a UDF. The table looks like this:
id | user_id | account_number
-------------------------------
1 | 1 | 12345671
2 | 4 | 12356673
3 | 7 | 12325678
The id and user_id are integers whereas the account number is a string. I'd like to select the account numbers that match the following conditions:
*
*Account number string contains exactly 8 digits
*Validation scheme
*
*Take the first 7 digits
*Multiply the first digit by 1, the second by 2, the third by 3, the fourth by 1, the fifth by 2, the sixth by 3 and the seventh by 1
*Sum the result of multiplying each digit by the relevant number
*If the 8th digit is the same as mod(sum, 10) then select this number
In this table above, I should only return the first two rows with the query.
Just to repeat, I can't create a UDF, so am looking to find out whether this is possible using ordinary SQL in a query.
Thanks!
A: Yes, you can do it. Basically, use SIMILAR TO to check for exactly 8 digits, then substring and cast to do the math. Something like this:
SELECT * FROM table_name WHERE
account_number SIMILAR TO '[0-9]{8}'
AND (
1 * CAST(SUBSTR(account_number, 1, 1) AS INTEGER) +
2 * CAST(SUBSTR(account_number, 2, 1) AS INTEGER) +
3 * CAST(SUBSTR(account_number, 3, 1) AS INTEGER) +
1 * CAST(SUBSTR(account_number, 4, 1) AS INTEGER) +
2 * CAST(SUBSTR(account_number, 5, 1) AS INTEGER) +
3 * CAST(SUBSTR(account_number, 6, 1) AS INTEGER) +
1 * CAST(SUBSTR(account_number, 7, 1) AS INTEGER)
)%10 = CAST(SUBSTR(account_number, 8, 1) AS INTEGER)
Of course, this returns no rows in your example, because:
1×1 + 2×2 + 3x3 + 1×4 + 2×5 + 3×6 + 1×7 = 53
53 MOD 10 = 3
3 ≠ 1
PS: You do realize the UDFs can be written in languages other than C. E.g., you can write one in PL/pgSQL.
A: Just create a table where you split out your digits, then do the arithmetic (of course, you can fill in the rest of the stuff where the ...s are).
create table digits as
select account_number,
substr(account_number::text,0,1)::int as digit_1
,substr(account_number::text,1,1)::int as digit_2
,...
substr(account_number::text,7,1) as digit_8
from table
where account_number::text~E'[0-9]{8}'; --regex to make sure acct numbers are of the right form.
select account_number,
(digit_1+2*digit_2+...+3*digit_6+dight_7)%10=digit_8 as valid
from digits;
Of course, if you'd rather not create a separate table, you can always put the select statement for the creation of the digits table into a subquery for the second query.
A: select id,
user_id,
digit_sum,
last_digit
from (
select id,
user_id,
(substring(account_number,1,1)::int +
substring(account_number,2,1)::int * 2 +
substring(account_number,3,1)::int * 3 +
substring(account_number,4,1)::int +
substring(account_number,5,1)::int * 2 +
substring(account_number,6,1)::int * 3 +
substring(account_number,7,1)::int ) as digit_sum,
substring(account_number,8,1)::int as last_digit
from accounts
) t
where last_digit = digit_sum % 10
To make life easier, I would create a view that does the splitting and summing of the values. Then you just need to select from that view with the where condition I used for the derived table.
A: You can try something along these lines.
select *, (
(substring(account_number from 1 for 1)::integer * 1) +
(substring(account_number from 2 for 1)::integer * 2) +
(substring(account_number from 3 for 1)::integer * 3) +
(substring(account_number from 4 for 1)::integer * 1) +
(substring(account_number from 5 for 1)::integer * 2) +
(substring(account_number from 6 for 1)::integer * 3) +
(substring(account_number from 7 for 1)::integer * 1)
) as sums,
(
(substring(account_number from 1 for 1)::integer * 1) +
(substring(account_number from 2 for 1)::integer * 2) +
(substring(account_number from 3 for 1)::integer * 3) +
(substring(account_number from 4 for 1)::integer * 1) +
(substring(account_number from 5 for 1)::integer * 2) +
(substring(account_number from 6 for 1)::integer * 3) +
(substring(account_number from 7 for 1)::integer * 1)
) % 10 as mod_10
from acct_no
where length(account_number) = 8
I wrote the calculation into the SELECT clause instead of the WHERE clause, because either my arithmetic is wrong or your specs are wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Groovy way of finding largest matching list member based on members property Is there a better way to find closest object with lesser marker?
class Prop implements Comparable {
BigDecimal marker
String value
int compareTo(other) {
return marker <=> other.marker
}
}
def props = [new Prop(marker: 0G, value: "1st"),
new Prop(marker: 20G, value: "2nd"),
new Prop(marker: 30G, value: "3rd"),
new Prop(marker: 40G, value: "4th"),
new Prop(marker: 50G, value: "5th"),
new Prop(marker: 100G, value: "6th"),
new Prop(marker: 1000G, value: "7th")]
def whereAmI = 44G
def here = props.findAll{it.marker <= whereAmI}.max()
A: Edit: Updated to return the correct object type, and nulls.
Assuming that order isn't guaranteed, you could use the inject method:
// Inject null, so if nothing is lower than max, this returns null
def here = props.inject(null){ max, it ->
(it.marker <= whereAmI && (!max || it > max)) ? it : max
}
If the list is always sorted, then simply use this:
// Inject null, so if nothing is lower than max, this returns null
def here = props.inject(null){ max, it ->
(it.marker <= whereAmI) ? it : max
}
The benefit here is you only loop over the set once, and you don't create an additional interim List of lesser values.
Now, depending on your list size, the argument may be that your original example is a lot easier to read, and a lot clearer. Clarity in code can trump performance.
(Note: inject is Groovy's version of reduce or fold.)
A: Here's an alternative to OverZealous's inject solution that works if the props list is sorted by marker. Create a takeWhile method on Lists, and then take the last one less than whereAmI:
List.metaClass.takeWhile = { closure ->
def iter = delegate.iterator()
int i = 0
def n = iter.next()
while(closure.call(n)) {
i++
if (iter.hasNext())
n = iter.next()
else
break
}
return delegate[0..<i]
}
props.takeWhile { it.marker < whereAmI }[-1] // exception if nothing matches
props.takeWhile { it.marker < whereAmI }.reverse()[0] // null if nothing matches
A: What a better way to do it is will depend on what you consider as better.
For code readability, I think the solution you originally proposed is very good.
The OverZealous solution migth be faster but, as he mentioned, it's not as readable. And in fact, if performance really matters for that code, you should profile it to see if it's really faster.
If the props list is created once (or few times) but the here value is calculated many times, you migth consider sorting props and looking for whereAmI with a binary search. This will take log(n) time (n the size of props) instead of linear time.
// Make whereAmI a Prop to avoid defining a Comparator
def whereAmI = new Prop(marker: 44G, value: '')
def i = Collections.binarySearch(props, whereAmI)
def here = props[i >= 0 ? i : -i - 2]
When whereAmI is not in props, bynarySearch returns the negative of one plus the index where whereAmI should be, hence the seemingly magical -1 -2 there.
Warning: this won't work if there is no element in props that is less than whereAmI. if that is a possibile case, you should ask for a i == -1. The original code assigned null to here in that case:
def here = i == -1 ? null : props[i >= 0 ? i : -i - 2]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How in SQL Server Management Studio 2008 to rollback easily? I'm used to setting Oracle's tools to not auto-commit, run statements, then click a 'rollback' button if I'm not happy with the result. I'm hoping I'm overlooking something in Microsoft's tool...
A: As far as I remember, you can do it by SET IMPLICIT_TRANSACTIONS ON (also with SET ANSI_DEFAULTS ON for connection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any way to access GAE dev app server in the local network? If I access my web site via http://localhost:8080 from the same Win 7 PC, where server is running, then it works well.
If I try to access that from another PC (with usage of my internal PC's ip http://192.168.1.98:8080), then it doesn't work. Moreover, it is not accessible with this ip even on the same machine. What am I doing wrong?
(I've tried to disable firewall on my Win 7 PC - it didn't help)
A: First check whether your server listens on loopback or on all interfaces - in command line type in netstat -an find a line with port 8080 and state LISTENING, something like this:
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING
If IP is 0.0.0.0 it means it listens on all IP addresses and the problem is with something else blocking it.
If IP is 127.0.0.1 then you need to bind to 0.0.0.0 address. And now the fun beings - according to documentation, you should add --address=0.0.0.0 or --host=0.0.0.0 to arguments in run configuration (depends on GAE version - thank you @momijigari). But in my case I have also GWT and parameters go to GWT and it does not accept this argument. But on the other hand listens on all interfaces, which I personally was trying to change to localhost. The GWT has -bindAddress parameter though, but it sets only address for code server (one with 9997 port by default), not HTTP.
A: I got it working using the suggestions above for --host=0.0.0.0.
Here are the steps.
*
*While on the project go to Edit > Application Settings
*Add to Extra Command Line Flags
A: If you are running devserver through maven add
<address>0.0.0.0</address>
under your
<configuration>
section in your appengine-maven-plugin.
A: For Google App Engine 1.8.9 (Java only), adding -a 0.0.0.0 for all interfaces, worked for me.
-a 0.0.0.0 --port=8888 "/home/dude/workspace-java/me.dude.thermo-AppEngine/war"
A: Command line
Pass this program argument:
--address=0.0.0.0
Eclipse
Start your dev server with this extra program argument (you can find this under “debug configurations” in eclipse):
--address=0.0.0.0
Gradle
If you’re using appengine-gradle-plugin +2.0.0, then you need to set it like this:
appengine {
host = "0.0.0.0"
port = 8888
...
If you're using appengine gradle plugin before version 2.0.0, then you need to set it like this:
appengine {
httpAddress = "0.0.0.0"
httpPort = 8888
...
Maven
<configuration>
<address>0.0.0.0</address>
...
A: In Gradle build file:
appengine {
httpAddress = "0.0.0.0"
}
(Gradle App Engine plugin)
A: Little update. Since version 1.8.7 you have to set a param "--host" instead of "--address"
So just add --host=0.0.0.0
A: Eclipse users can do the following in the GUI to implement the Command-Line Arguments:
Right click on project name -> Debug As (or Run As) -> Configurations... -> Arguments
In the Program arguments area replace
--port=8888
with
--port=8888 --host=0.0.0.0
or
--port=8888 --address=0.0.0.0
depending on the AppEngine SDK version, then also check port availability and software firewall settings.
A: I'm using Eclipse.
I've tryied to add --address=0.0.0.0, but it didn't work for me.
Then I've removed --port=8888 entity from the command line arguments => server runs on default port 8080 and only then team members could connect to my machine via my IP address.
Finally, try to remove port entity and add --address=0.0.0.0 entity as it was described in early posts
A: Step 1: Get the LAN IP
Goto your Windows Command Console (Press Win+R, then type "cmd"). In the console, enter "ipconfig". You will see a list of display. Under Wireless LAN adapter Wi-Fi, get the IPv4 Address. It will be something 192.168.x.x
LAN IP : 192.168.x.x
Step 2:
Go to Eclipse, Open the Configured server
Under Properties of GAE Development Server -> Local Interface address to bind to, enter the LAN IP address, and save.
Step 3:
Now you can access the GAE server by
http://192.168.x.x:8888/
8888 - Refers to the Port Number, as mentioned in the GAE development server
A: -bindAddress 0.0.0.0
is what i needed. I added it just before the -port arg. This was via Eclipse
A: To access the GAE development server(Local Sever) withing LAN from any machine(PC/Mobile), you need to configure the app engine to accept request from any ip as follows;
Run Configuration -> Arguments -> Program Arguments
--address=0.0.0.0 port=8181
Note: You can use any available port.
Once this done, you can just access this local server by entering the PC's IP address and above configured port;
http://192.168.1.102:8181/
A: If using GWT, add this program arguments
-bindAddress 0.0.0.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
} |
Q: changing number format with php I have numbers like these...
1.235,45
100,00
5,5678
25.321,10
But I need those numbers in the following format:
1235.45
100
5.5678
25321.1
A: $number = str_replace('.', '', $number);
$number = str_replace(',', '.', $number);
$number = (float)$number;
Should do the trick.
A: function cnv($str) {
$str = str_replace(".", "", $str);
$str = str_replace(",", ".", $str);
return (float) $str;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sort a PHP array by another array order and date Was wondering if there is a way to sort (usort or equiv) an array based on key order of another array and date. I know how to do basic date sorting with usort, but was wondering if you could do both in one shot.
$cats = array(1,6,3,4,7,2);
$prods = array(
array('cat'=>1,'date'=>'1/3/2011'),
array('cat'=>2,'date'=>'1/6/2011'),
array('cat'=>3,'date'=>'2/3/2011')
);
I want $prods sorted by the category order of $cats and date order of $prods
A: Pay attention to your low accept rate, as it can deter people from taking the time to answer your questions. Remember to mark valid answers as accepted or otherwise post a comment to them explaining why they aren't valid.
This solution works fine in php 5.3+, if you are trapped in an older version you can easily replace DateTime objects with calls to strptime.
Products with a category that has no position specified are pushed to the end of the list (see product with cat == 42 in the example).
$cats = array(1,6,3,4,7,2);
// added a few products to test the date sorting
$prods = array(
array('cat'=>1,'date'=>'3/3/2011'),
array('cat'=>1,'date'=>'2/3/2011'),
array('cat'=>1,'date'=>'1/3/2011'),
array('cat'=>42,'date'=>'2/3/2011'),
array('cat'=>2,'date'=>'1/3/2011'),
array('cat'=>2,'date'=>'2/3/2011'),
array('cat'=>2,'date'=>'1/6/2011'),
array('cat'=>3,'date'=>'2/3/2011')
);
// need an index of category_id => position wanted in the sort
$r_cats = array_flip($cats);
// if the category of a product is not found in the requested sort, we will use 0, and product with category id 0 will be sent to the end of the sort
$r_cats[0] = count($r_cats);
// this one is needed for DateTime, put whatever your timezone is (not important for the use we do of it, but required to avoid a warning)
date_default_timezone_set('Europe/Paris');
usort($prods, function($a, $b) use($r_cats) {
$cat_a = isset($r_cats[$a['cat']]) ? $r_cats[$a['cat']] : $r_cats[0];
$cat_b = isset($r_cats[$b['cat']]) ? $r_cats[$b['cat']] : $r_cats[0];
if ($cat_a < $cat_b) {
return -1;
} elseif ($cat_a > $cat_b) {
return 1;
}
$date_a = DateTime::createFromFormat('j/n/Y', $a['date']);
$date_b = DateTime::createFromFormat('j/n/Y', $b['date']);
if ($date_a < $date_b) {
return -1;
} elseif ($date_a > $date_b) {
return 1;
}
return 0;
});
var_dump($prods);
The results are as follow:
array(8) {
[0]=>
array(2) {
["cat"]=>
int(1)
["date"]=>
string(8) "1/3/2011"
}
[1]=>
array(2) {
["cat"]=>
int(1)
["date"]=>
string(8) "2/3/2011"
}
[2]=>
array(2) {
["cat"]=>
int(1)
["date"]=>
string(8) "3/3/2011"
}
[3]=>
array(2) {
["cat"]=>
int(3)
["date"]=>
string(8) "2/3/2011"
}
[4]=>
array(2) {
["cat"]=>
int(2)
["date"]=>
string(8) "1/3/2011"
}
[5]=>
array(2) {
["cat"]=>
int(2)
["date"]=>
string(8) "2/3/2011"
}
[6]=>
array(2) {
["cat"]=>
int(2)
["date"]=>
string(8) "1/6/2011"
}
[7]=>
array(2) {
["cat"]=>
int(42)
["date"]=>
string(8) "2/3/2011"
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: django urls optimization urls with 2 request params:
/prefix1/1/
/prefix2/2/
/prefix1/1/prefix2/2
/prefix2/2/prefix1/1
url( ur'^prefix1/(?P<p1>\d+)/$', 'app.views.view' ),
url( ur'^prefix2/(?P<p2>\d+)/$', 'app.views.view' ),
url( ur'^prefix1/(?P<p1>\d+)/prefix2/(?P<p2>\d+)/$', 'app.views.view' ),
url( ur'^prefix2/(?P<p2>\d+)/prefix1/(?P<p1>\d+)/$', 'app.views.view' ),
Is possible to do this more 'DRY' (with 3 request params, lines in urls.py = 15) ?
A: I hacked together a sample and, if lazerscience's comment doesn't do it for you, here's what I came up with:
url(r'^(?P<param1>foo|bar)(/(?P<param2>\d+))?(/(?P<param3>\d+))?(/(?P<param4>\d+))?/$', 'demo.views.view'),
And my view looked like:
def view(request, *args, **kwargs):
return render_to_response("index.html",
{ 'dict': [(k, v) for k,v in kwargs.iteritems()] },
context_instance=RequestContext(request))
It progressively added parameters as you added to the url, left to right, just as you'd expect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Maps API JS: Show map of a certain town Isn't it any longer possible in Google Maps API V3 (JavaScript) to display a marker at a setted/given town name? This is my code:
google.maps.event.addDomListener(window, 'load', function() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
new google.maps.Map(document.getElementById('locate'), myOptions);
There is the line center: new google.maps.LatLng(-34.397, 150.644) but I haven't the LatLng-Coordinates; just the town name. How could I display now the marker based on the name?
A: Two options... First, you can use the Google Geocoding API, which allows you to find the Lat/Lng of a site on the fly. Second, you can use this method, which requires a database.
A: If you're working with a limited set of towns, I'd suggest you create your own DB or hashmap of town names to latlng coordinates. Otherwise use either of Chris's suggestions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: xcode iphone UIPickerView My UIPickerView hits the didSelectRow method without actually clicking on the item in the list. All you have to do is flick the list to scroll and when it list stops scrolling it automatically fires this method. How can I fix this?
A: As herz said, this is simply how the UIPickerView behaves. You don't have to actually tap on the row to select it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CoreData inverse question My understanding of an inverse relationship in CoreData is that these two statements should be equivalent:
[department addEmployee:employee];
[employee setDepartment:department];
and that you only need to do one of them.
However, if I do this:
[department addEmployee:employee];
NSLog(@"%@",[employee department]);
It doesn't appear the the relationship was updated correctly.
Doing it this way however, works fine:
[employee setDepartment:department];
NSLog(@"%@",[employee department]);
I've also tried calling "processPendingChanges" on the context before the NSLog but it doesn't make a difference
A: Something looks wrong about your code. You have a method addEmployee, but the usual naming convention for such a method would be addEmployeesObject. It has an awkward name because you usually specify the name of a to-many relationship like that as "employees". Key-Value coding knows how to change the capitalization of your property name, but it doesn't know how to unpluralize it.
If you are calling addEmployee and not getting an error, either you have done something in an unconventional way, or you might be calling some unrelated method that happens to exist. If it's the latter it could explain your problem.
My second guess is to check to make sure your inverse is defined in both directions. That is, Department should have an employees relationship, and its inverse should be specified as department. Employee should have a department relationship, and its inverse should be specified as employees. I think if you use the model editor in XCode it automatically sets both inverses if you set one, but it might be possible to unintentionally override that, and I imagine if you define your data model in code you could do it.
Otherwise it seems that what you are doing should work.
A: Check your NSManagedObject subclasses (the classes that represent the classes in your Core Data model) that the relationships match what you have in your data model. For example, if you added a relationship to the model after you already generated/coded your Employee and Department NSManagedObject subclasses, then those subclasses will be out of date and not reflect your model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java PipedInputStream available() method return value I am trying to write a piece of unblocking code to read from a PipedInputStream. It basically checks if there is anything to be read before calling the blocking read API:
int n = 0;
if ((n = pipedInputStream_.available()) > 0) {
pipedInputStream_.read(...)
}
Reading through the java API doc I cant tell for sure what that check should be, since the possible values are zero (implies no data, or closed/broken stream) or greater than zero . So how can the caller know if there is anything to be read at all?
"Returns the number of bytes that can be read from this input stream without blocking, or 0 if this input stream has been closed by invoking its close() method, or if the pipe is unconnected, or broken."
Looking at the source it seems like the only values are zero or greater than zero.
public synchronized int available() throws IOException {
if(in < 0)
return 0;
else if(in == out)
return buffer.length;
else if (in > out)
return in - out;
else
return in + buffer.length - out;
}
A: If available() returns zero, there are no bytes available to read at present. Per the documentation you quote, that can be so for several reasons:
*
*The pipe was closed.
*The pipe is broken.
*All the previously-available input (if any) was already consumed.
A zero return value from available() might imply that an error had occurred, implying that you will never be able to read any more data through the pipe in the future, but you can't tell for sure here, because zero might be indicating that third condition above, where blocking on InputStream#read() might eventually yield more data that the corresponding OutputStream side will push through the pipe.
I don't see that it's possible to poll a PipedInputStream with available() until more data becomes available, because you'll never be able to distinguish the terminal cases above (the first and the second) from the reader being more hungry than the writer. Like so many stream interfaces, here too you have to try to consume and be ready to fail. That's the trap; InputStream#read() will block, but not until you commit to blocking on an attempt to read will you be able to discern that no more input is coming.
It is not feasible to base your consuming actions on available(). If it returns a positive number, there's something to be read, but of course even what is available now might not be "enough" to satisfy your consumer. You will find your application easier to manage if you commit a thread to consuming the InputStream in blocking fashion and skip the polling with available(). Let InputStream#read() be your sole oracle here.
A: I needed a filter to intercept slow connections where I need to close DB connections ASAP so I initially used Java pipes but when looked closer at their implementation, it is all synchronized so I ended up creating my own QueueInputStream using a small buffer and Blocking queue to put the buffer in the queue once was full, it is lock free except when for the lock conditions used at LinkedBlockingQueue which with the aid of the small buffer it should be cheap, this class is only intended to be used for a single producer and consumer per instance:
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.*;
public class QueueOutputStream extends OutputStream
{
private static final int DEFAULT_BUFFER_SIZE=1024;
private static final byte[] END_SIGNAL=new byte[]{-1};
private final BlockingQueue<byte[]> queue=new LinkedBlockingDeque<>();
private final byte[] buffer;
private boolean closed=false;
private int count=0;
public QueueOutputStream()
{
this(DEFAULT_BUFFER_SIZE);
}
public QueueOutputStream(final int bufferSize)
{
if(bufferSize<=0){
throw new IllegalArgumentException("Buffer size <= 0");
}
this.buffer=new byte[bufferSize];
}
private synchronized void flushBuffer()
{
if(count>0){
final byte[] copy=new byte[count];
System.arraycopy(buffer,0,copy,0,count);
queue.offer(copy);
count=0;
}
}
@Override
public synchronized void write(final int b) throws IOException
{
if(closed){
throw new IllegalStateException("Stream is closed");
}
if(count>=buffer.length){
flushBuffer();
}
buffer[count++]=(byte)b;
}
@Override
public synchronized void close() throws IOException
{
flushBuffer();
queue.offer(END_SIGNAL);
closed=true;
}
public Future<Void> asyncSendToOutputStream(final ExecutorService executor, final OutputStream outputStream)
{
return executor.submit(
new Callable<Void>()
{
@Override
public Void call() throws Exception
{
try{
byte[] buffer=queue.take();
while(buffer!=END_SIGNAL){
outputStream.write(buffer);
buffer=queue.take();
}
outputStream.flush();
} catch(Exception e){
close();
throw e;
} finally{
outputStream.close();
}
return null;
}
}
);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Jquery Event Handling Question Say I have this code:
$(document).ready(function()
{
$(".foo").click(processFooClick);
}
Once the document has loaded, then via javascript I dynamically add a new div with foo class to the document:
$("body").append( "<div class='foo'>click..</div>");
Would this new div also have the event handler automatically applied to it, or would I need to run the event setting code ( $(".foo").click(...) ) again?
Would using jquery's live function help with this? If so, how?
A: The new div will not have the event handler attached to it. live will allow it to work as you described:
$(".foo").live('click', processFooClick);
But, I'd just add the event handler to the new div again. You shouldn't use live unless you really don't control when new elements are added to the page.
A: click() is a shortcut for bind(). bind will attach directly to the matching elements. That means, no, your new element will not have a handler. Using $(".foo").live(processClick) will work, because live() works by attaching a handler to the document and catching bubbled-up events. Also look at delegate() for a more scoped live type of event handler.
A: When event handlers are added, they are added to the elements themselves, so adding new matching elements will not result in them having the event handlers. I believe you can re-assign the handlers.
Using .live() avoids this problem - I believe that (paraphrasing) events are handled on the fly, and if an element matches it it applied. You can add elements as needed and they will handle any events that have been applied to matching elements.
A: live would work, but your first method would not (if you add the div after the first click function was run)
If you decide to call click again, you need to make sure you are not adding the click handler twice to all your original foo divs, or they will be run twice
A: I'd say you probably need to use live as your click event registration is done after DOMs are loaded. Any dynamically generated DOM won't get that event handler so you have to use live. In this case, something like:
$(".foo").live('click', processFooClick);
Or if you have a narrower context scope:
$(".foo", $(someContext)[0]).live('click', processFooClick);
A: Your first method would not work, take a look at this jsFiddle: http://jsfiddle.net/esN4Q/
But, live would:
$(".foo").live('click', processFooClick);
jsFiddle Example of jQuery live: http://jsfiddle.net/ePmXU/ (I added an alert pop up in the jsFiddle so we can see if it works when it's clicked.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Silverlight DoubleAnimation: Set KeyProperties from Codebehind? Hi I define my Storyboard as Resource in XAML:
<Storyboard x:Name="vor">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="master">
<EasingDoubleKeyFrame x:Name="point" KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:2" Value="700"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
and now I try to modify the Value from one of the EasingDoubleKeyFrames:
private void test(object sender, RoutedEventArgs e)
{
point.SetValue(EasingDoubleKeyFrame.ValueProperty, 400);
vor.Begin();
}
it doesn't work. You know why not?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using sub-query inside "IN" operator? I'm extending a basic shopping cart system and need a way to show all invoices in which a given product was purchased. I'm not sure a SELECT can be done this way, but I could a boost.
The problem is that invoice IDs correspond to shopping cart entries which identify the product IDs being purchased. I am querying for all purchases within a given category of products (p.categoryid).
SELECT i.id, i.name, i.totalprice, i.dateof
FROM invoices i
WHERE i.status > '1' AND i.id IN (
SELECT c.invoice FROM maj_cart c, maj_products p WHERE c.pid = p.pid AND p.categoryid = '43'
)
Here is my database structure:
CREATE TABLE IF NOT EXISTS `maj_cart` (
`cid` int(10) NOT NULL auto_increment,
`pid` int(10) NOT NULL default '0',
`sessid` varchar(50) NOT NULL default '',
`dateof` int(10) NOT NULL default '0',
`price` decimal(10,2) NOT NULL,
`shipping` decimal(10,2) NOT NULL,
`discount` decimal(10,2) NOT NULL,
`quantity` int(10) NOT NULL default '0',
`total` decimal(10,2) NOT NULL,
`invoice` int(10) NOT NULL default '0',
`status` int(1) NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
CREATE TABLE IF NOT EXISTS `maj_invoices` (
`id` int(10) NOT NULL auto_increment,
`dateof` int(10) NOT NULL default '0',
`userid` int(10) NOT NULL default '0',
`sessid` varchar(50) NOT NULL default '',
`name` varchar(255) NOT NULL default '',
`company` varchar(150) NOT NULL,
`email` varchar(255) NOT NULL default '',
`address1` varchar(255) NOT NULL default '',
`address2` varchar(255) NOT NULL default '',
`city` varchar(255) NOT NULL default '',
`state` char(3) NOT NULL default '',
`zip` varchar(10) NOT NULL default '',
`phone` varchar(40) NOT NULL default '',
`phone2` varchar(40) NOT NULL,
`instructions` text NOT NULL,
`recipmssg` text NOT NULL,
`promo` int(10) NOT NULL,
`discount` decimal(10,2) NOT NULL,
`totalprice` decimal(10,2) NOT NULL default '0.00',
`filename` varchar(20) NOT NULL,
`status` int(1) NOT NULL default '0',
`shipped` int(1) NOT NULL default '0',
`errorno` int(1) NOT NULL default '0',
`notes` text,
`source` int(5) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 PACK_KEYS=1 ;
CREATE TABLE IF NOT EXISTS `maj_products` (
`pid` int(10) NOT NULL auto_increment,
`itemnum` varchar(30) NOT NULL default '',
`filename` varchar(100) default NULL,
`original` varchar(255) default NULL,
`itemname` varchar(255) NOT NULL default '',
`descrip` text,
`summary` varchar(100) NOT NULL default '',
`categoryid` int(11) NOT NULL default '0',
`userid` int(10) NOT NULL default '0',
`dateadded` int(12) NOT NULL default '0',
`displayorder` int(10) NOT NULL default '0',
`price` decimal(10,2) NOT NULL default '0.00',
`shipping` decimal(10,2) NOT NULL default '0.00',
`instock` int(10) NOT NULL default '0',
`discount` int(10) NOT NULL,
`meta_keywords` text NOT NULL,
`meta_descrip` text NOT NULL,
PRIMARY KEY (`pid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 PACK_KEYS=1 ;
A: The suggested method would be just a normal join:
SELECT i.id, i.name, i.totalprice, i.dateof
FROM invoices i
INNER JOIN maj_cart c ON c.invoice = i.id
INNER JOIN maj_products p ON c.pid = p.pid
WHERE p.category_id = 43
AND i.status > '1'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error Processor type not supported after project converted from Visual Studio 2008 to 2010 The solution, which retains an installer project, was recently converted from 2008 project to 2010.
However, attempts to run the .msi that is created returns the error
"Processor type not supported....
If you run the setup.exe, it will error that "the application is designed for a x64 platform but is being installed on an intel"
However, the configuration of the solution, is set to to Any CPU.
I am finding little in the way of possible solutions and have seen where people ran into this converting from 2003 - 2005.
Any suggestions?
A: Installer projects (assuming you mean the built in Visual Studio Installer stuff) don't expose their CPU type through the build/configuration system. Instead, there is a Target Platform property of the project itself (select project in Solution Explorer, open Properties).
This property only supports x86, x64 and Itanium, so whatever it's currently set to, it isn't AnyCPU.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook Like Button for multiple posts on one page: is it possible? I've been able to properly implement the Facebook Like Button for my WordPress single.php pages, where the link and a thumbnail from the post is correctly referred.
I've also been able to get the FB Like button to reference the correct link on a list of posts on the index.php. However, the thumbnails are being pulled randomly on the index.php.
Do I understand this correctly: that Facebook only allows you to specify one thumbnail per page with its Open Graph method in the space?
Just want a confirmation, because I can't find anything the definitively says this is the case.
A: No, you can specify multiple thumbnails on a page and then the user can pick from that selection of images. From the documentation:
You may include multiple og:image tags to associate multiple images
with your page.
A: There are two ways to get like the like button after each post, either you have to add this script underneath the POST QUERY
<span class='st_fblike_vcount'></span>
<span class='st_twitter_vcount'></span>
<span class='st_plusone_vcount'></span>
<span class='st_email_vcount'></span>
<span class='st_sharethis_vcount'></span>
stLight.options({publisher: "782110c4-838d-408f-8393-98897995ced4"});
Or install SHARETHIS plugin and configure it, choose AFTER EVERY POST...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the difference between Eclipse for Java and RCP? Do I have to download and install them separately? Or just the RCP package? Kinda confused.
A: The Eclipse RCP includes Eclipse for Java plus all tools needed to create eclipse plugins and Rich Client or Rich Ajax Applications (RCP+RAP). With RCP you can use eclipse as a base platform for your applications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flex DateTimeAxis not showing labels I have a chart that uses a DateTimeAxis for the x-axis and a renderer defined for it. I also have a function defined for the label on the axis but I am not able to get the labels to show.
Trying to print out a static time to test working.
private function timeAxisLabelFunction(obj1:Object, obj2:Object, axis:IAxis):String
{
return "9:30AM";
}
<mx:AreaChart
id="alertVolumeChart"
width="100%"
height="100%"
dataProvider="{volumes}"
showDataTips="true" >
<mx:horizontalAxis>
<mx:DateTimeAxis id="xAxis"
dataUnits="minutes"
baseAtZero="false"
alignLabelsToUnits="false"
interval="8"
minorTickInterval="1"
labelFunction="timeAxisLabelFunction"/>
</mx:horizontalAxis>
<mx:horizontalAxisRenderers>
<mx:AxisRenderer
id="hAxisRenderer" canDropLabels="false"
axis="{xAxis}" showLabels="true"
labelFunction="timeRendererLabelFunction"
minorTickLength="8" minorTickPlacement="outside"
tickLength="20" tickPlacement="outside"
labelAlign="right" labelGap="4"
tickStroke="{timeStroke}" minorTickStroke="{timeStroke}" axisStroke="{timeStroke}" >
</mx:AxisRenderer>
</mx:horizontalAxisRenderers>
<mx:series>
<mx:AreaSeries
yField="value" xField="time">
</mx:AreaSeries>
</mx:series>
</mx:AreaChart>
Update:
Apparently, the font family I was using doesnt support a font style that is used in the renderer. Not sure what style attribute it is yet.
A: The problem was with the font family i was trying to use. It was not compatible with the renderer so I needed to embed the same font again but with embedAsCFF: false;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: After each times click an increasing number? I want after each times click value 2011 an increasing number, how is it?
Example:
$('button').click(function() {
var num = '2011';
var out = num ++1;
alert(num); // i want this output: 2012
});
A: var num = 2011;
$('button').click(function() {
num++;
alert(num); // i want this output: 2012
});
A: var num = '2011';
$('button').click(function() {
num++;
alert(num); // i want this output: 2012
});
A: Try this:
var num = '2011';
$('button').click(function() {
var out = num++;
alert(num);
});
*
*var num must be outside of the function, otherwise it will be 2011 again every time the function is run.
*num++1 should be num++.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pivot Table Report I am trying to create a pivot table with data from a SQL database. The pivot table is basically a process capability report that requires certain information. I have created an Excel file that sort of does what we are trying to accomplish, but I don't think my calculations are quite accurate. I know after doing some research that there are Pivot Tables within SQL but I don't know how to get them to work.
The table that my data is stored in has thousands of records. Each record has the following information: DATE, TIME, PRODUCT_NO, SEQ, DATECODE, DATECODE_IDH, PRODUCT, LINE, SHIFT, SIZE, OPERATOR, SAMPLE_SIZE, WEIGHT (1-12), WEIGHTXR, LSL_WT, TAR_WT, USL_WT, LABEL, MAV, LINE_SIZE
For the report, I need to group the data based on product and by line. Since the product isn't consistent, each product can be described by TAR_WT. So the grouping will be a combination of TAR_WT and LINE_SIZE. I need to count how many instances of that product were measured which will be the number of measurements (each individual weight which is 12 weights per record). I also need to find the minimum, maximum, and average of all of the weights per product (again 12 weights for every record). After those values are obtained, I have to calculate the Standard Deviation, Cp, and Tz of the values (staistical calculations) and report all the information.
Date Time Product No Seq DateCode Internal DateCode&ProductNo Product Description Line Size Weight1 Weight2 Weight3 Weight4 WeightXR LSL_WT TAR_WT USL_WT LABEL MAV
8/3/11 0:37:54 1234567 23 DateCode Internal DateCode&ProductNo Product Description L-1A 50 1575 1566 1569.5 1575.5 1573.4 1550.809 1574.623 1598.437 1564.623 1525.507 L-1A_50
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Allow only numbers/year between rounded brackets For a website I want to allow only the year of production between rounded brackets with a RegEx.
Allowed:
Movie 1 (2010)
Disallowed:
Movie 2 (2010 English)
Movie 2 (01-01-2010)
What I want is a RegEx that will detect when letters are between the brackets or a combination of letters, spaces and numbers.
How do I achieve this?
A: Something like
/^.+\(\d{4}\)$/
A: This should do just fine:
/\(.*?([0-9]{4}).*?\)/
You can then use $1 to retrieve the year.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: External Interface Problem: Error calling method on NPObject Making a flash video streaming web-app using Actionscript 3's external Api. I am at a very rudimentary phase of the project where we're just experimenting with external interface. Right now i just have a flash object and 3 buttons each to play pause and load a video. The only button that is currently set up to do anything is the load button. My swf and my html file sit on the same file system, and my video files sit on another server with traffic being redirected through a media server.
When i press the load button, which should just give it the path of the video file on it's server. Instead it throws an error that reads "Error: Error Calling method on NPObject".
Without further adieu, here are snippets of relevant code:
ACTIONSCRIPT:
function loadVideo(newVideo){
clearInterval(progressInterval);
videoFile = newVideo;
stream.play(videoFile, 0, 0);
videoPositions = "0,0";
};
ExternalInterface.addCallback( "loadVideo", loadVideo );
JAVSCRIPT: (in the head of my html document)
<head>
<title> External API Test</title>
<script type="text/javascript">
var player = getFlashMovie();
if (typeof MY == 'undefined')
{
MY = {};
}
MY.load = function()
{
console.log('load called');
getFlashMovie().loadVideo("/media/preview/09/04/38833_2_720X405.mp4");
};
function getFlashMovie()
{
var isIE = navigator.appName.indexOf('Microsoft') != -1;
return (isIE) ? window['MYVID'] : document['MYVID'];
}
</script>
</head>
HTML:(in same document as javascript)
<body>
<div> This is a test</div>
<div class='my-media-player'>
<object width="720" height="405" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,16,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id='MYVID'>
<param value="as3VideoPlayer.swf" name="movie">
<param value="high" name="quality">
<param value="true" name="play">
<param value="false" name="LOOP">
<param value="transparent" name="wmode">
<param value="always" name="allowScriptAccess">
<embed width="720" height="405" name='MYVID' allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" loop="false" play="true" src="as3VideoPlayer.swf" wmode="transparent">
</object>
<div>
<button type="button" class='play'>Play</button>
<button type='button' class='pause'>Pause</button>
<button type='button' class='load' onclick='MY.load()'>Load</button>
</div>
</div>
</body>
Where is my mistake? I've read in a lot of places that this is an issue with security, but both my swf and html are in the same folder on my local machine. Only the files come from outside, and in any case I think i've set the security settings correctly when i declare my flash player in the object tag, but maybe i'm missing something there.
if you can't solve my question directly can someone please explain what "error calling method on NPObject" means? I'm sure its specific to flash-js communications because i've never seen it before and that's what i have gathered from my googling.
Thank in advanced.
A: I highly suggest SWFObject. Aside from that, I dare say you need to allow script access:
<script type="text/javascript">
// put your needed vars in the object below
var flashVars = {};
var params = {
allowScriptAccess:"always"
};
swfobject.embedSWF("myswf.swf", "myswf", "500", "400", "10.0.0", "", flashVars, params);
</script>
A: Can you try setting Security.allowDomain('*'); in your AS3 code right when it starts up?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: difference between int bar[10] vs int (*bar)[10] int bar[10]; /* bar is array 10 of int, which means bar is a pointer to array 10 of int */
int (*bar)[10]; /* bar is a pointer to array 10 of int */
According to me they both are same, am I wrong? Please tell me.
Edit: int *bar[10] is completely different.
Thanks
Raja
A: They are completely different. The first one is an array. The second one is a pointer to an array.
The comment you have after the first bar declaration is absolutely incorrect. The first bar is an array of 10 ints. Period. It is not a pointer (i.e. your "which means" part makes no sense at all).
It can be expressed this way:
typedef int T[10];
Your first bar has type T, while you r second bar has type T *. You understand the difference between T and T *, do you?
A: You can do this:
int a[10];
int (*bar)[10] = &a; // bar now holds the address of a
(*bar)[0] = 5; // Set the first element of a
But you can't do this:
int a[10];
int bar[10] = a; // Compiler error! Can't assign one array to another
A: These two declarations do not declare the same type.
Your first declaration declares an array of int.
Your second declaration declares a pointer to an array of int.
A: Here is a link about the C "right-left rule" I found useful when reading complex c declarations: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html. It may also help you understand the difference between int bar[10] and int (*bar)[10].
Taken from the article:
First, symbols. Read
* as "pointer to" - always on the left side
[] as "array of" - always on the right side
() as "function returning" - always on the right side
as you encounter them in the declaration.
STEP 1
------
Find the identifier. This is your starting point. Then say to yourself,
"identifier is." You've started your declaration.
STEP 2
------
Look at the symbols on the right of the identifier. If, say, you find "()"
there, then you know that this is the declaration for a function. So you
would then have "identifier is function returning". Or if you found a
"[]" there, you would say "identifier is array of". Continue right until
you run out of symbols *OR* hit a *right* parenthesis ")". (If you hit a
left parenthesis, that's the beginning of a () symbol, even if there
is stuff in between the parentheses. More on that below.)
STEP 3
------
Look at the symbols to the left of the identifier. If it is not one of our
symbols above (say, something like "int"), just say it. Otherwise, translate
it into English using that table above. Keep going left until you run out of
symbols *OR* hit a *left* parenthesis "(".
Now repeat steps 2 and 3 until you've formed your declaration.
A: There's also cdecl(1) and http://cdecl.org/
$ cdecl explain 'int bar[10]'
declare bar as array 10 of int
$ cdecl explain 'int (*bar)[10]'
declare bar as pointer to array 10 of int
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Images being requested multiple times from CSS Any idea what would make a stylesheet(s) load images multiple times? The images are the same URL, nothing fancy going on.
EDIT: Only happens in safari (5.0.3) in both iPhone "mode" and default "mode" - i cannot reproduce the problem in FF or IE.
Apache_access_log says that the image is indeed being accessed multiple times.
When adding styles that call the image back in one-by-one, they don't seem to follow any pattern as to when they will start to double up.
I also tried making the image significantly smaller to see if it was a cache issue. Didn't change anything.
A: Not sure what the deal is with Safari, but apparently:
If the CSS rules that reference the same sprite-sheet are not grouped together, it will request the image more than once. (Although not the full number of times the call appears).
#divOne, #divTwo, #divThree {
background-image: url('IMGURLHERE');
}
This would request the image one time.
#divOne {
background-image: url('IMGURLHERE');
}
#divTwo {
background-image: url('IMGURLHERE');
}
This would request the image twice.
No idea as to why this happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Powershell - how to create network adapter (loopback)? I want to create a loopback network adapter with powershell.
I can get an adapter using code like this.
$networkAdapter = Get-WMIObject win32_NetworkAdapter | where{$_.ServiceName -eq 'msloop'}
However, I cannot seem to find how to create an adapter. The only thing I found uses devcon.exe
.\devcon.exe -r install $env:windir\Inf\Netloop.inf *MSLOOP | Out-Null
This is going to be for a windows 7 box and I didn't want to have to install some other package just to do it. If devcon is required then is there a way to include the download and setup in the script as well?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Interesting tree/hierarchical data structure problem Colleges have different ways of organizing their departments. Some schools go School -> Term -> Department. Others have steps in between, with the longest being School -> Sub_Campus -> Program -> Term -> Division -> Department.
School, Term, and Department are the only ones that always exist in a school's "tree" of departments. The order of these categories never changes, with the second example I gave you being the longest. Every step down is a 1:N relationship.
Now, I'm not sure how to set up the relationships between the tables. For example, what columns are in Term? Its parent could be a Program, Sub_Campus, or School. Which one it is depends on the school's system. I could conceive of setting up the Term table to have foreign keys for all of those (which all would default to NULL), but I'm not sure this is the canonical way of doing things here.
A: I suggest you better use a general table, called e.g. Entity which would contain id field and a self-referencing parent field.
Each relevant table would contain a field pointing to Entity's id (1:1). In a way each table would be a child of the Entity table.
A: Here's one design possibility:
This option takes advantage of your special constraints. Basically you generalize all hierarchies as that of the longest form by introducing generic nodes. If school doesn't have "sub campus" then just assign it a generic sub campus called "Main". For example, School -> Term -> Department can be thought of same as School -> Sub_Campus = Main -> Program=Main -> Term -> Division=Main -> Department. In this case, we assign a node called "Main" as default when school doesn't have that nodes. Now you can just have a boolean flag property for these generic nodes that indicates that they are just placeholders and this flag would allow you to filter it out in middle layer or in UX if needed.
This design will allow you to take advantage of all relational constraints as usual and simplify handling of missing node types in your code.
A: -- Enforcing a taxonomy by self-referential (recursive) tables.
-- Both the classes and the instances have a recursive structure.
-- The taxonomy is enforced mostly based on constraints on the classes,
-- the instances only need to check that {their_class , parents_class}
-- form a valid pair.
--
DROP schema school CASCADE;
CREATE schema school;
CREATE TABLE school.category
( id INTEGER NOT NULL PRIMARY KEY
, category_name VARCHAR
);
INSERT INTO school.category(id, category_name) VALUES
( 1, 'School' )
, ( 2, 'Sub_campus' )
, ( 3, 'Program' )
, ( 4, 'Term' )
, ( 5, 'Division' )
, ( 6, 'Department' )
;
-- This table contains a list of all allowable {child->parent} pairs.
-- As a convention, the "roots" of the trees point to themselves.
-- (this also avoids a NULL FK)
CREATE TABLE school.category_valid_parent
( category_id INTEGER NOT NULL REFERENCES school.category (id)
, parent_category_id INTEGER NOT NULL REFERENCES school.category (id)
);
ALTER TABLE school.category_valid_parent
ADD PRIMARY KEY (category_id, parent_category_id)
;
INSERT INTO school.category_valid_parent(category_id, parent_category_id)
VALUES
( 1,1) -- school -> school
, (2,1) -- subcampus -> school
, (3,1) -- program -> school
, (3,2) -- program -> subcampus
, (4,1) -- term -> school
, (4,2) -- term -> subcampus
, (4,3) -- term -> program
, (5,4) -- division --> term
, (6,4) -- department --> term
, (6,5) -- department --> division
;
CREATE TABLE school.instance
( id INTEGER NOT NULL PRIMARY KEY
, category_id INTEGER NOT NULL REFERENCES school.category (id)
, parent_id INTEGER NOT NULL REFERENCES school.instance (id)
-- NOTE: parent_category_id is logically redundant
-- , but needed to maintain the constraint
-- (without referencing a third table)
, parent_category_id INTEGER NOT NULL REFERENCES school.category (id)
, instance_name VARCHAR
); -- Forbid illegal combinations of {parent_id, parent_category_id}
ALTER TABLE school.instance ADD CONSTRAINT valid_cat UNIQUE (id,category_id);
ALTER TABLE school.instance
ADD FOREIGN KEY (parent_id, parent_category_id)
REFERENCES school.instance(id, category_id);
;
-- Forbid illegal combinations of {category_id, parent_category_id}
ALTER TABLE school.instance
ADD FOREIGN KEY (category_id, parent_category_id)
REFERENCES school.category_valid_parent(category_id, parent_category_id);
;
INSERT INTO school.instance(id, category_id
, parent_id, parent_category_id
, instance_name) VALUES
-- Zulo
(1,1,1,1, 'University of Utrecht' )
, (2,2,1,1, 'Uithof' )
, (3,3,2,2, 'Life sciences' )
, (4,4,3,3, 'Bacherlor' )
, (5,5,4,4, 'Biology' )
, (6,6,5,5, 'Evolutionary Biology' )
, (7,6,5,5, 'Botany' )
-- Nulo
, (11,1,11,1, 'Hogeschool Utrecht' )
, (12,4,11,1, 'Journalistiek' )
, (13,6,12,4, 'Begrijpend Lezen' )
, (14,6,12,4, 'Typvaardigheid' )
;
-- try to insert an invalid instance
INSERT INTO school.instance(id, category_id
, parent_id, parent_category_id
, instance_name) VALUES
( 15, 6, 3,3, 'Procreation' );
WITH RECURSIVE re AS (
SELECT i0.parent_id AS pa_id
, i0.parent_category_id AS pa_cat
, i0.id AS my_id
, i0.category_id AS my_cat
FROM school.instance i0
WHERE i0.parent_id = i0.id
UNION
SELECT i1.parent_id AS pa_id
, i1.parent_category_id AS pa_cat
, i1.id AS my_id
, i1.category_id AS my_cat
FROM school.instance i1
, re
WHERE re.my_id = i1.parent_id
)
SELECT re.*
, ca.category_name
, ins.instance_name
FROM re
JOIN school.category ca ON (re.my_cat = ca.id)
JOIN school.instance ins ON (re.my_id = ins.id)
-- WHERE re.my_id = 14
;
The output:
INSERT 0 11
ERROR: insert or update on table "instance" violates foreign key constraint "instance_category_id_fkey1"
DETAIL: Key (category_id, parent_category_id)=(6, 3) is not present in table "category_valid_parent".
pa_id | pa_cat | my_id | my_cat | category_name | instance_name
-------+--------+-------+--------+---------------+-----------------------
1 | 1 | 1 | 1 | School | University of Utrecht
11 | 1 | 11 | 1 | School | Hogeschool Utrecht
1 | 1 | 2 | 2 | Sub_campus | Uithof
11 | 1 | 12 | 4 | Term | Journalistiek
2 | 2 | 3 | 3 | Program | Life sciences
12 | 4 | 13 | 6 | Department | Begrijpend Lezen
12 | 4 | 14 | 6 | Department | Typvaardigheid
3 | 3 | 4 | 4 | Term | Bacherlor
4 | 4 | 5 | 5 | Division | Biology
5 | 5 | 6 | 6 | Department | Evolutionary Biology
5 | 5 | 7 | 6 | Department | Botany
(11 rows)
BTW: I left out the attributes. I propose they could be hooked to the relevant categories by means of a EAV type of data model.
A: I'm going to start by discussing implementing a single hierarchical model (just 1:N relationships) relationally.
Let's use your example School -> Term -> Department.
Here's code that I generated using MySQLWorkbench (I removed a few things to make it clearer):
-- -----------------------------------------------------
-- Table `mydb`.`school`
-- -----------------------------------------------------
-- each of these tables would have more attributes in a real implementation
-- using varchar(50)'s for PKs because I can -- :)
CREATE TABLE IF NOT EXISTS `mydb`.`school` (
`school_name` VARCHAR(50) NOT NULL ,
PRIMARY KEY (`school_name`)
);
-- -----------------------------------------------------
-- Table `mydb`.`term`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`term` (
`term_name` VARCHAR(50) NOT NULL ,
`school_name` VARCHAR(50) NOT NULL ,
PRIMARY KEY (`term_name`, `school_name`) ,
FOREIGN KEY (`school_name` )
REFERENCES `mydb`.`school` (`school_name` )
);
-- -----------------------------------------------------
-- Table `mydb`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`department` (
`dept_name` VARCHAR(50) NOT NULL ,
`term_name` VARCHAR(50) NOT NULL ,
`school_name` VARCHAR(50) NOT NULL ,
PRIMARY KEY (`dept_name`, `term_name`, `school_name`) ,
FOREIGN KEY (`term_name` , `school_name` )
REFERENCES `mydb`.`term` (`term_name` , `school_name` )
);
Here is the MySQLWorkbench version of the data model:
As you can see, school, at the top of the hierarchy, has only school_name as its key, whereas department has a three-part key including the keys of all of its parents.
Key points of this solution
*
*uses natural keys -- but could be refactored to use surrogate keys (SO question -- along with UNIQUE constraints on multi-column foreign keys)
*every level of nesting adds one column to the key
*each table's PK is the entire PK of the table above it, plus an additional column specific to that table
Now for the second part of your question.
My interpretation of the question
There is a hierarchical data model. However, some applications require all of the tables, whereas others utilize only some of the tables, skipping the others. We want to be able to implement 1 single data model and use it for both of these cases.
You could use the solution given above, and, as ShitalShah mentioned, add a default value to any table which would not be used. Let's see some example data, using the model given above, where we only want to save School and Department information (no Terms):
+-------------+
| school_name |
+-------------+
| hogwarts |
| uCollege |
| uMatt |
+-------------+
3 rows in set (0.00 sec)
+-----------+-------------+
| term_name | school_name |
+-----------+-------------+
| default | hogwarts |
| default | uCollege |
| default | uMatt |
+-----------+-------------+
3 rows in set (0.00 sec)
+-------------------------------+-----------+-------------+
| dept_name | term_name | school_name |
+-------------------------------+-----------+-------------+
| defense against the dark arts | default | hogwarts |
| potions | default | hogwarts |
| basket-weaving | default | uCollege |
| history of magic | default | uMatt |
| science | default | uMatt |
+-------------------------------+-----------+-------------+
5 rows in set (0.00 sec)
Key points
*
*there is a default value in term for every value in school -- this could be quite annoying if you had a table deep in the hierarchy that an application didn't need
*since the table schema doesn't change, the same queries can be used
*queries are easy to write and portable
*SO seems to think default should be colored differently
There is another solution to storing trees in databases. Bill Karwin discusses it here, starting around slide 49, but I don't think this is the solution you want. Karwin's solution is for trees of any size, whereas your examples seem to be relatively static. Also, his solutions come with their own set of problems (but doesn't everything?).
I hope that helps with your question.
A: For the general problem of fitting hierarchical data in a relational database, the common solutions are adjacency lists (parent-child links like your example) and nested sets. As noted in the wikipedia article, Oracle's Tropashko propsed an alternative nested interval solution but it's still fairly obscure.
The best choice for your situation depends on how you will be querying the structure, and which DB you are using. Cherry picking the article:
Queries using nested sets can be expected to be faster than queries
using a stored procedure to traverse an adjacency list, and so are the
faster option for databases which lack native recursive query
constructs, such as MySQL
However:
Nested set are very slow for inserts because it requires updating lft
and rgt for all records in the table after the insert. This can cause
a lot of database thrash as many rows are rewritten and indexes
rebuilt.
Again, depending on how your structure will be queried, you may choose a NoSQL style denormalized Department table, with nullable foreign keys to all possible parents, avoiding recursive queries altogether.
A: I would develop this in a very flexible manner and what seems to mean to be the simplest as well:
There should only be one table, lets call it the category_nodes:
-- possible content, of this could be stored in another table and create a
-- 1:N -> category:content relationship
drop table if exists category_nodes;
create table category_nodes (
category_node_id int(11) default null auto_increment,
parent_id int(11) not null default 1,
name varchar(256),
primary key(category_node_id)
);
-- set the first 2 records:
insert into category_nodes (parent_id, name) values( -1, 'root' );
insert into category_nodes (parent_id, name) values( -1, 'uncategorized' );
So each record in the table has a unique id, a parent id, and a name.
Now after the first 2 inserts: in category_nodes where the category_node_id is 0 is the root node (the parent of all nodes no matter how many degres away. The second is just for a little helper, set an uncategorized node at the category_node_id = 1 which is also the defalt value of parent_id when inserting into the table.
Now imagining the root categories are School, Term, and Dept you would:
insert into category_nodes ( parent_id, name ) values ( 0, 'School' );
insert into category_nodes ( parent_id, name ) values ( 0, 'Term' );
insert into category_nodes ( parent_id, name ) values ( 0, 'Dept' );
Then to get all the root categories:
select * from category_nodes where parent_id = 0;
Now imagining a more complex schema:
-- School -> Division -> Department
-- CatX -> CatY
insert into category_nodes ( parent_id, name ) values ( 0, 'School' ); -- imaging gets pkey = 2
insert into category_nodes ( parent_id, name ) values ( 2, 'Division' ); -- imaging gets pkey = 3
insert into category_nodes ( parent_id, name ) values ( 3, 'Dept' );
--
insert into category_nodes ( parent_id, name ) values ( 0, 'CatX' ); -- 5
insert into category_nodes ( parent_id, name ) values ( 5, 'CatY' );
Now to get all the subcategories of School for example:
select * from category_nodes where parent_id = 2;
-- or even
select * from category_nodes where parent_id in ( select category_node_id from category_nodes
where name = 'School'
);
And so on. Thanks to a default = 1 with the parent_id, inserting into the 'uncategorized' category become simple:
<?php
$name = 'New cat name';
mysql_query( "insert into category_nodes ( name ) values ( '$name' )" );
Cheers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: The click event is not working Can someone point me in the right direction in figuring out why the event in the code below is not working. I tried using firefox but not sure how to troubleshooting this problem using firefox.
When I click on the button, nothing happens. I don't see the alert box
<script type="text/javascript">
$(document).ready(function()
{
$(#saveButton).click(function()
{
alert("hello World");
});
});
</script>
<div id="west" class="ui-layout-west">
<input id="saveButton" type="button" value="save"></input>
<div> <ul id="ul_west"></ul> </div>
</div>
A: You forgot the quotes around the id.
$('#saveButton').click(function(){
alert("hello World");
});
A: $('#saveButton').click(function() // forgot '
{
alert("hello World");
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why am I getting a '.class' expected error? Simple Array script My program is creating an array and allowing the user to input 10 double precision numbers. Then the program will sort them in order from lowest to highest. I have the following but receive .class expected error upon compiling. Any ideas on why this is happening? Note * I have not been able to compile this yet so I don't even know if this will work. *
import java.io.*;
public class ArrayDemo
{
public static void main(String[] args) throws IOException
{
int i = 0;
int j = 0;
int temp = 0;
double[] intValue = new double[10];
String[] numbers = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"};
int len = intValue.length[];
BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
for (i = 0; i < len; ++i)
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
{
for (j = 0; j < (len - 1) -i; j++)
if (intValue[j] > intValue[j+1])
{
temp = intValue[j];
intValue[j] = intValue[j+1];
intValue[j+1] = temp;
}
for (i = 0; i < 10; i++);
{
System.out.println("Array after sorting in ascending order");
System.out.println();
System.out.println(intValue[i]);
}
}
}
}
Thank you for any input. :)
A: int temp = 0; should be double temp = 0;
and
int len = intValue.length[]; should be int len = intValue.length;
and
for (i = 0; i < 10; i++); should be for (i = 0; i < 10; i++)
Sample
EDIT
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
int i = 0;
int j = 0;
int k = 0;
double temp = 0;
double[] intValue = new double[10];
String[] numbers = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"};
int len = intValue.length;
BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
for (i = 0; i < len; ++i) {
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
}
for (j = 0; j < len; j++)
{
for(k = 0; k < len; k++) {
if (intValue[j] > intValue[k])
{
temp = intValue[j];
intValue[j] = intValue[k];
intValue[k] = temp;
}
}
}
System.out.println("Array after sorting in ascending order");
for (i = 0; i < 10; i++)
{
System.out.print(intValue[i] + ", ");
}
}
}
A: int len = intValue.length[];
You don't need [] after length and you also tried to assign int temp to a value in a double array
temp = intValue[j];
Also using an IDE like Eclipse/NetBeans/IntelliJ would definitely help!
A: int len = intValue.length[];
should instead be:
int len = intValue.length;
Also, some of your bracketing appears to be incorrect. I believe, for example, that you want the following snippet:
for (i = 0; i < len; ++i)
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
Changed to:
for (i = 0; i < len; ++i)
{
System.out.println("Enter the " + numbers[i] + " number");
intValue[i] = Double.valueOf(dataIn.readLine());
}
You have a number of other logical errors in your code as well. Let me know, after you work with the code for a while based on the current answers, if you have any specific questions and I will help you further.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should project that will always use MySQL use PDO? I have created a project which uses a MySQL-database in a very basic way. This means I only use SELECT, INSERT, UPDATE and DELETE. No joins, no table creation. Most queries are SELECTs and most of the time I only select some rows of one record.
I'm also quite sure that this project will always use MySQL.
Now I've heard about PDO and some people seem to think that it's in general a good idea to use it. According to php.net "PDO provides [only] a data-access abstraction layer".
Is there any reason why a project which will always use MySQL should use PDO? Any reason why it might be a bad idea to use PDO in such a project?
A: It's always a good idea, if only for prepared statements and bound parameters.
PDO supports different database drivers but does not provide database abstraction, it just provides a consistent interface to accessing data. There is really no drawback in using it, and mysql_* functions should just be dropped.
A: There is no reason why you should not use it.
You can also be totally safe not using it, just remember to use the modern extension mysqli and not mysql, and use parameterized queries instead of the utter mess that is string concatenation and mysql_real_escape_string().
The reason why you should be using PDO, however, is that it will teach you how to use an interface database that will give you the generic knowledge to work on any other database in your future projects. In other words, it will teach you to differentiate "ask some data from the database" from "how exactly does this particular database need to be called".
Again, use parameterized queries with it.
A: If you have no joins why are you using a relational database in the first place? You just need a key/value store.
I usually don't use pdo for MySQL specific projects.
A: First of all, PDO is mostly used for object oriented programming. It is also a lot safer and faster than MySQL. Since you are accessing data for CRUD (create,read, update,delete) it is actually more efficient than MySQL.
Only problem I see is to install the PDO driver, but it is installed on most servers now.
So, if you're going to use OOP, the you must use PDO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Landscape mode without a ViewController I have a project based on a window-template, so it doesn't have a viewController. Now I'm trying to make this work in landscape only, and I have set the "supported device orientations" to "Landscape (right home button)" only, just the way I want it. The app actually launches in Landscape mode, but when I want to show an image which is btw a landscape-fullscreen one, iOS draws it in Portrait mode, cutting off what doesn't fit. Well I know the option of implementing a ViewController and editing the "shouldAutorotate..." method, but I want to do it without.
I have one solution in my mind, but I'm not sure whether it#s such a great idea: Rotate the whole coordinate-system on app-startup manually using "CGTransform..."
A: Down that path lies madness. Just because the template doesn't include a built-in UIViewController doesn't mean you can't add one yourself.
Add one, and save yourself a bazillion headaches.
From a more technical standpoint, a lot a UIKit expects the window to have a UIViewController, and not having one means you can lose out on a whole lot of behavior that you would otherwise get for free.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android - will users trust embedded webview for twitter authorization? Will users trust if I use an embedded webview to authorize my app with twitter? I could obviously be providing a fake page to catch their login. Or do they expect me to launch a browser so they can see the url etc? If I do that, is there any way to automatically return to my app when finished? How do other apps handle this? Expecting the user to press the back button after they're done isn't very graceful, as the oauth process involves about 3 page redirects in my case.
A: Users seem to trust an embedded webview, especially if you place it in a "pop-up" dialog. We have done that in some of our apps (http://larvalabs.com). Once authorized, it is possible to get a callback to automatically return to your app, sparing the user the hassle. See for example this approach:
http://blog.doityourselfandroid.com/2011/08/08/improved-twitter-oauth-android/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I require a library newer than the one required by the Play! Framework? I need a newer version than 1.5 of the oval framework, so I try to add it to the dependencies but play requires 1.5 which overrides my dependency. How do I force play to let me use a newer version? (I know technically I could change it in $PLAY_HOME$/framework/dependencies.yml, but that seems like a bad idea)
My conf/dependencies.yml
require:
- play
- net.sf.oval -> oval 1.7
My error
~ Some dependencies have been evicted,
~
~ oval 1.7 is overriden by oval 1.50
A: Try to use force option:
- net.sf.oval -> oval 1.7:
force: true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do $_REQUEST two fields and post them together on another page? I have a form that inserts data into mySQL. It works fine.
After the submission, I have a success page that displays 'part_no'. I need to also show 'add_qty', as well.
How do i alter my post script to show two field data's on the success page?
Here is part of my code (that already works):
$part_no = $_REQUEST['part_no'] ;
header("location: inv_fc_add_success.php?part_no=" . urlencode($part_no));
}
else {
header("location: inv_fc_add_fail.php");
}
?>
A: Just append it as another $_GET variable i.e part_no="part"&quantity=1
header("location: inv_fc_add_success.php?part_no=" . urlencode($part_no)."&qty=".$quantity );
A: You need 3 things.
First, you'll need:
$add_qty = $_REQUEST['add_qty'];
Alternatively you can simply use $_REQUEST['add_qty'] directly instead of assigning it to a new variable ($add_qty).
Then instead of:
header("location: inv_fc_add_success.php?part_no=" . urlencode($part_no));
you need:
header("location: inv_fc_add_success.php?part_no=" . urlencode($part_no) . "&add_qty=" . urlencode($add_qty));
Then, on the page inv_fc_add_success.php (which you will need to edit), you display the variable the same way that you display $part_no. As always, you can either assign it to a variable, like you already do at the top, or you can just use $_REQUEST['add_qty'] directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XML Generate Columns by Group using XSLT I am trying to generate a 4 column directory, grouped by the 4 disciplines in my department. One XML file contains the entire group. Each element has a department tag. The construction of the directory would be the following:
Group each entry by discipline.
For each group, cycle through each entry. If the Rank equals Supervisor, fill out the supervisor DIV, otherwise keep generating a div for each person in the group.
Once all entries in the group are exhausted, construct the next column for the next group...
Keep going until all groups are exhausted.
I'm new to XSLT and really need help. I can create a key for each group, and cycle through the entries in the group, but I'm not sure how to cycle through the different groups.
My mark up is below.
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="group" match="employee" use="dept" />
<xsl:template match="/">
<div id="directory">
<div class="man">
<h1>Manager</h1>
<h2>John Doe</h2>
</div>
<div class="group">
<xsl:for-each select="key('group', 'Mechanical')">
<xsl:sort select="name" order="ascending"/>
(I need a conditional here to check if rank = supervisor)
<div class="super">
<h1>Supervisor</h1>
<h2><xsl:value-of select="name"/></h2>
</div>
<div>
<p class="name"><xsl:value-of select="name"/></p>
<p class="ID"><xsl:value-of select="id"/></p>
</div>
</xsl:for-each>
</div>
XML Directory
<?xml version="1.0" encoding="ISO-8859-1" ?>
<directory>
<employee>
<dept></dept>
<rank>Manager</rank>
<name>John Doe</name>
<id>1234</id>
</employee>
<employee>
<dept>Mechanical</dept>
<rank>Supervisor</rank>
<name>Jane Doe</name>
<id>4321</id>
</employee>
<employee>
<dept>Mechanical</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
<employee>
<dept>Mechanical</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
<employee>
<dept>Civil</dept>
<rank>Supervisor</rank>
<name>Jane Doe</name>
<id>4321</id>
</employee>
<employee>
<dept>Civil</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
<employee>
<dept>Civil</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
<employee>
<dept>Electrical</dept>
<rank>Supervisor</rank>
<name>Jane Doe</name>
<id>4321</id>
</employee>
<employee>
<dept>Electrical</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
<employee>
<dept>Electrical</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
</directory>
Output would look something like:
HTML should look something like:
<div id="directory">
<div class="man">
<h1>Manager</h1>
<h2>John Doe</h2>
</div>
<div class="group">
<div class="super">
<h1>Mechanical Supervisor</h1>
<h2>Supervisor Name</h2>
</div>
<div>
<p class="name">Mech employee name</p>
<p class="ID">Mech employee ID</p>
</div><!--end group A-->
<div class="group">
<div class="super">
<h1>CivilSupervisor</h1>
<h2>Supervisor Name</h2>
</div>
<div>
<p class="name">Civil employee name</p>
<p class="ID">Civil employee ID</p>
</div><!--end group B-->
<div class="group">
<div class="super">
<h1>Electrical Supervisor</h1>
<h2>Supervisor Name</h2>
</div>
<div>
<p class="name">Electrical employee name</p>
<p class="ID">Electrical employee ID</p>
</div><!--end group C-->
</div>
A: This XSLT 1.0 transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kEmpByDeptRank" match="employee"
use="concat(dept,'+', rank)"/>
<xsl:key name="kEmpByDept" match="employee"
use="dept"/>
<xsl:template match="directory">
<div id="directory">
<xsl:apply-templates select=
"key('kEmpByDeptRank', '+Manager')"/>
<xsl:apply-templates select=
"employee[not(rank='Manager')]"/>
</div>
</xsl:template>
<xsl:template match=
"employee[generate-id()
=
generate-id(key('kEmpByDept', dept)[1])
]
">
<div class="group">
<xsl:apply-templates mode="inGroup" select=
"key('kEmpByDeptRank', concat(dept,'+Supervisor'))"/>
<xsl:apply-templates mode="inGroup" select=
"key('kEmpByDept', dept)[not(rank='Supervisor')]"/>
</div>
</xsl:template>
<xsl:template match="employee[rank='Manager']">
<div class="man">
<h1>Manager</h1>
<h2><xsl:value-of select="name"/></h2>
</div>
</xsl:template>
<xsl:template match="employee[rank='Supervisor']"
mode="inGroup">
<div class="super">
<h1>
<xsl:value-of select="concat(dept, ' Supervisor')"/>
</h1>
<h2><xsl:value-of select="name"/></h2>
</div>
</xsl:template>
<xsl:template match="employee" mode="inGroup">
<div>
<p class="name">
<xsl:value-of select="concat(dept, ' ', name)"/>
</p>
<p class="ID">
<xsl:value-of select="concat(dept, ' ', id)"/>
</p>
</div>
</xsl:template>
<xsl:template match="employee"/>
</xsl:stylesheet>
when applied on this XML document (similar to the provided one, but changed the names and Ids to be distinct):
<directory>
<employee>
<dept></dept>
<rank>Manager</rank>
<name>John Doe</name>
<id>1234</id>
</employee>
<employee>
<dept>Mechanical</dept>
<rank>Supervisor</rank>
<name>Jane Doe</name>
<id>4321</id>
</employee>
<employee>
<dept>Mechanical</dept>
<rank>General</rank>
<name>Joe Doe</name>
<id>2314</id>
</employee>
<employee>
<dept>Mechanical</dept>
<rank>General</rank>
<name>Jim Smith</name>
<id>2315</id>
</employee>
<employee>
<dept>Civil</dept>
<rank>Supervisor</rank>
<name>Ann Smith</name>
<id>4322</id>
</employee>
<employee>
<dept>Civil</dept>
<rank>General</rank>
<name>Peter Pan</name>
<id>2316</id>
</employee>
<employee>
<dept>Civil</dept>
<rank>General</rank>
<name>Mike Sims</name>
<id>2317</id>
</employee>
<employee>
<dept>Electrical</dept>
<rank>Supervisor</rank>
<name>Amy Dull</name>
<id>4323</id>
</employee>
<employee>
<dept>Electrical</dept>
<rank>General</rank>
<name>Dan Brown</name>
<id>2318</id>
</employee>
<employee>
<dept>Electrical</dept>
<rank>General</rank>
<name>John Kerry</name>
<id>2319</id>
</employee>
</directory>
produces the wanted, correct result:
<div id="directory">
<div class="man">
<h1>Manager</h1>
<h2>John Doe</h2>
</div>
<div class="group">
<div class="super">
<h1>Mechanical Supervisor</h1>
<h2>Jane Doe</h2>
</div>
<div>
<p class="name">Mechanical Joe Doe</p>
<p class="ID">Mechanical 2314</p>
</div>
<div>
<p class="name">Mechanical Jim Smith</p>
<p class="ID">Mechanical 2315</p>
</div>
</div>
<div class="group">
<div class="super">
<h1>Civil Supervisor</h1>
<h2>Ann Smith</h2>
</div>
<div>
<p class="name">Civil Peter Pan</p>
<p class="ID">Civil 2316</p>
</div>
<div>
<p class="name">Civil Mike Sims</p>
<p class="ID">Civil 2317</p>
</div>
</div>
<div class="group">
<div class="super">
<h1>Electrical Supervisor</h1>
<h2>Amy Dull</h2>
</div>
<div>
<p class="name">Electrical Dan Brown</p>
<p class="ID">Electrical 2318</p>
</div>
<div>
<p class="name">Electrical John Kerry</p>
<p class="ID">Electrical 2319</p>
</div>
</div>
</div>
and it displays in the browser as:
Manager
John Doe
Mechanical Supervisor
Jane Doe
Mechanical Joe Doe
Mechanical 2314
Mechanical Jim Smith
Mechanical 2315
Civil Supervisor
Ann Smith
Civil Peter Pan
Civil 2316
Civil Mike Sims
Civil 2317
Electrical Supervisor
Amy Dull
Electrical Dan Brown
Electrical 2318
Electrical John Kerry
Electrical 2319
Explanation: Muenchian method for grouping, and locating an employee (Manager or Supervisor) using a composite key (rank, department).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I communicate with a printer via USB using java in windows platform How can I communicate with a printer via USB using java in windows platform? I don't want to use JNI. I want to use jsr80 or libusb-win32 if any experienced have work with that please share his/her knowledge with some code. I think in libusb-win32 java wrapper must install some driver, correct? I don't want to use any driver. I want to designing my application like plug and play type device by which I can send file easily. I don't want to buy any software.
Is there any other way to communicate with printer?
A: To communicate with most usb devices a driver is required. In most cases though the driver should already be installed on the target pc unless this is a remote printing application. Also most printer drivers are free so you shouldn't need to buy anything.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: android ImageButton click I have just a little problem
in my layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:weightSum="1">
<ImageButton android:id="@+id/startLogo"
android:layout_height="230dp"
android:adjustViewBounds="true"
android:background="@drawable/whatelsecomics"
android:layout_width="230dp"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
in my activity I have
public class WhatelsecomicsActivity extends Activity {
private ImageButton whatelsecomics;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // your layout file name
whatelsecomics = (ImageButton) findViewById(R.id.startLogo); // your image button
// click event on your button
whatelsecomics.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent wecSeriesList = new Intent(WhatelsecomicsActivity.this, wecSeriesListActivity.class);
//Start next activity
WhatelsecomicsActivity.this.startActivity(wecSeriesList);
}
});
}
}
in my log
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): FATAL EXCEPTION: main
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): java.lang.RuntimeException: Unable to start activity ComponentInfo{zepod.whatelsecomics/zepod.whatelsecomics.WhatelsecomicsActivity}: java.lang.NullPointerException
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.os.Handler.dispatchMessage(Handler.java:99)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.os.Looper.loop(Looper.java:123)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at java.lang.reflect.Method.invokeNative(Native Method)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at java.lang.reflect.Method.invoke(Method.java:507)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at dalvik.system.NativeStart.main(Native Method)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): Caused by: java.lang.NullPointerException
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at zepod.whatelsecomics.WhatelsecomicsActivity.onCreate(WhatelsecomicsActivity.java:21)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-23 21:31:05.081: ERROR/AndroidRuntime(3805): ... 11 more
Anyone can say me why?
A: If you're using Eclipse, click Project->Clean... (and rebuild it if you don't have it automatically doing so). The usual cause of problems like this is the R file isn't properly generated so that rebuilds the project to generate it again.
A: You have NullPointerException on WhatelsecomicsActivity.java:21
What line is that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to correctly read Javascript hash in custom affiliate URL? I'm creating a custom affiliate program. I want my links to be as SEO friendly as possible, so I will use a Javascript hash appended to the URL to send the affiliate id, read the affiliate id, store the click, and then 301 re-direct to the page they were linked too. That way we have no canonical issues whatsoever, and every affiliate link passes link juice!
Now, how would I read the following URL?
www.mydomain.com/seo-friendly-url#ref=john
After getting the hash value for ref and adding the click, how would I then 301 re-direct the user back to
www.mydomain.com/seo-friendly-url
Any help is greatly appreciated!
A: Fragment identifiers (the part after the #) are not sent to the server, so they cannot be read by anything that could then emit an HTTP response (which you need for a 301 redirect).
A: The "hash" portion of a URL is not passed to the server, so you will not be able to utilize this data for any server-side redirection or processing directly. However, it is possible to grab the hash on page load and pass it on to the server via AJAX or redirection:
To immediately redirect a user from www.mydomain.com/seo-friendly-url#ref=john to www.mydomain.com/seo-friendly-url/ref/john
if (window.location.hash.match(/#ref=/))
window.location = window.location.href.replace('#ref=', '/ref/')
... but then, why not have just used www.mydomain.com/seo-friendly-url/ref/john to begin with and save the extra leg work? The other route, through AJAX, involves reading the value of the hash after the page has loaded and sending that off to the server to be recorded.
(note: this code uses a generic cross-browser XMLHTTPRequest to send an AJAX GET request. replace with your library's implementation [if you are using a library])
window.onload = function () {
// grab the hash (if any)
var affiliate_id = window.location.hash;
// make sure there is a hash, and that it starts with "#ref="
if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
// clear the hash (it is not relevant to the user)
window.location.hash = '';
// initialize an XMLRequest, send the data to affiliate.php
var oXMLHttpRequest = new XMLHttpRequest;
oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
oXMLHttpRequest.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
// do anything else that needs to be done after recording affiliate
}
}
oXMLHttpRequest.send(null);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error recording to movie file with AVFoundation This is a strange problem. I have not changed any code involving this in my project but my video recording has randomly stopped working. When I try to save to a movie to a file I get the following error:
Error Domain=NSOSStatusErrorDomain Code=-12780 "The operation couldn’t be completed. (OSStatus error -12780.)"
I start my capture with the following code:
- (void)initVideoCapture {
self.captureSession = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoCaptureDevice = [self frontFacingCameraIfAvailable];
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoCaptureDevice error:nil];
[self.captureSession addInput:videoInput];
aMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
[self.captureSession addOutput:aMovieFileOutput];
[self detectVideoOrientation:aMovieFileOutput];
[self.captureSession setSessionPreset:AVCaptureSessionPresetMedium];
[self.captureSession startRunning];
}
I then call this method from the viewController to start recording:
- (void) startRecord {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *newDateString = [outputFormatter stringFromDate:[NSDate date]];
[outputFormatter release];
NSString * fileString = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",newDateString]];
recordFileURL = [[NSURL alloc] initFileURLWithPath:fileString];
[aMovieFileOutput startRecordingToOutputFileURL:recordFileURL recordingDelegate:self];
}
At this time I get the error in this function.
*
*(void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections error:(NSError *)error
What is really weird is that it randomly works sometimes. Like, I will compile the project and it will work 100% of the time. Next time I compile it will work 0%. What could I be doing wrong? Anything obvious?
A: I've gotten -12780 when the orientation of the device was UIDeviceOrientationFaceUp, UIDeviceOrientationFaceDown and UIDeviceOrientationUnknown. Since a recoded video's orientation has to be portrait or landscape, it'll error out on you. I had to write a quick method that checks for those three, and just translates them to portrait.
A: this seems to be a bug with apple. i solved it by using AVAssetWriter and AVAssetWriterInput
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can one make internal links work within a client-side-generated HTML page? Situation: for various reasons (mainly, that it will be used at times in situations where the Internet is not availble), some JavaScript-heavy HTML I am building has to be able to run at times strictly on the client, with no server involved. For the most part, I've been able to come up with workarounds that allow pages from this site to be saved by the usual browser 'Save Page As' mechanisms, embed all the pieces they need, and massage paths to refer where I want them to (on the local machine) when the browser isn't smart enough to fix the URL (which is more often than I might have thought).
One piece I haven't been able to solve yet, though: each main page can open a help page in a new tab/window. To do that, I embed the content of the help page in the main saved page. Then I can use helpWindow.document.write(helpContent) to open that. Problem: as far as the browser is concerned, the help page ends up with the same URL as the original page, so I can't effectively use page-internal links on that page: it tries to load the main saved page if you click one!
For example: <a name="target" /> ... <a href="#target">link</a> in the help page: if you click "link", the browser loads the main saved page, rather scrolling the help page.
My temporary workaround is to strip these links when I have to operate in this environment, but I'd sure rather have a way to make them work. Any suggestions? Suggestions could include an entirely different way to open a help page. I'd rather not use iframes, though, I'd really like it to stay in a separate tab/window.
A: You should read this: http://en.wikipedia.org/wiki/Single-page_application
In particular try: http://en.wikipedia.org/wiki/TiddlyWiki
(Sorry, that this doesn't answer your question, but if you have not see those, maybe you can get ideas from them.)
Edit:
I tried this out a bit, and that's really strange! It almost seems like a bug to me. Do all browsers do this?
A solution could be to use ID instead of A NAME (which BTW you can/should do even if you wanted to link by anchor fragment) and then use
document.getElementById(elID).scrollIntoView();
To jump to the element.
A: You can scroll to the bookmark with JavaScript with element.scrollIntoView():
function goToBookmark(e)
{
e = e || window.event;
if (e.preventDefault)
{
e.preventDefault();
}
e.returnValue = false;
var bookmarkName = this.href.replace(/^#/, "");
var bookmark = document.getElementsByName(bookmarkName)[0];
if (bookmark)
{
bookmark.scrollIntoView();
}
}
for (var i = 0; i < document.links.length; i++)
{
var link = document.links[i];
if (/^#/.test(link.href))
{
link.onclick = goToBookmark;
}
}
Or, if you are using jQuery:
$("a[href^='#']").click(function(e) {
e.preventDefault();
var bookmark = $("a[name=" + this.href.replace(/^#/, "") + "]")[0];
if (bookmark) {
bookmark.scrollIntoView();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: X marks along the direction I have never worked with Google maps API.
For the school project I am working on; I need to get a direction between two locations (this is easy part and I think I can do this),
However I also need to put an X mark; at every 10 miles along the way.
Is this even possible?
Thank You.
A: Ok, here's a working solution that draws markers every 200 miles (I was working on big distances to check it worked on geodesic curved lines, which it does). To make this work for you, just change all the coordinates, and change 200 to 10
<!DOCTYPE html>
<html>
<head>
<title>lines with markers every x miles</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<!--- need to load the geometry library for calculating distances, see http://www.svennerberg.com/2011/04/calculating-distances-and-areas-in-google-maps-api-3/ --->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var startLatlng = new google.maps.LatLng(54.42838,-2.9623);
var endLatLng = new google.maps.LatLng(52.908902,49.716793);
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(51.399206,18.457031),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var startMarker = new google.maps.Marker({
position: startLatlng,
map: map
});
var endMarker = new google.maps.Marker({
position: endLatLng,
map: map
});
// draw a line between the points
var line = new google.maps.Polyline({
path: [startLatlng, endLatLng],
strokeColor: "##FF0000",
strokeOpacity: 0.5,
strokeWeight: 4,
geodesic: true,
map: map
});
// what's the distance between these two markers?
var distance = google.maps.geometry.spherical.computeDistanceBetween(
startLatlng,
endLatLng
);
// 200 miles in meters
var markerDistance = 200 * 1609.344;
var drawMarkers = true;
var newLatLng = startLatlng;
// stop as soon as we've gone beyond the end point
while (drawMarkers == true) {
// what's the 'heading' between them?
var heading = google.maps.geometry.spherical.computeHeading(
newLatLng,
endLatLng
);
// get the latlng X miles from the starting point along this heading
var newLatLng = google.maps.geometry.spherical.computeOffset(
newLatLng,
markerDistance,
heading
);
// draw a marker
var newMarker = new google.maps.Marker({
position: newLatLng,
map: map
});
// calculate the distance between our new marker and the end marker
var newDistance = google.maps.geometry.spherical.computeDistanceBetween(
newLatLng,
endLatLng
);
if (newDistance <= markerDistance) {
drawMarkers = false;
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Force MP3 files to download instead of opening in the browser with Quicktime OK I have a website that serves podcasts in MP3 format. There is a .htaccess that routes requests for MP3 files to a download script, and that is as follows:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule (.*.mp3)$ download.php?file=$1
</IfModule>
The PHP download script is as follows:
$filename = (isset($_REQUEST['file']) ? $_REQUEST['file'] : '');
$filesize = @filesize($filename);
if ($filename == '' || $filesize == 0) exit(0);
header("Content-Type: audio/mpeg");
header("Content-Description: {$filename}");
header("Content-length: {$filesize}");
header("Content-Disposition: attatchment; filename={$filename}");
readfile($filename);
Everything works beautifully on PC, and in most Mac browsers. However, on Safari, Quicktime is intercepting the download. Same thing is happening on iPhone and iPad. Since the target audience is likely to be mostly Apple users, I would like the "Download" button to do just that -- download, not play in the browser with the Quicktime plugin, regardless of device. The "Stream" button can play the file in the browser, but not the "Download" button.
Doing a Right-click (or Cmd+Click) and Save File As... is not acceptable.
Is there any way to do force download across all platforms with PHP, HTTP, HTML, etc. that doesn't require the user to do anything except click the Download button?
A: You need to set the content-disposition HTTP header when serving the file. By setting this HTTP header it will instruct the browser to provide a prompt which lets the user save or open the file. You can find more information here:
http://support.microsoft.com/kb/260519
A: You can divide your streams and downloads in two separate folders in combination with the following:
"If you want to force all files in a directory to download, create a .htaccess file in that directory, then paste this in it:
## force all file types to download if they are in this directory:
ForceType application/octet-stream
Don’t stick this in your root level .htaccess file. It will cause all the files on your server to download."
You can read more about this in this conversation:
https://css-tricks.com/snippets/htaccess/force-files-to-download-not-open-in-browser/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NoMethodError in Users#new I started getting this error:
NoMethodError: undefined method `has_key?' for nil:NilClass
in the process of nearly finishing Hartl's excellent Rails Tutorial. It looks like I must have left out a method, but I have idea where, and am new to debugging in Rails.
Here's the full stack trace:
activerecord (3.0.9) lib/active_record/attribute_methods/read.rb:80:in `id'
activerecord (3.0.9) lib/active_record/attribute_methods/primary_key.rb:9:in `to_key'
actionpack (3.0.9) lib/action_controller/record_identifier.rb:82:in `record_key_for_dom_id'
actionpack (3.0.9) lib/action_controller/record_identifier.rb:63:in `dom_id'
actionpack (3.0.9) lib/action_view/helpers/form_helper.rb:331:in `apply_form_for_options!'
actionpack (3.0.9) lib/action_view/helpers/form_helper.rb:313:in `form_for'
app/views/users/new.html.erb:3:in `_app_views_users_new_html_erb___834068491__620833808_0'
actionpack (3.0.9) lib/action_view/template.rb:135:in `send'
actionpack (3.0.9) lib/action_view/template.rb:135:in `render'
activesupport (3.0.9) lib/active_support/notifications.rb:54:in `instrument'
actionpack (3.0.9) lib/action_view/template.rb:127:in `render'
actionpack (3.0.9) lib/action_view/render/rendering.rb:59:in `_render_template'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.9) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.9) lib/action_view/render/rendering.rb:56:in `_render_template'
actionpack (3.0.9) lib/action_view/render/rendering.rb:26:in `render'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:115:in `_render_template'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:109:in `render_to_body'
actionpack (3.0.9) lib/action_controller/metal/renderers.rb:47:in `render_to_body'
actionpack (3.0.9) lib/action_controller/metal/compatibility.rb:55:in `render_to_body'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:102:in `render_to_string'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:93:in `render'
actionpack (3.0.9) lib/action_controller/metal/rendering.rb:17:in `render'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:40:in `render'
activesupport (3.0.9) lib/active_support/core_ext/benchmark.rb:5:in `ms'
/usr/lib/ruby/1.8/benchmark.rb:308:in `realtime'
activesupport (3.0.9) lib/active_support/core_ext/benchmark.rb:5:in `ms'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:40:in `render'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:78:in `cleanup_view_runtime'
activerecord (3.0.9) lib/active_record/railties/controller_runtime.rb:15:in `cleanup_view_runtime'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:39:in `render'
actionpack (3.0.9) lib/action_controller/metal/implicit_render.rb:10:in `default_render'
actionpack (3.0.9) lib/action_controller/metal/mime_responds.rb:261:in `retrieve_response_from_mimes'
actionpack (3.0.9) lib/action_controller/metal/mime_responds.rb:192:in `call'
actionpack (3.0.9) lib/action_controller/metal/mime_responds.rb:192:in `respond_to'
app/controllers/users_controller.rb:29:in `new'
actionpack (3.0.9) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.9) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.9) lib/abstract_controller/base.rb:150:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/rendering.rb:11:in `process_action'
actionpack (3.0.9) lib/abstract_controller/callbacks.rb:18:in `process_action'
activesupport (3.0.9) lib/active_support/callbacks.rb:436:in `_run__434435962__process_action__943997142__callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:410:in `send'
activesupport (3.0.9) lib/active_support/callbacks.rb:410:in `_run_process_action_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `send'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
actionpack (3.0.9) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.9) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/rescue.rb:17:in `process_action'
actionpack (3.0.9) lib/abstract_controller/base.rb:119:in `process'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:41:in `process'
actionpack (3.0.9) lib/action_controller/metal.rb:138:in `dispatch'
actionpack (3.0.9) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.0.9) lib/action_controller/metal.rb:178:in `action'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:62:in `call'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:27:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:103:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:493:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.3) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:302:in `call'
activerecord (3.0.9) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.9) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.9) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.9) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.9) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.9) lib/active_support/callbacks.rb:416:in `_run_call_callbacks'
actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.3) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.0.9) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.3) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.9) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `synchronize'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/static.rb:30:in `call'
railties (3.0.9) lib/rails/application.rb:168:in `call'
railties (3.0.9) lib/rails/application.rb:77:in `send'
railties (3.0.9) lib/rails/application.rb:77:in `method_missing'
railties (3.0.9) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.3) lib/rack/content_length.rb:13:in `call'
rack (1.2.3) lib/rack/handler/webrick.rb:52:in `service'
/usr/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/usr/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/usr/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/usr/lib/ruby/1.8/webrick/server.rb:162:in `start'
/usr/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/usr/lib/ruby/1.8/webrick/server.rb:95:in `start'
/usr/lib/ruby/1.8/webrick/server.rb:92:in `each'
/usr/lib/ruby/1.8/webrick/server.rb:92:in `start'
/usr/lib/ruby/1.8/webrick/server.rb:23:in `start'
/usr/lib/ruby/1.8/webrick/server.rb:82:in `start'
rack (1.2.3) lib/rack/handler/webrick.rb:13:in `run'
rack (1.2.3) lib/rack/server.rb:217:in `start'
railties (3.0.9) lib/rails/commands/server.rb:65:in `start'
railties (3.0.9) lib/rails/commands.rb:30
railties (3.0.9) lib/rails/commands.rb:27:in `tap'
railties (3.0.9) lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6
I can see that the error is because a User is not getting created during the signin process.
So I went into the console, and just tried to create a User; here's the error stack from that:
from script/rails:6irb(main):004:0> user=User.new
NoMethodError: undefined method `has_key?' for nil:NilClass
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/base.rb:1512:in `has_attribute?'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/base.rb:1672:in `inspect'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/base.rb:1671:in `collect'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/base.rb:1671:in `inspect'
from /usr/lib/ruby/1.8/irb.rb:310:in `output_value'
from /usr/lib/ruby/1.8/irb.rb:159:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:271:in `signal_status'
from /usr/lib/ruby/1.8/irb.rb:155:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:154:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:71:in `start'
from /usr/lib/ruby/1.8/irb.rb:70:in `catch'
from /usr/lib/ruby/1.8/irb.rb:70:in `start'
from /usr/lib/ruby/gems/1.8/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
from /usr/lib/ruby/gems/1.8/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
from /usr/lib/ruby/gems/1.8/gems/railties-3.0.9/lib/rails/commands.rb:23
from script/rails:6:in `require'
I'm using Rails 3.0.9. If anyone can point me in the right direction, sure would appreciate it!
thanks,
rick
Additional post (9/27/11):
to help my commenters --
yes, I've migrated my database.
where I'm at in the Tutorial: I've basically finished the tutorial, but differed from how it coded up Users, but using a scaffold instead of the incremental approach that Hartl takes.
here's users/new.html.erb:
<h1>New user</h1>
<%= form_for(@user) do |f| %>
<div class="field">
<%= f.label :firstname, "First Name" %><br />
<%= f.text_field :firstname %>
</div>
<div class="field">
<%= f.label :lastname, "Last Name" %><br />
<%= f.text_field :lastname %>
</div>
<div class="field">
<%= f.label :username %><br />
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation, "Confirmation" %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
<%= link_to 'Back', users_path %>
Where I think is causing my bug is that a user object does not get created by the model, for some reason; and that's why I get the 'nil object' error.
Any help much appreciated!
--rick
A: Welcome to Rails and to debugging a Rails program.
Some general debugging tips.
*
*While the nil object does have a number of methods, it is obviously not an ActiveRecord object and thus doesn't have the has_key? method.
*So the problem (as you surmised) is that the method that should return an ActiveRecord object is returning nil instead.
*So next is to figure out why. Since you're trying to create the ActiveRecord object it may well be that the object is not passing its validations. Check this by using valid? before saving. Or use save! instead of save The save! method will throw an error if the save operation doesn't succeed.
*Learn how to use the logging statement to send log messages to the log file as you debug.
*You can also use the interactive debugger. It can be set up so it'll be invoked when the browser's request reaches a particular line of code in the server. -- The browser will sit with an hour-glass until you "continue" within the debugger.
Added Debugging validations
To debug validations, I use a couple of techniques:
*
*Don't try to use the debugger to follow the execution of the validations--as you've seen, that's a mug's game.
*Do use the debugger to invoke the save or valid? method on the AR object. You can then inspect the object or use a method to view the error object that is contained within the AR object. The error object will often tell you which validation failed.
*You can also individually comment out validations until you find the one that is giving you a problem.
*You can also use the debugger to examine the attributes of the AR object to see whether the attribute values will pass validation or not.
*Re: when do validations run (as you ask in your comment). Do remember that by default, validations will run on create as well as update calls. If you want an individual validation to only be checked on update (not on create), there are several ways to do that, check the docs for the individual validation.
There's more to say about validations. If you have a specific validation that fails and you don't understand why it is failing, then open a separate question in SO.
Re: why do validations have to be passed on creation, not just updates -- that's a feature. It enables you to assure yourself that only valid objects are being created in the db. But you don't have to use it. You can set validations to only be active on Update.
Validations are a powerful, sophisticated part of ActiveRecord. In other words, they can be complicated until they're understood.
A: Maybe on your User model you were creating an initialize method that overrode ActiveRecord:Base
script/console
class User < ActiveRecord:Base
def initialize
end
end
User.new
=> NoMethodError: undefined method `has_key?' for nil:NilClass
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to restrict motion to vertical in box2d I have a box2d body that has a fixture of a ball. It just bounces up and down on top of a rectangular box. Sometimes it will fall off of the box for no apparent reason. I there a way to restrict gravity to only vertical so that I can solve this problem?
A: Or you could use a prismatic joint. Check out this video.
A: Use b2LineJoint to allow your body to move in one direction only
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamically adding child field on form as described in Railscast 197 does not use :child_index parameter to generate html name attribute I have an application where I am trying to add records as shown in the Railscast number 197. My objects are more simple, as I only have one level of Parent/child relationships: Patients and events. The code works fine for removing a child record (events), but adding a record fails for the following reason. I am able to create a new Object, generate the fields to display on the form, and the form looks ok. However the :child_index is missing from the name attribute in the generated html. An example of the html generated is:
<textarea cols="30" id="patient_events_attributes_description" name="patient[events_attributes][description]" rows="3"></textarea>
The html of an existing record is:
<textarea cols="30" id="patient_events_attributes_1_description" name="patient[events_attributes][1][description]" rows="3">Opgepakt met gestolen goederen</textarea>
Note that the [1] in the existing record is missing in the new html. Of course it should not be 1, but new_xxx which is then replaced by a unique number. But the whole [new_xxx] is missing in the generated html. Does anyone have an idea of what is wrong?
I am using Ruby 1.9.2, with Rails 3.0.10. I have only JQuery with no prototype, or query-ujs.
The code I'm using is shown here below, but it is a copy of the Railscast code:
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| # new_#{association}
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
function remove_fields(link) {
$(link).prev("input[type=hidden]").val = "1";
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
alert(content);
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).before(content.replace(regexp, new_id));
}
i haven't been able to find any other comments that this code does not work, so I must be doing something very wrong. Any ideas out there?
A: After looking at the source code for fields_for, I found the two problems:
1. The :child_index parameter is not used, instead of that the :index option is used.
2. fields_for only generates the correct html if the object passed is an active record object, or an array. I changed the parameter passed to type array, with the new blank object as the [0] entry.
It is remarkable that there is no documentation of this feature. It makes ROR very time consuming to use, unless you were born there.
The code that finally works is as follows. Note that the '99' must be replace with a unique number if more records are to be added.
I still haven't go it completely working as the @patient.update_attributes(params[:patient]) gives some errors, but the worst part (adding the html) is fixed.
def link_to_add_fields(name, g, association)
new_object = []
new_object[0] = g.object.class.reflect_on_association(association).klass.new
fields = g.fields_for(association, new_object, :index => '99') do |builder| # , {:child_index => "new_#{association}"} new_#{association}
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to post file to remote url? I followed another question about posting a file to a remote url: Upload files with HTTPWebrequest (multipart/form-data)
It is making the remote url crash in my HttpHandler with: "Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'." Is the method posting the right file data, or is it posting just a string?
This is the method that is used to post the file to the remote server:
public void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
Response.Write(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
var rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
var stream2 = wresp.GetResponseStream();
var reader2 = new StreamReader(stream2);
Response.Write(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
Response.Write("Error uploading file: " + ex.Message);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
This is the HttpHandler on the remote server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
namespace SitefinityWebApp.Widgets.Files
{
public class UploadFileHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//VALIDATE FILES IN REQUEST
if (context.Request.Files.Count > 0)
{
try
{
//HANDLE EACH FILE IN THE REQUEST
foreach (HttpPostedFile item in context.Request.Files)
{
item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName));
context.Response.Write("File uploaded");
}
}
catch (Exception ex)
{
//NO FILES IN REQUEST TO HANDLE
context.Response.Write("Error: " + ex.Message);
}
}
else
{
//NO FILES IN REQUEST TO HANDLE
context.Response.Write("No file uploaded");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
And this is how you use the HttpUploadFile method:
var nvc = new NameValueCollection();
nvc.Add("user", userName);
nvc.Add("password", password);
nvc.Add("library", libraryName);
HttpUploadFile(destinationUrl, uploadFile, "file", "image/png", nvc);
A: Iterating through the HttpFileCollection will return only the file keys. So you have to change your HTTP handler as follow:
//HANDLE EACH FILE IN THE REQUEST
foreach (string key in context.Request.Files)
{
HttpPostedFile item = context.Request.Files[key];
item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName));
context.Response.Write("File uploaded");
}
Hope, this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: css selector specificity conflicts due to multiple stylesheets Ok, I've been reading through stackoverflow css selectors. on the thread here what is the differences in this syntax? What does the ^= mean? What is it selecting? all?
[class^='Rating']
and
div.Rating0_5
Also, there's a statement here that reads:
Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.
What does that mean?
I'm asking because I'm having to clean up alot of CSS code on a website. There are over a dozen stylesheets each containing 200+ lines of code, and there are styles that are overriding each other among the stylesheets, maybe even within them if repeated occurences increase specificity. It's painstaking to go line by line through the stylesheets to find out what particular class, div, etc is over-riding another and some of the specificity is seven selectors deep! It's almost impossible for me and very stressful.
Is there a tool to use that will target styles overwriting other styles? Is it easy to use and what does it do exactly? If not, how can I write my CSS with enough specificity without having extremely long selectors to hopefully ensure uniqueness so that they will not be overwritten by another stylesheet of rules?
Thanks, I hope this makes some sense and someone has had this experience.
A: ^= is "starts with" for CSS selector. In your case it will apply to classes with names starting with "rating".
With traditional CSS you do have to make really long selectors to be specific and I think the statement meant you can have duplicate selector and the styling will be combined.
In terms of cleaning up the CSS I don't have a good suggestion for an automated tool but you can take a look at http://sass-lang.com/ (SCSS) for a better syntax layer on top of CSS that does variable and inheritance of selectors. Does clean up CSS a lot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to include resource file in program I was trying ICZELION's tutorials and this is my asm program:
.386
.model flat,stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\masm32.inc
include \masm32\include\user32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\user32.lib
.data
ClassName BYTE "Name of Class",0
MenuName BYTE "Name of Menu",0
TestPrompt BYTE "Test",0
GoodByePrompt BYTE "Good Bye!",0
HelloPrompt BYTE "Hello",0
AppName BYTE "Name Of App",0
.data?
.const
IDM_TEST equ 1
IDM_HELLO equ 2
IDM_GOODBYE equ 3
IDM_EXIT equ 4
.code
main PROC
push SW_SHOWDEFAULT
call GetCommandLine
push eax
push NULL
push NULL
call GetModuleHandle
push eax
call WinMain
push eax
call ExitProcess
main ENDP
WinMain PROC
;[ebp+014h]CmdShow
;[ebp+010h]commandline
;[ebp+0Ch]hPrevInstance
;[ebp+08h]hInstance
push ebp
mov ebp, esp
add esp, 0FFFFFFB0h
mov DWORD PTR [ebp-030h], SIZEOF WNDCLASSEX
mov DWORD PTR [ebp-02Ch], CS_HREDRAW or CS_VREDRAW
mov DWORD PTR [ebp-028h], OFFSET WinProc
mov DWORD PTR [ebp-024h], NULL
mov DWORD PTR [ebp-020h], NULL
push DWORD PTR [ebp+08h]
pop DWORD PTR [ebp-0Ch]
push IDI_APPLICATION
push NULL
call LoadIcon
mov DWORD PTR [ebp-018h], eax
mov DWORD PTR [ebp-04h], eax
push IDC_ARROW
push NULL
call LoadCursor
mov DWORD PTR [ebp-014h], eax
mov DWORD PTR [ebp-010h], COLOR_WINDOW
mov DWORD PTR [ebp-0Ch], OFFSET MenuName
mov DWORD PTR [ebp-08h], OFFSET ClassName
lea eax, DWORD PTR [ebp-030h]
push eax
call RegisterClassEx
push NULL
push [ebp+08h]
push NULL
push NULL
push 400
push 400
push 200
push 200
push WS_OVERLAPPEDWINDOW
push OFFSET AppName
push OFFSET ClassName
push NULL
call CreateWindowEx
mov [ebp-050h], eax
;display and update the window
push [ebp+014h]
push [ebp-050h]
call UpdateWindow
push [ebp-050h]
call ShowWindow
_MessageLoop:
push NULL
push NULL
push [ebp-050h]
push [ebp-04Ch]
call GetMessage
cmp eax, 0FFFFFFFFh
je _ExitMessageLoop
lea eax, DWORD PTR [ebp-04Ch]
push eax
call TranslateMessage
lea eax, DWORD PTR [ebp-04Ch]
push eax
call DispatchMessage
jmp _MessageLoop
_ExitMessageLoop:
mov eax, [ebp-044h]
mov esp,ebp
pop ebp
ret 010h
WinMain ENDP
WinProc PROC
;[ebp+014h]lParam
;[ebp+010h]wParam
;[ebp+0Ch]uMsg
;[ebp+08h]hWnd
push ebp
mov ebp, esp
cmp DWORD PTR[ebp+0ch], WM_DESTROY
je _WMDESTROY
cmp DWORD PTR [ebp+0Ch], WM_COMMAND
je _WMCOMMAND
_WMDESTROY:
push NULL
call PostQuitMessage
_WMCOMMAND:
mov eax, [ebp+0Ch]
cmp al, IDM_TEST
je _test
cmp al, IDM_HELLO
je _hello
cmp al, IDM_GOODBYE
je _goodbye
cmp al, IDM_EXIT
je _exit
jmp _ExitWmCommand
_test:
push MB_OK
push OFFSET AppName
push OFFSET TestPrompt
push NULL
call MessageBox
jmp _ExitWmCommand
_hello:
push MB_OK
push OFFSET AppName
push OFFSET HelloPrompt
push NULL
call MessageBox
jmp _ExitWmCommand
_goodbye:
push MB_OK
push OFFSET AppName
push OFFSET GoodByePrompt
push NULL
call MessageBox
jmp _ExitWmCommand
_exit:
push [ebp+08h]
call DestroyWindow
_ExitWmCommand:
push DWORD PTR [ebp+014h]
push DWORD PTR [ebp+010h]
push DWORD PTR [ebp+0Ch]
push DWORD PTR [ebp+08h]
call DefWindowProc
xor eax, eax
pop ebp
ret 010h
WinProc ENDP
END main
Here is my resource file, mainprog.rc:
#define IDM_TEST 1
#define IDM_HELLO 2
#define IDM_GOODBYE 3
#define IDM_EXIT 4
FirstMenu MENU
{
POPUP "&PopUp"
{
MENUITEM "&SayHello", IDM_HELLO
MENUITEM "&SayGoodBye",IDM_GOODBYE
MENUITEM SEPARATOR
MENUITEM "&Exit",IDM_EXIT
}
MENUITEM "&Test", IDM_TEST
}
I'm unable to include the resource file in the program.
What i do is run an ml on the main asm file, then an rc on the resource file and then link them together. The program assembles normally, but when i run the program, it crashes. On debugging, i found that windows could not find the resource data.
Devjeet
A: The problem is that the MenuName in your .asm is defined as:
MenuName BYTE "Name of Menu",0
But in your resource file it's called 'FirstMenu'.
I suspect that, if you were to change that to:
MenuName BYTE "FirstMenu"
as shown in the example at http://win32assembly.online.fr/tut8.html, the program will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Casting and Performance in C# I'm writing a code that selects data from a database, store it in a DataTable, do some hard math, and updates the database back.
The main issue is that it requires a lot of casting due to DataRow collections returns columns as the object type, forcing me to do float.parse() every single row and making it time-consuming.
Do you guys have any suggestions on how I can avoid this?
Thanks in advance.
A: float.Parse is not the same as casting. You should be able to actually cast the value, e.g. one of
(float) row["Foo"]
(double) row["Foo"]
(decimal) row["Foo"]
depending on the type. That will avoid doing any reparsing - you're just unboxing. You may need to unbox and cast if the value isn't in the type you want, e.g.
(float) (double) row["Foo"]
It's unclear exactly how you're using the DataTable, but I would suggest creating your own model class which represents a row of a table in a strongly-typed way, with conversions to and from DataRow - or use a strongly-typed DataSet to start with. That way your code will be a lot clearer, and you'll only need to perform conversions for a small part of your code.
A:
forcing me to do float.parse() every single row
If you need float.parse(), you're doing something wrong somewhere. You should be storing the column in numeric type (float, numeric, decimal, money, etc) rather than a string type (char, varchar, nvarchar, etc), and if you're doing that the value in the datarow column already is a type such that you can use a simple (float) cast (and maybe a check for DBNull).
float.parse() is doubly bad, because not only do you have to parse the value from a string, but you have to first create the string to parse... you're paying for this twice.
A: If your database returns floats, you don't have to use float.parse. Assuming you have a DataRow row, you can just use something like this:
float val = (float)row["column"];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Chrome closing connection on handshake with Java SSL Server There are several questions that are similar to this, but none address this specific issue. If there is one and I missed it, please direct me to the relevant solution.
Now for my issue. I wrote a test SSL Server in Java:
import java.io.FileInputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
public class Server {
public static void main(String[] args) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("server.jks"), "123456".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "123456".toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory factory = context.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(8443);
SSLSocket socket = null;
OutputStream out = null;
while (true) {
try {
System.out.println("Trying to connect");
socket = (SSLSocket) serverSocket.accept();
socket.startHandshake();
out = socket.getOutputStream();
out.write("Hello World".getBytes());
out.flush();
} catch (SSLHandshakeException e) {
e.printStackTrace();
continue;
} finally {
if (socket != null) {
socket.close();
}
}
}
}
}
And I created my key store like so:
keytool -genkey -keyalg RSA -alias server-keys -keystore server.jks
When prompted, I put localhost for the key name.
Then I compile (I am using Sun/Oracle JDK and JRE version 1.6.0_26):
javac Server.java
Then I run:
java Server
I then tested by navigating to https://localhost:8443
It worked like a charm in the following browsers:
*
*Firefox
*Opera
*Mobile Safari (iPhone4)
*Safari
However, when I tried it with Chrome, I got the expected self-signed cert notification, I accepted the cert, I get this:
This webpage is not available
The connection to localhost was interrupted.
Here are some suggestions:
Reload this webpage later.
Check your Internet connection. Restart any router, modem, or other network devices you may be using.
Add Google Chrome as a permitted program in your firewall's or antivirus software's settings. If it is already a permitted program, try deleting it from the list of permitted programs and adding it again.
If you use a proxy server, check your proxy settings or contact your network administrator to make sure the proxy server is working. If you don't believe you should be using a proxy server, adjust your proxy settings: Go to the wrench menu > Preferences > Under the Hood > Change Proxy Settings... and make sure your configuration is set to "no proxy" or "direct."
Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.
So, what gives? Is this a problem with Java, Chrome, or my implementation?
Any help in getting this working with Chrome as a client will be greatly appreciated.
Here is the Stack Trace for the error:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:817)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1149)
at Server.main(Server.java:32)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:333)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
... 4 more
The message from Chrome makes it seem that the server closed the connection too early, while the stack trace from the server makes it seem that Chrome closed the connection prematurely.
Update: I whipped up a non-SSL server in Java and tested it with Chrome, and it works just fine. The real problem seems to be that somehow the connection is getting lost during the SSL handshake. Does anyone have any suggestions about how to fix this?
If you have suggestions for code improvement or anything that might help, don't be shy. Thanks in advance.
Update: Here is the output from java -Djavax.net.debug=all Server
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
[Raw read]: length = 5
0000: 16 03 01 00 B0 .....
[Raw read]: length = 176
0000: 01 00 00 AC 03 01 4E 82 02 10 A6 FF DD 15 5E 3F ......N.......^?
0010: 6E 00 75 43 BD AB 02 67 B7 D3 F8 9A C7 58 85 E2 n.uC...g.....X..
0020: 99 65 73 67 37 91 00 00 48 C0 0A C0 14 00 88 00 .esg7...H.......
0030: 87 00 39 00 38 C0 0F C0 05 00 84 00 35 C0 07 C0 ..9.8.......5...
0040: 09 C0 11 C0 13 00 45 00 44 00 66 00 33 00 32 C0 ......E.D.f.3.2.
0050: 0C C0 0E C0 02 C0 04 00 96 00 41 00 04 00 05 00 ..........A.....
0060: 2F C0 08 C0 12 00 16 00 13 C0 0D C0 03 FE FF 00 /...............
0070: 0A 02 01 00 00 3A 00 00 00 0E 00 0C 00 00 09 6C .....:.........l
0080: 6F 63 61 6C 68 6F 73 74 FF 01 00 01 00 00 0A 00 ocalhost........
0090: 08 00 06 00 17 00 18 00 19 00 0B 00 02 01 00 00 ................
00A0: 23 00 00 33 74 00 00 00 05 00 05 01 00 00 00 00 #..3t...........
main, READ: TLSv1 Handshake, length = 176
*** ClientHello, TLSv1
RandomCookie: GMT: 1300365840 bytes = { 166, 255, 221, 21, 94, 63, 110, 0, 117, 67, 189, 171, 2, 103, 183, 211, 248, 154, 199, 88, 133, 226, 153, 101, 115, 103, 55, 145 }
Session ID: {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x88, Unknown 0x0:0x87, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x84, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x45, Unknown 0x0:0x44, SSL_DHE_DSS_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x96, Unknown 0x0:0x41, SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods: { 1, 0 }
Unsupported extension server_name, [host_name: localhost]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension status_request, data: 01:00:00:00:00
***
[read] MD5 and SHA1 hashes: len = 176
0000: 01 00 00 AC 03 01 4E 82 02 10 A6 FF DD 15 5E 3F ......N.......^?
0010: 6E 00 75 43 BD AB 02 67 B7 D3 F8 9A C7 58 85 E2 n.uC...g.....X..
0020: 99 65 73 67 37 91 00 00 48 C0 0A C0 14 00 88 00 .esg7...H.......
0030: 87 00 39 00 38 C0 0F C0 05 00 84 00 35 C0 07 C0 ..9.8.......5...
0040: 09 C0 11 C0 13 00 45 00 44 00 66 00 33 00 32 C0 ......E.D.f.3.2.
0050: 0C C0 0E C0 02 C0 04 00 96 00 41 00 04 00 05 00 ..........A.....
0060: 2F C0 08 C0 12 00 16 00 13 C0 0D C0 03 FE FF 00 /...............
0070: 0A 02 01 00 00 3A 00 00 00 0E 00 0C 00 00 09 6C .....:.........l
0080: 6F 63 61 6C 68 6F 73 74 FF 01 00 01 00 00 0A 00 ocalhost........
0090: 08 00 06 00 17 00 18 00 19 00 0B 00 02 01 00 00 ................
00A0: 23 00 00 33 74 00 00 00 05 00 05 01 00 00 00 00 #..3t...........
%% Created: [Session-2, TLS_DHE_RSA_WITH_AES_128_CBC_SHA]
*** ServerHello, TLSv1
RandomCookie: GMT: 1300365840 bytes = { 222, 252, 143, 86, 187, 89, 214, 118, 63, 242, 37, 135, 249, 157, 237, 68, 89, 183, 207, 35, 214, 165, 158, 236, 247, 198, 35, 127 }
Session ID: {78, 130, 2, 16, 13, 19, 136, 228, 191, 64, 181, 90, 114, 50, 25, 82, 4, 243, 33, 245, 240, 52, 212, 152, 131, 33, 75, 87, 233, 215, 115, 40}
Cipher Suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA
Compression Method: 0
Extension renegotiation_info, renegotiated_connection: <empty>
***
Cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA
*** Certificate chain
chain [0] = [
[
Version: V3
Subject: CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 1024 bits
modulus: 150590733090315595349916824289564207692943099832411234713235760334933701999028974289384033235479148899664720703153353063908054708567240747626032506431265644085048315430102573809958618243293819948440416636547643820235902609912005328682275839878326324697902360462814295687875085227151160366663023713790874542041
public exponent: 65537
Validity: [From: Mon Sep 26 15:14:30 PDT 2011,
To: Sun Dec 25 14:14:30 PST 2011]
Issuer: CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown
SerialNumber: [ 4e80f946]
]
Algorithm: [SHA1withRSA]
Signature:
0000: 11 71 DF 8F 2B 4C 8C 3A 43 2F 91 49 FB 2E 45 41 .q..+L.:C/.I..EA
0010: B9 0D 9A E7 A9 48 36 FC BC 87 E4 F2 7E 4C BE EB .....H6......L..
0020: 0C E0 36 D2 67 0C C7 0D D2 69 5E D7 65 93 F6 FE ..6.g....i^.e...
0030: 48 1B 63 00 75 E5 96 AE E5 82 BA ED 50 07 26 90 H.c.u.......P.&.
0040: 42 E1 CF 33 3F 84 A7 75 18 C0 0B 96 C3 E4 B4 FA B..3?..u........
0050: AA AE 91 D2 48 E8 38 70 CA 60 E7 BC 19 EA 0D 76 ....H.8p.`.....v
0060: 55 B4 B7 D6 20 ED F3 C6 CE 8F 88 32 EE E8 D8 94 U... ......2....
0070: 2F 8A 58 55 30 90 4A A7 D1 88 3B C4 6E 4B 29 2A /.XU0.J...;.nK)*
]
***
*** Diffie-Hellman ServerKeyExchange
DH Modulus: { 233, 230, 66, 89, 157, 53, 95, 55, 201, 127, 253, 53, 103, 18, 11, 142, 37, 201, 205, 67, 233, 39, 179, 169, 103, 15, 190, 197, 216, 144, 20, 25, 34, 210, 195, 179, 173, 36, 128, 9, 55, 153, 134, 157, 30, 132, 106, 171, 73, 250, 176, 173, 38, 210, 206, 106, 34, 33, 157, 71, 11, 206, 125, 119, 125, 74, 33, 251, 233, 194, 112, 181, 127, 96, 112, 2, 243, 206, 248, 57, 54, 148, 207, 69, 238, 54, 136, 193, 26, 140, 86, 171, 18, 122, 61, 175 }
DH Base: { 48, 71, 10, 213, 160, 5, 251, 20, 206, 45, 157, 205, 135, 227, 139, 199, 209, 177, 197, 250, 203, 174, 203, 233, 95, 25, 10, 167, 163, 29, 35, 196, 219, 188, 190, 6, 23, 69, 68, 64, 26, 91, 44, 2, 9, 101, 216, 194, 189, 33, 113, 211, 102, 132, 69, 119, 31, 116, 186, 8, 77, 32, 41, 216, 60, 28, 21, 133, 71, 243, 169, 241, 162, 113, 91, 226, 61, 81, 174, 77, 62, 90, 31, 106, 112, 100, 243, 22, 147, 58, 52, 109, 63, 82, 146, 82 }
Server DH Public Key: { 223, 130, 204, 208, 52, 175, 11, 85, 214, 72, 110, 90, 77, 68, 217, 136, 237, 178, 54, 164, 253, 209, 6, 158, 45, 31, 163, 85, 50, 239, 30, 8, 182, 172, 102, 95, 13, 100, 82, 42, 208, 217, 211, 182, 60, 83, 105, 182, 33, 25, 180, 69, 90, 92, 193, 127, 207, 7, 224, 113, 107, 150, 106, 20, 38, 190, 185, 60, 47, 69, 155, 242, 29, 51, 230, 214, 149, 167, 250, 125, 42, 158, 148, 136, 202, 227, 159, 250, 160, 191, 193, 10, 192, 73, 235, 70 }
Signed with a DSA or RSA public key
*** ServerHelloDone
[write] MD5 and SHA1 hashes: len = 1122
0000: 02 00 00 4D 03 01 4E 82 02 10 DE FC 8F 56 BB 59 ...M..N......V.Y
0010: D6 76 3F F2 25 87 F9 9D ED 44 59 B7 CF 23 D6 A5 .v?.%....DY..#..
0020: 9E EC F7 C6 23 7F 20 4E 82 02 10 0D 13 88 E4 BF ....#. N........
0030: 40 B5 5A 72 32 19 52 04 F3 21 F5 F0 34 D4 98 83 @.Zr2.R..!..4...
0040: 21 4B 57 E9 D7 73 28 00 33 00 00 05 FF 01 00 01 !KW..s(.3.......
0050: 00 0B 00 02 5D 00 02 5A 00 02 57 30 82 02 53 30 ....]..Z..W0..S0
0060: 82 01 BC A0 03 02 01 02 02 04 4E 80 F9 46 30 0D ..........N..F0.
0070: 06 09 2A 86 48 86 F7 0D 01 01 05 05 00 30 6E 31 ..*.H........0n1
0080: 10 30 0E 06 03 55 04 06 13 07 55 6E 6B 6E 6F 77 .0...U....Unknow
0090: 6E 31 10 30 0E 06 03 55 04 08 13 07 55 6E 6B 6E n1.0...U....Unkn
00A0: 6F 77 6E 31 10 30 0E 06 03 55 04 07 13 07 55 6E own1.0...U....Un
00B0: 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 0A 13 07 known1.0...U....
00C0: 55 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 0B Unknown1.0...U..
00D0: 13 07 55 6E 6B 6E 6F 77 6E 31 12 30 10 06 03 55 ..Unknown1.0...U
00E0: 04 03 13 09 6C 6F 63 61 6C 68 6F 73 74 30 1E 17 ....localhost0..
00F0: 0D 31 31 30 39 32 36 32 32 31 34 33 30 5A 17 0D .110926221430Z..
0100: 31 31 31 32 32 35 32 32 31 34 33 30 5A 30 6E 31 111225221430Z0n1
0110: 10 30 0E 06 03 55 04 06 13 07 55 6E 6B 6E 6F 77 .0...U....Unknow
0120: 6E 31 10 30 0E 06 03 55 04 08 13 07 55 6E 6B 6E n1.0...U....Unkn
0130: 6F 77 6E 31 10 30 0E 06 03 55 04 07 13 07 55 6E own1.0...U....Un
0140: 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 0A 13 07 known1.0...U....
0150: 55 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 0B Unknown1.0...U..
0160: 13 07 55 6E 6B 6E 6F 77 6E 31 12 30 10 06 03 55 ..Unknown1.0...U
0170: 04 03 13 09 6C 6F 63 61 6C 68 6F 73 74 30 81 9F ....localhost0..
0180: 30 0D 06 09 2A 86 48 86 F7 0D 01 01 01 05 00 03 0...*.H.........
0190: 81 8D 00 30 81 89 02 81 81 00 D6 72 C5 3F 68 BE ...0.......r.?h.
01A0: C7 2A 8E 24 13 EB 54 C4 16 49 68 A0 1C 1F 4D 26 .*.$..T..Ih...M&
01B0: E6 C5 A1 EC 63 4E EF B6 49 A2 26 8A 2B 47 D1 A5 ....cN..I.&.+G..
01C0: ED 4C F0 61 15 AE E0 AA 20 7B 59 6C 42 4B A8 3D .L.a.... .YlBK.=
01D0: 8A DC 0F E9 B2 67 2C 74 F8 22 F3 00 40 17 40 11 .....g,t."..@.@.
01E0: A5 8E 9F 0D 9C 7D 7B 0A 57 7F EC 29 2E 74 83 27 ........W..).t.'
01F0: 9C 3D BF 9E 23 74 C5 FC 95 6C B9 0B 3B 33 DB AE .=..#t...l..;3..
0200: A2 F3 2C 35 8A EB 57 F6 5B 97 73 88 F0 BF 06 AD ..,5..W.[.s.....
0210: F7 E0 58 6A 0E 66 36 16 DF D9 02 03 01 00 01 30 ..Xj.f6........0
0220: 0D 06 09 2A 86 48 86 F7 0D 01 01 05 05 00 03 81 ...*.H..........
0230: 81 00 11 71 DF 8F 2B 4C 8C 3A 43 2F 91 49 FB 2E ...q..+L.:C/.I..
0240: 45 41 B9 0D 9A E7 A9 48 36 FC BC 87 E4 F2 7E 4C EA.....H6......L
0250: BE EB 0C E0 36 D2 67 0C C7 0D D2 69 5E D7 65 93 ....6.g....i^.e.
0260: F6 FE 48 1B 63 00 75 E5 96 AE E5 82 BA ED 50 07 ..H.c.u.......P.
0270: 26 90 42 E1 CF 33 3F 84 A7 75 18 C0 0B 96 C3 E4 &.B..3?..u......
0280: B4 FA AA AE 91 D2 48 E8 38 70 CA 60 E7 BC 19 EA ......H.8p.`....
0290: 0D 76 55 B4 B7 D6 20 ED F3 C6 CE 8F 88 32 EE E8 .vU... ......2..
02A0: D8 94 2F 8A 58 55 30 90 4A A7 D1 88 3B C4 6E 4B ../.XU0.J...;.nK
02B0: 29 2A 0C 00 01 A8 00 60 E9 E6 42 59 9D 35 5F 37 )*.....`..BY.5_7
02C0: C9 7F FD 35 67 12 0B 8E 25 C9 CD 43 E9 27 B3 A9 ...5g...%..C.'..
02D0: 67 0F BE C5 D8 90 14 19 22 D2 C3 B3 AD 24 80 09 g......."....$..
02E0: 37 99 86 9D 1E 84 6A AB 49 FA B0 AD 26 D2 CE 6A 7.....j.I...&..j
02F0: 22 21 9D 47 0B CE 7D 77 7D 4A 21 FB E9 C2 70 B5 "!.G...w.J!...p.
0300: 7F 60 70 02 F3 CE F8 39 36 94 CF 45 EE 36 88 C1 .`p....96..E.6..
0310: 1A 8C 56 AB 12 7A 3D AF 00 60 30 47 0A D5 A0 05 ..V..z=..`0G....
0320: FB 14 CE 2D 9D CD 87 E3 8B C7 D1 B1 C5 FA CB AE ...-............
0330: CB E9 5F 19 0A A7 A3 1D 23 C4 DB BC BE 06 17 45 .._.....#......E
0340: 44 40 1A 5B 2C 02 09 65 D8 C2 BD 21 71 D3 66 84 D@.[,..e...!q.f.
0350: 45 77 1F 74 BA 08 4D 20 29 D8 3C 1C 15 85 47 F3 Ew.t..M ).<...G.
0360: A9 F1 A2 71 5B E2 3D 51 AE 4D 3E 5A 1F 6A 70 64 ...q[.=Q.M>Z.jpd
0370: F3 16 93 3A 34 6D 3F 52 92 52 00 60 DF 82 CC D0 ...:4m?R.R.`....
0380: 34 AF 0B 55 D6 48 6E 5A 4D 44 D9 88 ED B2 36 A4 4..U.HnZMD....6.
0390: FD D1 06 9E 2D 1F A3 55 32 EF 1E 08 B6 AC 66 5F ....-..U2.....f_
03A0: 0D 64 52 2A D0 D9 D3 B6 3C 53 69 B6 21 19 B4 45 .dR*....<Si.!..E
03B0: 5A 5C C1 7F CF 07 E0 71 6B 96 6A 14 26 BE B9 3C Z\.....qk.j.&..<
03C0: 2F 45 9B F2 1D 33 E6 D6 95 A7 FA 7D 2A 9E 94 88 /E...3......*...
03D0: CA E3 9F FA A0 BF C1 0A C0 49 EB 46 00 80 17 76 .........I.F...v
03E0: 7D D7 E4 0E D7 D5 6E 5B 0A B3 C5 DA 92 13 20 1E ......n[...... .
03F0: 4A D7 A3 07 C4 2B DA F8 ED 13 48 3A 6B 39 4E 5F J....+....H:k9N_
0400: 1B 01 A3 A1 47 AB 65 21 D3 62 7B D3 01 7D AF C5 ....G.e!.b......
0410: B2 D0 C0 A1 CB 04 DA C3 82 4F DA 16 5C 7D A6 BD .........O..\...
0420: 48 6F 8C E9 E0 FF A0 E9 BF 44 16 4B 33 E1 DA 70 Ho.......D.K3..p
0430: 75 3C EE E5 9D 50 BE 17 56 E7 50 D6 E5 EF 29 6F u<...P..V.P...)o
0440: 66 A0 45 6D 91 CA D5 97 72 15 BD F7 8D 98 65 35 f.Em....r.....e5
0450: 87 52 35 FB D6 43 42 5D 90 C6 36 EB E6 8A 0E 00 .R5..CB]..6.....
0460: 00 00 ..
main, WRITE: TLSv1 Handshake, length = 1122
[Raw write]: length = 1127
0000: 16 03 01 04 62 02 00 00 4D 03 01 4E 82 02 10 DE ....b...M..N....
0010: FC 8F 56 BB 59 D6 76 3F F2 25 87 F9 9D ED 44 59 ..V.Y.v?.%....DY
0020: B7 CF 23 D6 A5 9E EC F7 C6 23 7F 20 4E 82 02 10 ..#......#. N...
0030: 0D 13 88 E4 BF 40 B5 5A 72 32 19 52 04 F3 21 F5 .....@.Zr2.R..!.
0040: F0 34 D4 98 83 21 4B 57 E9 D7 73 28 00 33 00 00 .4...!KW..s(.3..
0050: 05 FF 01 00 01 00 0B 00 02 5D 00 02 5A 00 02 57 .........]..Z..W
0060: 30 82 02 53 30 82 01 BC A0 03 02 01 02 02 04 4E 0..S0..........N
0070: 80 F9 46 30 0D 06 09 2A 86 48 86 F7 0D 01 01 05 ..F0...*.H......
0080: 05 00 30 6E 31 10 30 0E 06 03 55 04 06 13 07 55 ..0n1.0...U....U
0090: 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 08 13 nknown1.0...U...
00A0: 07 55 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 .Unknown1.0...U.
00B0: 07 13 07 55 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 ...Unknown1.0...
00C0: 55 04 0A 13 07 55 6E 6B 6E 6F 77 6E 31 10 30 0E U....Unknown1.0.
00D0: 06 03 55 04 0B 13 07 55 6E 6B 6E 6F 77 6E 31 12 ..U....Unknown1.
00E0: 30 10 06 03 55 04 03 13 09 6C 6F 63 61 6C 68 6F 0...U....localho
00F0: 73 74 30 1E 17 0D 31 31 30 39 32 36 32 32 31 34 st0...1109262214
0100: 33 30 5A 17 0D 31 31 31 32 32 35 32 32 31 34 33 30Z..11122522143
0110: 30 5A 30 6E 31 10 30 0E 06 03 55 04 06 13 07 55 0Z0n1.0...U....U
0120: 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 08 13 nknown1.0...U...
0130: 07 55 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 55 04 .Unknown1.0...U.
0140: 07 13 07 55 6E 6B 6E 6F 77 6E 31 10 30 0E 06 03 ...Unknown1.0...
0150: 55 04 0A 13 07 55 6E 6B 6E 6F 77 6E 31 10 30 0E U....Unknown1.0.
0160: 06 03 55 04 0B 13 07 55 6E 6B 6E 6F 77 6E 31 12 ..U....Unknown1.
0170: 30 10 06 03 55 04 03 13 09 6C 6F 63 61 6C 68 6F 0...U....localho
0180: 73 74 30 81 9F 30 0D 06 09 2A 86 48 86 F7 0D 01 st0..0...*.H....
0190: 01 01 05 00 03 81 8D 00 30 81 89 02 81 81 00 D6 ........0.......
01A0: 72 C5 3F 68 BE C7 2A 8E 24 13 EB 54 C4 16 49 68 r.?h..*.$..T..Ih
01B0: A0 1C 1F 4D 26 E6 C5 A1 EC 63 4E EF B6 49 A2 26 ...M&....cN..I.&
01C0: 8A 2B 47 D1 A5 ED 4C F0 61 15 AE E0 AA 20 7B 59 .+G...L.a.... .Y
01D0: 6C 42 4B A8 3D 8A DC 0F E9 B2 67 2C 74 F8 22 F3 lBK.=.....g,t.".
01E0: 00 40 17 40 11 A5 8E 9F 0D 9C 7D 7B 0A 57 7F EC .@.@.........W..
01F0: 29 2E 74 83 27 9C 3D BF 9E 23 74 C5 FC 95 6C B9 ).t.'.=..#t...l.
0200: 0B 3B 33 DB AE A2 F3 2C 35 8A EB 57 F6 5B 97 73 .;3....,5..W.[.s
0210: 88 F0 BF 06 AD F7 E0 58 6A 0E 66 36 16 DF D9 02 .......Xj.f6....
0220: 03 01 00 01 30 0D 06 09 2A 86 48 86 F7 0D 01 01 ....0...*.H.....
0230: 05 05 00 03 81 81 00 11 71 DF 8F 2B 4C 8C 3A 43 ........q..+L.:C
0240: 2F 91 49 FB 2E 45 41 B9 0D 9A E7 A9 48 36 FC BC /.I..EA.....H6..
0250: 87 E4 F2 7E 4C BE EB 0C E0 36 D2 67 0C C7 0D D2 ....L....6.g....
0260: 69 5E D7 65 93 F6 FE 48 1B 63 00 75 E5 96 AE E5 i^.e...H.c.u....
0270: 82 BA ED 50 07 26 90 42 E1 CF 33 3F 84 A7 75 18 ...P.&.B..3?..u.
0280: C0 0B 96 C3 E4 B4 FA AA AE 91 D2 48 E8 38 70 CA ...........H.8p.
0290: 60 E7 BC 19 EA 0D 76 55 B4 B7 D6 20 ED F3 C6 CE `.....vU... ....
02A0: 8F 88 32 EE E8 D8 94 2F 8A 58 55 30 90 4A A7 D1 ..2..../.XU0.J..
02B0: 88 3B C4 6E 4B 29 2A 0C 00 01 A8 00 60 E9 E6 42 .;.nK)*.....`..B
02C0: 59 9D 35 5F 37 C9 7F FD 35 67 12 0B 8E 25 C9 CD Y.5_7...5g...%..
02D0: 43 E9 27 B3 A9 67 0F BE C5 D8 90 14 19 22 D2 C3 C.'..g......."..
02E0: B3 AD 24 80 09 37 99 86 9D 1E 84 6A AB 49 FA B0 ..$..7.....j.I..
02F0: AD 26 D2 CE 6A 22 21 9D 47 0B CE 7D 77 7D 4A 21 .&..j"!.G...w.J!
0300: FB E9 C2 70 B5 7F 60 70 02 F3 CE F8 39 36 94 CF ...p..`p....96..
0310: 45 EE 36 88 C1 1A 8C 56 AB 12 7A 3D AF 00 60 30 E.6....V..z=..`0
0320: 47 0A D5 A0 05 FB 14 CE 2D 9D CD 87 E3 8B C7 D1 G.......-.......
0330: B1 C5 FA CB AE CB E9 5F 19 0A A7 A3 1D 23 C4 DB ......._.....#..
0340: BC BE 06 17 45 44 40 1A 5B 2C 02 09 65 D8 C2 BD ....ED@.[,..e...
0350: 21 71 D3 66 84 45 77 1F 74 BA 08 4D 20 29 D8 3C !q.f.Ew.t..M ).<
0360: 1C 15 85 47 F3 A9 F1 A2 71 5B E2 3D 51 AE 4D 3E ...G....q[.=Q.M>
0370: 5A 1F 6A 70 64 F3 16 93 3A 34 6D 3F 52 92 52 00 Z.jpd...:4m?R.R.
0380: 60 DF 82 CC D0 34 AF 0B 55 D6 48 6E 5A 4D 44 D9 `....4..U.HnZMD.
0390: 88 ED B2 36 A4 FD D1 06 9E 2D 1F A3 55 32 EF 1E ...6.....-..U2..
03A0: 08 B6 AC 66 5F 0D 64 52 2A D0 D9 D3 B6 3C 53 69 ...f_.dR*....<Si
03B0: B6 21 19 B4 45 5A 5C C1 7F CF 07 E0 71 6B 96 6A .!..EZ\.....qk.j
03C0: 14 26 BE B9 3C 2F 45 9B F2 1D 33 E6 D6 95 A7 FA .&..</E...3.....
03D0: 7D 2A 9E 94 88 CA E3 9F FA A0 BF C1 0A C0 49 EB .*............I.
03E0: 46 00 80 17 76 7D D7 E4 0E D7 D5 6E 5B 0A B3 C5 F...v......n[...
03F0: DA 92 13 20 1E 4A D7 A3 07 C4 2B DA F8 ED 13 48 ... .J....+....H
0400: 3A 6B 39 4E 5F 1B 01 A3 A1 47 AB 65 21 D3 62 7B :k9N_....G.e!.b.
0410: D3 01 7D AF C5 B2 D0 C0 A1 CB 04 DA C3 82 4F DA ..............O.
0420: 16 5C 7D A6 BD 48 6F 8C E9 E0 FF A0 E9 BF 44 16 .\...Ho.......D.
0430: 4B 33 E1 DA 70 75 3C EE E5 9D 50 BE 17 56 E7 50 K3..pu<...P..V.P
0440: D6 E5 EF 29 6F 66 A0 45 6D 91 CA D5 97 72 15 BD ...)of.Em....r..
0450: F7 8D 98 65 35 87 52 35 FB D6 43 42 5D 90 C6 36 ...e5.R5..CB]..6
0460: EB E6 8A 0E 00 00 00 .......
main, received EOFException: error
main, handling exception: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
main, SEND TLSv1 ALERT: fatal, description = handshake_failure
main, WRITE: TLSv1 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 01 00 02 02 28 ......(
main, called closeSocket()
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:817)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:632)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
at java.io.OutputStream.write(OutputStream.java:58)
at Server.main(Server.java:44)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:333)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
... 5 more
It appears something went horribly wrong after Server Hello Done. Although, at the moment, I have no idea what to do about it. Any suggestions?
Update: I ran the debug test from http://prefetch.net/articles/debuggingssl.html, and everything looked fine. I'm beginning to suspect a bad SSL implementation in Chrome.
Update: I ran this Server on Windows XP, and Chrome worked beautifully. However, I want to get it working in Linux (Ubuntu). That is where I have the troubles. Also, I have to revise all my previous statements about IE working. It gives me the self signed warning, but when I say its OK, IE tells me it can't render the page. The IE problems occur on both Windows and Linux. Still looking for answers.
SOLVED See my answer below.
A: WooHoo! I finally figured this one out. After long, frustrating hours of searching the Intarwebz, I found documentation on this hidden Java library in J2SE 6+.
com.sun.net.httpserver
This implementation simply negotiates the SSL handshake and returns the request as plain text:
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.util.concurrent.Executor;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
public class HTTPS {
public static void main(String[] args) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("server.jks"), "123456".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "123456".toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
final HttpsServer server = HttpsServer.create(new InetSocketAddress("localhost", 8443), 10);
server.createContext("/", new HttpHandler() {
public void handle(HttpExchange xchng) throws IOException {
HttpsExchange exchange = (HttpsExchange) xchng;
String ret = "";
ret += exchange.getRequestMethod() + " " + exchange.getRequestURI() + " " + exchange.getProtocol() + "\n";
Headers headers = exchange.getRequestHeaders();
if (!headers.isEmpty()) {
ret += "\n";
for (String key : headers.keySet()) {
ret += key + ": ";
boolean semiColon = false;
for (String value : headers.get(key)) {
if (semiColon) {
ret += "; ";
}
ret += value;
semiColon = true;
}
ret += "\n";
}
}
if (headers.get("Content-Length") != null) {
InputStream in = exchange.getRequestBody();
ret += "\n";
int i;
while ((i = in.read()) != -1) {
ret += String.valueOf((char) i);
}
}
headers = exchange.getResponseHeaders();
headers.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, ret.length());
OutputStream out = exchange.getResponseBody();
out.write(ret.getBytes());
exchange.close();
}
});
server.setHttpsConfigurator(new HttpsConfigurator(context) {
public void configure(HttpsParameters params) {
}
});
server.setExecutor(new Executor() {
public void execute(Runnable command) {
new Thread(command).start();
}
});
server.start();
/*
* In a real app:
*
* public class ServerShutdownHook extends Thread {
* HttpServer server;
* int seconds;
*
* public ServerShutdownHook(HttpServer server, int seconds) {
* this.server = server;
* this.seconds = seconds;
* }
*
* public void run() {
* System.out.println("Server shutting down. Waiting " + this.seconds + " seconds for exchanges to complete.");
* server.stop(this.seconds);
* }
* }
*
* Runtime.getRuntime().addShutdownHook(new ServerShutdownHook(server, 3));
*/
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Server shutting down. Waiting 3 seconds for exchanges to complete.");
server.stop(3);
}
});
}
}
I tested this on my Ubuntu box and it works for the following browsers:
*
*Chrome
*Firefox
*Opera
*Mobile Safari (iPhone4)
*Safari
*IE
A: I suspect there is a firewall in the way that dropped the connection for some reason, or an inbound or outbound proxy. You may need to sniff the network packet exchange.
A: In my case there was a big hassle with supported ciphers and at the end it turned out that the order of them is important (the most desired by server on the very bottom - then the less wished above and so on...). You can figure out what is the wish list by checking https://www.ssllabs.com/ssltest
Also you might have to patch your jdk with JCE (http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html) Although jdk 8 should have the latest ciphers included and enabled accourding to the documentation (https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SunJSSEProvider)
private static final String TLS_PROTOCOL_1_2 = "TLSv1.2";
private static final String TLS_PROTOCOL_1_1 = "TLSv1.1";
private static final String TLS_PROTOCOL_3 = "SSLv3";
private static final String TLS_RSA_WITH_AES_256_CBC_SHA ="TLS_RSA_WITH_AES_256_CBC_SHA";
private static final String TLS_RSA_WITH_AES_256_CBC_SHA256 ="TLS_RSA_WITH_AES_256_CBC_SHA256";
private static final String TLS_RSA_WITH_AES_256_GCM_SHA384 = "TLS_RSA_WITH_AES_256_GCM_SHA384";
private static final String TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA";
private static final String TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384";
private static final String AUTHORIZATION = "Basic Zmlkb3I6d2lyIWJhbmsk";
@Override
public HttpURLConnection openSecureConnection(String path) throws IOException, KeyManagementException, NoSuchAlgorithmException {
URL url = new URL(baseUrl+path);
SSLContext sslContext = SSLContext.getInstance(TLS_PROTOCOL_1_2);
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sslSocketFactory);
con.setDoOutput(true);
con.setConnectTimeout(getTimeout());
con.setReadTimeout(getTimeout());
//set server-prefered cipher suits
SSLServerSocket soc = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket();
soc.setEnabledProtocols(new String[]{TLS_PROTOCOL_3, TLS_PROTOCOL_1_2, TLS_PROTOCOL_1_1});
soc.setEnabledCipherSuites(new String[] {
TLS_RSA_WITH_AES_256_CBC_SHA,
TLS_RSA_WITH_AES_256_CBC_SHA256,
TLS_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
});
return con;
}
For jdk 1.7 is it important to add VM option "-Dhttps.protocols=TLSv1.1,TLSv1.2"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: WinRT's WriteableBitmap no longer allows random access to pixel data? One of the changes in WinRT's WriteableBitmap class is that, instead of exposing a Pixels property as an array, it now has a PixelBuffer of type IBuffer.
The problem is that IBuffer doesn't have any way to do random access to the data. I can create a DataReader and get the data one piece at a time and copy the data to an array for random access, but no direct access to the IBuffer data. How do I do this, or is it impossible?
A: Seems like the exact same discussion happened over at the MSDN Forums.
For now, it doesn't appear that direct pixel manipulation is there, but there are work arounds by working with streams (as you have already noted).
All things considered, it is a developer preview and the functionality may be added in a later build.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: help with this query It shows repeated records and It is not working? I am trying to write a sql statement to retrieve all the messages with user_id_user = '3' and status = '2' but I get repeated records I dont know why, I am stuck with it
My tables are this
message
id_message title content date user_id_user status
-------------------------------------------------------------
user
id_user name
----------------
message_has_user
message_id_message user_id_user
----------------------------------
my mysql query but I get repeated records I dont know why, I am reading tutorial also any help really appreciated
SELECT
message.title,
message.content,
message.date,
message.id_message,
message_has_usuario.user_id_user,
message.status,
user.name
FROM
message ,
message_has_usuario
INNER JOIN user ON message_has_usuario.user_id_user = '3'
WHERE
message.status = '2'
A: You're getting a Cartesian product because you're not joining all your tables accurately.
You're joining USER and MESSGAE_HAS_USERIO but you're not doing any joins on MESSAGE
Quick Example _ I assume those relationships are correct.
SELECT *
FROM Message M
INNER JOIN Message_Has_User MAU on M.MessageID = MAU.MessageID
INNER JOIN User U ON MAU.UserID = U.UserID AND U.UserID = M.User_Id_User
WHERE MAU.userID = '3'
AND M.Status = '2'
I neither endorse or will admit that I used a Select *. Darn it all to heck that I even wrote it. /hides
A: Try this:
...
FROM message
JOIN message_has_usuario
on message_has_usuario.message_has_usuario = message.message_has_usuario
...
A: select message.*
from message, user
where user.id = 3
and user.id = message.user_id_user
and message.status = 2
Your not using INNER JOIN correctly. This should work for you!! Also what is the point of the message_has_user table? I looks redundant in this case since you can store the user_id directly on the message table. A user can have many messages, ie. One-To-Many.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to generically create a thumbnail corresponding to a given RSS feed's article So I'm brainstorming right now and would like to hear your thoughts on this.
So you know the news app, pulse?
As you can see it pulls thumbnails from virtually any news source.
I'm curious as to how they gather the title and image from various sources since their RSS feeds will always vary.
I was thinking, for each article in the RSS feed, I would just iterate over its content until I find a preg_match for an image source.
Is that the best way to generically determine the image?
..How about the title?
:)
A: The titles is obviously from the RSS. Look at any rss feeds for their title tags.
Probably the only tricky part is the thumbnail. However some RSS feeds like Engadget http://www.engadget.com/rss.xml;
has image associate with each article (under the CDATA of the description tag) which can be easily regex match.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: image saving, resizing I have one basic question. I have project where I need more sizes of one picture.
Yes... During uploading you make thumbnails... and so on... I know this story ... performance vs. storing possibilities.
So I save original img, a make 2 thumbnails copies for example max width 100px and maxwidht 200px with respect to ratio.
Now I need show image in 150px max width so I take saved img(200px) and .....
I use getimagesize() for calculating showing width and height respected to ratio,
or I set max-widht and max-height and I leave it for browser (browser make it for me),
or I set width a keep height: auto (but I want also limit max height)
So actualy I use php and getimagesize() but this function every time work with file and I am little scared. When you process 1 img it is OK but what about 20 or 100.
And... another idea, while uploading I save to DB also size information, for this I have to save data for 3 img (now only original one) this complicate everything.
So ... any ideas? What is your practice? THX.
A: Two images, at a maximum: A thumbnail, and the original image are sufficient. Make sure that your upload page is well-secured, because I've seen a website taken down through DoS (abusing an unprotected image-resizing page). Also limit the maximum upload size, to prevent abuse.
You can use the max-width and max-height CSS properties to limit the size of your images.
A: My approach
I wrote a pretty simple gallery application in php a while ago and this is how it works:
The images are stored in a folder with subfolders representing albums (and subalbums). They are uploaded via FTP and the webserver only has read-permissions on them.
For each image there are three versions:
*
*a full one (the original)
*a "mid" one (1024x768px max)
*a "thumb" one (250x250px max)
All requests for images by the browser are served by php, and not-yet-existing versions are generated on the fly. The actual data is served through X-Sendfile, but that's an implementation detail.
I store the smaller versions in separate directories. When given a path to an original image, it is trivial to find the corresponding downscaled files (and check for existence and modification times).
Thoughts on your problem
Scaling images using HTML / CSS is considered bad practice for two simple reasons: if you are scaling up, you have a blurred image. If you are scaling down, you waste bandwidth and make your page slower for no good reason. So don't do it.
It should be possible to determine a pretty small set of required versions of each file (for example those used in a layout as in my case). Depending on the size and requirements of your project there are a few possibilities for creating those versions:
*
*on the fly: generate / update them, when they are requested
*during upload: have the routine that is called during the upload-process do the work
*in the background: have the upload-routine add a job to a queue that is worked on in the background (probably most scalable but also fairly complex to implement and deploy)
Scaling down large images is a pretty slow operation (taking a few seconds usually). You might want to throttle it somehow to prevent abuse / DoS. Also limit dimensions and file size. A 100 MP (or even bigger) plain white (or any color) JPG might be very small when compressed, but will use an awful lot of RAM during scaling. Also big PNGs take really long to decompress (and even more to compress).
For a small website it doesn't matter, which approach you choose. Something that works (even if it doesn't scale) will do. If you plan on getting a good amount of traffic and a steady stream of uploads, then choose wisely and benchmark carefully.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I verify that a swt text widget is a decimal value In swt, text widget allow any string.
But What is the most appropriate SWT widget in which to enter a Decimal value?
I found two answers :
*
*First, implement the VerifyKeyListener and VerifyListener, work for french decimal notation, but simple and easy to implement :
package test.actions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Text;
public final class AmountVerifyKeyListener implements VerifyListener, VerifyKeyListener {
private static final String REGEX = "^[-+]?[0-9]*[,]?[0-9]{0,2}+$";
private static final Pattern pattern = Pattern.compile(REGEX);
public void verifyText(VerifyEvent verifyevent) {
verify(verifyevent);
}
public void verifyKey(VerifyEvent verifyevent) {
verify(verifyevent);
}
private void verify (VerifyEvent e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
Text text = (Text)e.getSource();
if ( ( ",".equals(string) || ".".equals(string) ) && text.getText().indexOf(',') >= 0 ) {
e.doit = false;
return;
}
for (int i = 0; i < chars.length; i++) {
if (!(('0' <= chars[i] && chars[i] <= '9') || chars[i] == '.' || chars[i] == ',' || chars[i] == '-')) {
e.doit = false;
return;
}
if ( chars[i] == '.' ) {
chars[i] = ',';
}
}
e.text = new String(chars);
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
Matcher matcher = pattern.matcher(newS);
if ( !matcher.matches() ) {
e.doit = false;
return;
}
}
}
And the main class associated to the verifyKeyListener :
package test.actions;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TestMain {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(2, false));
final Text text = new Text(shell, SWT.NONE);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
text.addVerifyListener(new AmountVerifyKeyListener() ) ;
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
*
*Use the FormattedText from the nebula project : http://eclipse.org/nebula/
Somebody see another solution ?
A: A cleaner and easier way would be to use Double.parseString() and catch the NumberFormatException's to figure out if the text in it can be converted to a double.
A: *
*For the validation of Double values you have to consider that characters like E may be included in Doubles and that partial input like "4e-" should be valid while typing to allow to finally enter "4e-3". The partial expressions might give a NumberFormatException for Double.parseDouble(partialExpression)
*Also see my answer at following related question:
How to set a Mask to a SWT Text to only allow Decimals
*(Further note: If one only wants to allow Integer values a Spinner can be used instead of a text field.)
A: Why not a simple regex on the widget like the following:
if(Text.getText().matches("^[0-9]+$")) {
show an error dialog or similar
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: My android app "stops unexpectedly" I have recently got into writing android apps and have hit a brick wall very early on that I can't figure out, and i'm sure it's mind numbingly simple.
Everytime I run it in my emulator, I get the "Stopped unexpectedly" error :/
Files
The main ".java" file and the main.xml are in there, just scroll down.
EDIT: Fixed now, just needed a simple clean :3
A: Somewhere in your layout XML, there's an invalid element named EditText2. There's no such view in the Android SDK, remove the "2".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery DataTables .Net Server Side Pagination Issues I'm working on a bug fix right now for an application at work where the prior developer (since gone) didn't bother to paginate the data results on a page meant specifically for listing out data results.
This of course has reared it's ugly head as users are starting to see long running script errors in IE. This, combined with the sheer data volume size, is making web pages nearly useless.
Fast forward to my attempts to fix it and they've gone pretty well. The site is a .NET MVC 2 site that was developed using DataTables to add search/sort/paging functionality on the client. I'd just completed a similar task using jqGrid so figured this would be relatively straight forward. And it has been except one small problem. I cannot for the life of me get page links to generate.
A quick results view:
The results know that there are 2086 records in this query:
But paging links are not generated.
My action method is returning JSON via
return Json(new
{
param.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = filteredContracts.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
where
param.sEcho = "1",
iTotalRecords = 2086,
iTotalDisplayRecords = 25,
and aaData is the array result of data to display
To be thorough, he's the datatable initialize statement:
$("#tblToDoItems").dataTable({
'bServerSide': true,
'bProcessing': true,
'sAjaxSource': '/Home/GetContractList',
"bJQueryUI": true,
"bAutoWidth": false,
"bPaginate": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 25,
/* make the first and last columns not sortable */
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [0, -1] }
]
});
Am I missing some setting that would prevent DataTables from properly generating pagination via server side data retrieval?
A: Your iTotalDisplayRecords is equal to 25, so datatables think that there are only 25 contracts on the server side and second page is not needed because all of them are already shown on the current page.
This is comon mistake - if you take a look at the JQuery MVC tutorial section Implementation of server-side paging you will see that there are three numbers:
*
*iTotalRecords = allCompanies.Count() representing all entries in the database (in your case 2086)
*iTotalDisplayRecords = filteredCompanies.Count() representing the number of the records that match the current search condition. If you didn't used filtering this number should be same as the iTotalRecords 2086, but in yourcase it is 25.
*result.Count - this is 25. This number is not passed in the JSON response because DataTables already knows that there should be 25 records per page.
If you put all.Count insteadof the result.Count into the iTotalDisplayRecords DataTables will show paging. iTotalDisplayRecords and iTotalRecords are used to show message
"Showing 1 to 25 of iTotalDisplayRecords (iTotalRecords in total)"
If iTotalDisplayRecords is equal to 25, DataTables will show message "Showing 1 to 25 of 25 (iTotalRecords in total)", and assume that there is no page 2; hence, paging will be disabled, as in your example.
Jovan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Windows Service output not showing up in Event Log I am trying to follow this walkthrough.
I'm using Visual Studio 2010 Premium.
The only events I see in Server Explorer or in Event Viewer are "Service started successfully." and "Service stopped successfully."
Here is the service code:
namespace MyNewService
{
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
if (!EventLog.SourceExists("MySource"))
{
EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
}
}
A: I had the same issue with Visual Studio 2010 Professional on Win 7 64. My newly compiled service was installed with InstallUtil.exe running as Administrator. It started and stopped correctly. No exceptions but no amount of refreshing the Event Viewer revealed a new event log. Fran71's suggestion worked for me: I closed the Event Viewer and reopened. Voilà, the newly created application log file appeared.
A: FWIW, I ran into this problem in Win8 and found that Refreshing the Event Viewer did not cause my newly created Event Log to show up, but closing and reopening Event Viewer did. Was driving me insane since no exceptions were being thrown when Creating the Event source or writing a log entry.
A: Probably a permissions problem. Like the commenter said, try running VStudio or your compiled service as an Administrator.
Also, you can still debug a service - put a thread.Sleep(up to 20 seconds) as your first line (to give yourself time to attach the debugger), then put a break point on the line after that. Then go Tools --> Attach To Process and select your .exe. If you get that done before the end of your Thread.Sleep() then you should break.
Keep in mind that the service must complete the OnStart within IIRC 30 seconds or Windows will think it is not responding and kill your process, so move your code out of the service start if you are going to do much debugging. Just throw a timer in there or something.
To make it easier to debug, consider moving your functionality to a DLL and then keep your service to just enough code to call into your DLL - this will ease unit testing and debugging - but don't forget that lots of things change when you're actually running it as a service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: If I @Ignore a test class in JUnit4, does @BeforeClass still run? Quick background: I've been hunting down a Maven / Surefire test-running problem for days now, and I've narrowed it down to a small number suspect of tests. The behavior I'm seeing is insane. I start with mvn clean test: 250 tests run, 0 skipped. Now, I move the suspect test into src/test/java and try again: 146 tests run, 0 skipped! The output of Maven gives no clue that other tests aren't being run, even with the -X flag.
That brings me to my question: the reason I call the test 'suspect' is that the whole class is decorated with @Ignore, so I would imagine that including it in my test sources should have no effect at all. Then it occurred to me -- those classes have @BeforeClass/@AfterClass methods that
manage a dummy Zookeeper server. It's resulted in wonky behavior before, which is why we have the tests @Ignored.
If JUnit is running the before/after code but ignoring the tests, I have no idea what might happen (but it'd probably be super bad). Is this happening? Is this supposed to happen? If so, how am I supposed to say "for reference, here's a test that should work but needs fixing" when it includes @BeforeClass / @AfterClass? Also of substantial interest: what the hell is this doing to Surefire / Maven, that it causes unrelated tests to fall off the face of the Earth?
A: Environment: JDK 1.6, surefire plugin 2.9, jUnit 4.8.1, Maven 3.0, 3.0.3, 2.2.1.
I created this test class:
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class IgnoreTest {
@BeforeClass
public static void beforeClass() {
System.out.println("BEFORE CLASS");
}
@AfterClass
public static void afterClass() {
System.out.println("AFTER CLASS");
}
@Test
public void test1() throws Exception {
System.out.println("test1");
}
@Test
public void test2() throws Exception {
System.out.println("test2");
}
@Test
public void test3() throws Exception {
System.out.println("test3");
}
}
Then mvn clean test print this:
Running hu.palacsint.stackoverflow.q7535177.IgnoreTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.015 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1
Works as you expected. If I remove the @Ignore and run mvn clean test again it prints this:
Running hu.palacsint.stackoverflow.q7535177.IgnoreTest
BEFORE CLASS
test2
test1
test3
AFTER CLASS
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.045 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
So, it works for me with three different Maven versions. No @BeforeClass/@AfterClass was run in @Ignored classes.
There is one (maybe more) situation when @BeforeClass/@AfterClass methods could run in an @Ignored test class. It's when your ignored class has a not ignored subclass:
import org.junit.Test;
public class IgnoreSubTest extends IgnoreTest {
@Test
public void test4() throws Exception {
System.out.println("test4 subclass");
}
}
Results of mvn clean test:
Running hu.palacsint.stackoverflow.q7535177.IgnoreTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.047 sec
Running hu.palacsint.stackoverflow.q7535177.IgnoreSubTest
BEFORE CLASS
test4 subclass
test1
test2
test3
AFTER CLASS
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.057 sec
Results :
Tests run: 5, Failures: 0, Errors: 0, Skipped: 1
In this case the @BeforeClass and the @AfterClass methods runs because they are methods of the IgnoreSubTest test class.
A: If you have a test with the @Ignore annotation, then it is normal behaviour for the @BeforeClass & @AfterClass to get run, whether or not all of the tests are @Ignored.
If, however, the Class has an @Ignore annotation, then the @BeforeClass & @AfterClass don't get run.
For maven, if you don't want to run any tests in a particular class, then you have to ignore them in surefire or failsafe. Add this to the maven configuration (see Maven Surefire Plugin)
<excludes>
<exclude>**/FoobarTest.class</exclude>
</excludes>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How does threading or Multiprocessing work with recursions? Background
I'm a bit new to developing and had a general python/programming question. If you have a method that is a recursion, what is involved to enabling multiple threads or multiprocessing? I've done some light reading and a few examples but they seem to be applying the syntax for new code(and not very cpu intensive tasks), I'm more wondering how do I re-design existing code to do this?
Say I have something thats cpu intensive(basically keeps adding to itself until limit is hit):
def adderExample(sum, number):
if sum > 1000:
print 'sum is larger than 10. Stoping'
else:
sum = sum + number
print sum
number = number + 1
adderExample(sum, number)
adderExample(0,0)
Question(s)/Though process
How would I approach this to make it run faster assuming I have multiple cores available(I want it to eventually want it span machines but I think thats a sperate issue with hadoop so I'll keep this example to only one system with multiple cpu's)? It seems threading it isn't the best choice(because of the time it takes to spawn new threads), if thats true should I only focus on multiprocessing? If so, can recursions be split to different cpu's(vai queues I assume and then rejoin after its done)? Can I create multiple threads for each process than split those processes over multiple cpu's? Lastly, is recursion depth limits an overall limit or is it based on threads/proceses, if so does multiprocessing/threading get around it?
Another question(related) how do those guys trying to codes(rsa, wireless keys,etc) via brute force overcome this problem? I assume they are scaling their mathematical processes over multiple cpu somehow. This or any example to build my understanding would be great.
Any tips/suggestions would be great
Thanks!
A: Such a loop wouldn't benefit much at all from threading. Consider that you're doing a series of additions, whose intermediate values depend on the previous iterations. This can't be parallelized, because the threads would be stomping on each other's values and overwriting things. You can lock the data so only one thread works on it at a time, but then you lose any benefit of having multiple threads working on that data.
Threads work best when they have independent data sets. e.g. a graphics renderer is a perfect example. Each thread renders a subset of the larger image - they may share common data sources for texture/vertex/color/etc... data, but each thread has its own little section of the total image to work one, and doesn't touch other areas of the image. Whatever thread #1 does on its little section of pixels won't affect what thread #2 is doing elsewhere in the image.
For your related question, password cracking is another example where threading/multiprocessing makes sense. Each thread goes off on its own testing multiple possible passwords against one common "to be cracked" list. What one thread is doing doesn't affect any of the other cracker threads, unless you get a match, which may mean all threads abort since the job is "done".
Once threads become interdependent on each other, you lose a lot of the benefits of having multiple threads. They'll spend more time waiting for the other to finish than they'll spend on doing actual work. Of course, this doesn't say you should never use threads. Sometimes it does makes sense to have multiple threads, even if they are interdependent. E.g. a graphics thread + sound effects thread + action processor thread + A.I. calculations thread, etc... in a game. each one is nominally dependent on each other, but while the sound thread is busy generating the bang+ricochet audio for the gun the player just shot, the a.i. thread is off calculating what the game's mobs are doing, the graphics thread is drawing some clouds in the background, etc...
A: Threading kinda sorta implies multiple stacks, recursion single stacks. That said, if you get to the recurse-left, recurse-right part and decide to spawn threads for the sub-problems if the current count of threads is "low" and do straight recursion otherwise you can combine the concepts.
But regular Python is not a good language for this pattern. Python threads all run on the same interpreter hardware thread, so you won't actually pick up any multiprocessing goodness.
A: Phunctor is correct that the threading library is a poor choice for parallelizing this type of problem, due to the "Global Interpreter Lock" that prevents multiple threads from executing Python code in parallel.
Where the threading library can be highly useful, though, is when each thread's code spends a lot of time waiting for I/O to happen. So, for example, if you're implementing a server that has to hit the disk or wait on a network response, servicing a request in each thread can be very efficient, since the threading library can favor the ones that are not waiting on I/O and thus maximize use of the Python interpreter. (In a single thread, you'd have to use a tight loop checking the statuses of your I/O requests, which would tend to be wasteful as load got high.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ImportError; and zipimporters disappeared from pkgutil.iter_importers() I have a Django instance that's mysteriously incapable of import memcache ... after (some unknown event that happens after a period of running just fine.)
LAMP configuration:
*
*RHEL 5.7
*Apache 2.2.3
*mod_wsgi 2.3 (dynamically linked to Python2.5.4 .so)
*Python 2.5.4
*Django 1.2
memcache sits in: /usr/local/lib/python2.5/site-packages/python_memcached-1.44-py2.5.ee/memcache.pyc
If I open up a command shell, and import memcache, it imports just fine.
And for a time, in Django, import memcache works just fine.
But after some unknown event, the import fails: ImportError: No module named memcache
Just prior point of failure, I logged the system path, and the path explicitly includes /usr/local/lib/python2.5 and /usr/local/lib/python2.5/site-packages.
I also logged the response to pkgutil.iter_importers(), and found something interesting: At the point of failure, iter_importers features NONE of the zipimporters -- and it is a zipimporter that is required to look inside the egg and find memcache.
If I manually import memcache, it functions:
try:
import memcache
except ImportError:
import zipimport
zi = zipimport.zipimporter('/usr/local/lib/python2.5/site-packages/python_memcached-1.44-py2.5.egg')
memcache = zi.load_module('memcache')
What is going on? What can I do to make it work without the workaround?
A: Okay. I found the answer. There is a bug in Python 2.5's os.listdir C implementation on 64-bit computers. When I applied the patch, everything works permanently.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS3 animation issue with z-index I have two elements in this jsFiddle. Each expands on mouseover with a :hover transition.
I want the blue animation to match the red one. Right now the red one expands over top of the blue one on mouseover, but the blue one expands under the red one. I would like each to animate over top of the other. This could probably be done by changing the z-index on :hover but that didn't seem to work very well.
A: Since you are animating all properties, the z-index animates and steps from 0 to 1 at the end of the animation.
Just animate the properties that you need and it works:
#a, #b {
width: 100px;
height: 100px;
position: absolute;
top: 0;
-webkit-transition: width .6s ease-in-out;
-moz-transition: width .6s ease-in-out;
-o-transition: width .6s ease-in-out;
-ms-transition: width .6s ease-in-out;
transition: width .6s ease-in-out;
}
http://jsfiddle.net/duopixel/hfM7E/
A: Try adding this to the CSS (and remove the z-index modifier in #a:hover, #b:hover {...}):
#a {
background: #55a;
left: 0;
z-index: 1;
}
#b:hover {
z-index: 2;
}
Example: http://jsfiddle.net/h6ztv/3/
A: Try setting initial z-index value to '0'
#a, #b {
width: 100px;
height: 100px;
position: absolute;
top: 0;
-webkit-transition: all .6s ease-in-out;
-moz-transition: all .6s ease-in-out;
-o-transition: all .6s ease-in-out;
-ms-transition: all .6s ease-in-out;
transition: all .6s ease-in-out;
z-index:0;
}
#a:hover, #b:hover {
width: 600px;
z-index: 1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When to use a key/value store such as Redis instead/along side of a SQL database? I have read great things about key/value stores such as Redis but I can't seem to figure out when it's time to use it in an application.
Say I am architecting a web-based application; I know what stack I am going to use for the front-end, back-end, database(s), etc..what are some scenarios where I would go "oh we also need Redis for X,Y, or Z."
I would appreciate node.js examples as well as non-node.js examples.
A: I think nothing explains better the use cases for Redis than this article:
http://antirez.com/post/take-advantage-of-redis-adding-it-to-your-stack.html
I bet you'll have an aha! moment. ;)
A quote from a previous reader:
I've read about Redis before and heard how companies are using it, but never completely understood it's purpose. After reading this I can actually say I understand Redis now and how it's useful. Amazing that after hearing so much about it all it took was a relatively simple article.
A quote from the article:
Redis is different than other database solutions in many ways: it uses memory as main storage support and disk only for persistence, the data model is pretty unique, it is single threaded and so forth. I think that another big difference is that in order to take advantage of Redis in your production environment you don't need to switch to Redis. You can just use it in order to do new things that were not possible before, or in order to fix old problems.
Use cases the article touches on:
*
*Slow latest items listings in your home page
*Leaderboards and related problems
*Order by user votes and time
*Implement expires on items
*Counting stuff
*Unique N items in a given amount of time
*Real time analysis of what is happening, for stats, anti spam, or whatever
*Pub/Sub
*Queues
*Caching
A: One thing off hand is that Redis isn't a relational database. If you're going to be needing an SQL "JOIN" then you won't want to use Redis, nor any other non-relational database. Redis is faster though than most relational databases. If you're only going to be doing key:value pair queries, then you'll want to use Redis.
A:
I can't seem to figure out when it's time to use it in an application.
I would recommend you to read this tutorial which contains also use cases. Since redis is rather memory oriented it's really good for frequently updated real-time data, such as session store, state database, statistics, caching and its advanced data structures offers versatility to many other scenarios.
Redis, however, isn't NoSQL replacement for classic relational databases since it doesn't support many standard features of RDBMS world such as querying of your data which might slow it down. Replacement are rather document databases like MongoDB or CouchDB and redis is great at supplementing specific functionality where speed and support for advanced data structures comes handy.
A: *
*I would love to use redis on the real time projects. I did recently
for one gps tracking system which was previously built on mysql as a
database.
ADVANTAGE
*
*Every time the tracker broadcast data I do not need to open mysql connection and store on it. We can save it on redis and later migrate
to mysql using some other process. This will avoid concurrent
connection from mutiple tracker to mysql.
*I can publish all those gps data and other clients(javascript/android) can subscribe in a real time using message queue based on redis
*I can trigger real time alerts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "204"
} |
Q: cmake set_property on SOURCE files with COMPILE_FLAGS I'm using CMake 2.8.1 (tried this on CMake 2.8.5 too). I'm using the Visual Studio generator for VS2008. I would like to selectively apply compile flags on some some source files differently than for other files, and all of these files are going into the same static library (splitting the library into two different targets is not an option at this time). I cannot use set_target_properties in this case because the compile flags must be different. However I discovered something quite odd. The following works (works being defined that I see the /flubber option show up in the AdditionalOptions fields in the .vcproj file CMake generates):
set_property(SOURCE file1.cpp file2.cpp
PROPERTY COMPILE_FLAGS /flubber
)
But this does not work:
set_property(SOURCE file1.cpp file2.cpp
PROPERTY COMPILE_FLAGS /GR
)
Why is CMake filtering out or ignoring the /GR option? Is that a CMake bug or intentional?
Now this question is a bit contrived given that, circa VS2005, the /GR option was defined to be on by default (gives RTTI), so I really don't have to specify it. But that isn't the point because there are other flags that start with "/G" that are perfectly valid to want to specify on one source file, but not another, and in the same static library target.
A: Visual Studio provides special option for /GR flag:
cmake knows that and transforms your /GR flag into that option. If you open your cmake-generated project file (.vcproj) with notepad, then you can see additional RuntimeTypeInfo="TRUE" attribute inside your file configuration:
/flubber flag added:
<Tool Name="VCCLCompilerTool" AdditionalOptions="/flubber" />
/GR flag added:
<Tool Name="VCCLCompilerTool" RuntimeTypeInfo="TRUE" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to return an encoded JSON string to jQuery call? I do something like this in my PHP AJAX:
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
print json_encode($rows);
My calling JavaScript code is like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
//$("input[type=button]").click(function()
{
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
if(name=='' || problem_blurb == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
How can I transfer the encoded JSON back to the jQuery call, decode it, and output that data? And would it be better to have just looped through the data myself and made the JSON code by concatinating the string together?
Thanks!!
A: set the dataType:'json' so you dont need to parse the json
$.ajax({
type: "POST",
dataType:'json', <----
url: "/problems/add_problem.php", <---- here you call the php file
data: dataString,
success: function(data) <--- here the data sent by php is receieved
{
// data will contain the decoded json sent by server
// you can do data.property that depends upon how the json is structured
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
add_problem.php
$name=$_POST['problem_name']; // get the name here
$desc=$_POST['problem_blurb']; //get the description here
$rows = array();
//fetch data from DB
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
print json_encode($rows); //json encode it and send back to ajax success handler
//or
//echo json_encode($rows);
A: jQuery.getJSON and $.ajax have some parameters, that are passed as per need. "data : JSON" expects output to be in json format. And when you need output, you need to pass a variable in success handler. i.e.
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: JSON, `datastring is replaced by JSON datatype`
success: function(data) `data is json object that will contain the jsonencoded output returned from add_problem.php`
{
for(var i in data)
{
console.log(data[i]) `returns the data at i'th index.`
}
}
});
A: Just do it in your callback function
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: function( data )
{
foreach( var i in data )
// do something
}
});
It's better to json encode it on the server side because it's easier to work with json on the client side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help with format string in scanf Here's the statement:
int i;
scanf("%d ",&i);
Why does the space at the end of the format string causes scanf to accept two inputs instead of 1?
A: The space at the end of the format string tells scanf to eat whitespace after the first integer. It's not actually accepting a second input. When you do enter a second value, scanf sees that the whitespace is finished it returns, storing the first integer into your variable i. The "second input" is still in the standard input stream.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Core Data / Range Update Here is a simple mySQL request :
UPDATE myTable SET X=X-1 WHERE (X>100)
Now my question goes like this.
How would I write a similar request in Core Data ?
I am starting to find out my way in Core Data; but the last part of the above SQL order gives me problems in Core Data.
In other word : how do I handle the WHERE (X>100) part.
If the mySQL request concerned one record only, I would use some thing like this :
[matchItem setValue:VALUE forKey:@"X"];
But how do I do if is a range of records, like here, where I want to perform some actions for all records where X>100.
A: Use an NSPredicate and add it to your NSFetchRequest.
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"X > %@", [NSNumber numberWithInt:100]];
Iterate through your results array and set the value as appropriate.
for (NSManagedObject *match in resultsArray) {
NSInteger newValue = [[match objectForKey:@"X"] intValue] +1;
[match setValue:[NSNumber numberWithInt:newValue] forKey:@"X"];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to disable just vertical scrolling in a UIScrollView? UIScrollView has a property scrollEnabled to disable all scrolling, but I want to disable only the vertical scrolling.
Is that possible? Thanks.
A: If the scrollView's contentSize.height is less than its bounds.size.height it won't scroll vertically.
Try setting:
scrollView.contentSize = (CGSize){<yourContentWidth>, 1.0}
Swift
scrollView.contentSize = CGSize(width: <yourContentWidth>, height: 1.0)
A: - (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
[aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x,0)];
}
you must have confirmed to UIScrollViewDelegate
aScrollView.delegate = self;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: GoogleAppEngine: how to prevent image resize failure for big images I've got to manage some images taken from the client.
Up to now, my code is the following:
Image oldImage = null;
try {
oldImage = ImagesServiceFactory.makeImage(imageBuf);
} catch (Exception e) {
log.severe("Cannot make the image due to " + e);
return;
}
int newWidth = ??; //how can I guess this value to reach a size < 1MB??
int newHeight= ??; //how can I guess this value to reach a size < 1MB??
Transform resize = ImagesServiceFactory.makeResize(newWidth, newHeight);
Image newImage = imagesService.applyTransform(resize, oldImage); //Exception if > 1MB
Such images may exceed the size limit of GAE (1 MB), and I'd like to resize or crop them in order to reach a size of little less than 1 MB (say, 950kB).
How can I achieve this goal?
I cannot directly use the resize method, as I don't know the exact width & height which the image should be resized to.
Moreover, depending on the encoding of the picture (png, jpeg, etc.) the size of the image may vary also using fixed height and width.
I really have no efficient ideas on how to face this issue: the only way I can see a solution is to continue trying with lower and lower dimensions until I get a good-sized image, but this is obviously not acceptable in terms of performances...
Please, help me!!
Thank you very much
Bye
cghersi
A: If you store the images in the blobstore, you can resize much larger images than you can passing the image through your appserver, by using the getServingUrl() function. Since this does not pass its data through the API, it's not limited by the API response size limits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MySQL two different groupings required in one query Struggling to do this with one query:
scores
==========
| child_name | week | behaviour_score | test | test_score |
+---------------------------------------------------------+
| jo | 1 | 75 | 1 | 55 |
| jo | 1 | 75 | 2 | 54 |
| jo | 2 | 71 | 1 | 65 |
| jo | 3 | 68 | 1 | 70 |
| jo | 3 | 68 | 2 | 74 |
| jo | 3 | 68 | 3 | 45 |
Each child takes 1 to n tests each week. Behaviour is recorded as a value for the week, but is stored in each row - so e.g. jo's behaviour for week 1 is 75, and for week 3 is 68. It's not normalised. I know. Wasn't my call.
The table contains records like this for many children.
I am trying to return 1 row per child, with name, sum of behaviour, and sum of test scores.
But because behaviour isnt normalised it must only count the value once per week.
So sum of behaviour above is 75+71+68
And sum of test scores is 55+54+65+70+74+45
My first attempt was
SELECT
child_name,
SUM(behaviour_score),
SUM(test_Score)
FROM results
GROUP BY child_name
But of course, that gives too large a value for behaviour score as it doesnt account for the values being duplicated for a given week.
Is it possible to achieve this with one query?
A: You need to first reduce the data into one row per child, per week with the total test score but only one (let's take the MAX) behavior score), then base your query on that:
SELECT
child_name,
SUM(behaviour_score),
SUM(test_Score)
FROM (
SELECT child_name, MAX(behavior_score), SUM(test_Score)
FROM result GROUP BY child_name, week
) AS OnePerWeek
GROUP BY child_name
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unQL and Django? sorry if this is too earlier to speak about that, but it seems that NoSQL and SQL has made something between them called UnQL (Sqlite and CouchDB), maybe i dident understand the concept, but if that UnQL will be aviable, so Django will behave with him as what? as an SQL or as a NoSql? since they said that the future release of Sqlite will have the UnQL support? and that concept is only restricted to CouchDB and not MongoDB? am really lost! will they add CouchDB options to Sqlite to call it UnQL since they say that Sqlite will have UnQL in the future?! what is that?
A:
it seems that NoSQL and SQL has made something between them called
UnQL (Sqlite and CouchDB), maybe i dident understand the concept, but
if that UnQL will be aviable, so Django will behave with him as what?
as an SQL or as a NoSql?
Target of the UnQL specification is to offer the option/opportunity to implement open and unified querying language functionality among various NoSQL databases and their vendors. Queries in UnQL should be parsable to SQL in order to maintain some level of compatibility with RDBMS world.
since they said that the future release of Sqlite will have the UnQL
support? and that concept is only restricted to CouchDB and not
MongoDB?
The UnQL specification is in it's early stages and although there are already some prototype codes, it's probably 6-8 months away from some major implementation from the side of database vendors. So far the UnQL participants include SQLite, CouchDB (and probably also Couchbase), but I think as time will go on and the specification will take it's form, more vendors would join the effort to participate and support this unified querying language. Concept is not restricted since the specification is open, so it's up to the database vendors if they will support the UnQL.
will they add CouchDB options to Sqlite to call it UnQL since they say
that Sqlite will have UnQL in the future?! what is that?
CouchDB has nothing to do with SQLite and vice versa. Whether CouchDB, SQLite, MongoDB or whatever database will implement UnQL in the future is entirely up to it's vendors/developers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Make a component fill all available space on screen I want something like this:
But I don't know how to resize the TextView so it gets all the available space on screen which is not ocuppied by the EditText or the Buttons. May I do it in the code, or in the xml?
At XML I tried putting the TextView into a FrameLayout, but it makes no difference. Currently looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/consola"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars = "vertical"
android:text="@string/hello"/>
</FrameLayout>
<EditText
android:id="@+id/comando"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:text="Conectar"
android:id="@+id/boton_conectar"
android:layout_width="wrap_content"
android:layout_weight="0.5"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Enviar"
android:id="@+id/boton_enviar"
android:layout_width="wrap_content"
android:layout_weight="0.5"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
</LinearLayout>
At the code I'm just checking if the Buttons are pushed with Listeners. One of them, when pushed, gets the text at the EditText, and appends it to the TextView. It works, and TextView gets higher, while EditText and Buttons downs one line. If I go on appending lines, finaly EditText and Buttons get out of the screen. I want to avoid this behaviour, and accomplish to get this 3 widgets sticked to the bottom of the screen.
A: Use the android:layout_weight=1 attribute, like the buttons on the bottom of the form. That will assign most of the space to it and anything that's left to the rest of the elements.
A: It's all about the weight. This should give you what you want:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:text="TextView"
android:id="@+id/textView1"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
</TextView>
<EditText android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<requestFocus></requestFocus>
</EditText>
<LinearLayout android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button android:text="Button"
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp">
</Button>
<Button android:text="Button"
android:id="@+id/button2"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1">
</Button>
</LinearLayout>
</LinearLayout>
(Side note: When using weight, setting the corresponding height/width to 0dp sometimes gets around some weird behavior.)
A: Try android:fillViewport="true".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adding View to Relative Layout behind an existing view causes screen flicker I'm trying to insert a View behind another view that is taking up the full screen and then later removing the view in the front to reveal the only remaining view. Functionally, everything is working as expected but the problem is that when I call View.addView() to add the second view, specifying to add it at index 0 so it is behind the first view, the screen flickers. It's almost as if the view is actually getting added in front of the first view for a fraction of a second and then it is hidden again as it is moved behind it.
Here's what I'm doing:
When the Activity is created I add an ImageView to a RelativeLayout and make the RelativeLayout instance the Activity's content view:
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
m_layout = new RelativeLayout(this);
m_layout.setBackgroundColor(Color.BLACK);
m_splashImage = new ImageView(this);
m_splashImage.setImageResource(R.drawable.splash);
m_splashImage.setScaleType(ScaleType.FIT_XY);
m_layout.addView(m_splashImage,
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
setContentView(m_layout);
}
When the Activity is started, I created and add the GLSurfaceView to the RelativeLayout at index 0, so it is behind the ImageView:
protected void onStart() {
super.onStart();
m_layout.addView(new MyGLSurfaceView(), 0,
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
}
Later, after all of the loading is done and the GLSurfaceView is ready to continuously render,
the splash ImageView is removed and cleaned up.
public void hideSplashScreen() {
if (m_splashImage != null) {
m_layout.removeView(m_splashImage);
m_splashImage = null;
}
}
Is there a better way to do this that doesn't require creating the GLSurfaceView before the onStart() is called?
A: Have you tried using view.setVisibility(View.GONE) on of the view that you adding behind? Of course before you are adding it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: unmarshalling complex types with Jaxb2 Hi I have following XML and java classes when I unmarshall using JAXB2 processor using Spring OXM framework I am getting all null values. Any idea?
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="AuthentXML",namespace="http://xml.authentify.net/MessageSchema.xml")
public class AuthentifyResult {
private Header header;
public Header getHeader() {
return header;
}
public void setHeader(Header header) {
this.header = header;
}
}
@XmlType(name="", propOrder={"asid", "teid", "replyTo"})
public class Header {
private String asid;
private String teid;
private String replyTo;
public String getAsid() {
return asid;
}
public void setAsid(String asid) {
this.asid = asid;
}
public String getTeid() {
return teid;
}
public void setTeid(String teid) {
this.teid = teid;
}
public String getReplyTo() {
return replyTo;
}
public void setReplyTo(String replyTo) {
this.replyTo = replyTo;
}
}
<?xml version="1.0" ?>
<AuthentXML>
<header>
<asid>AuthenticationSubjectID</asid>
<teid>B6F997AE-FB4E-11D3-80BD-0050DA5DC7B8</teid>
<replyTo>https://r1.authentify.net/s2s/default.asp</replyTo>
</header>
</AuthentXML>
unmarshaling code
FileInputStream is = null;
is = new FileInputStream(FILE_NAME);
this.authentifyResult = (AuthentifyResult) this.jaxbUnmarshaller.unmarshal(new StreamSource(is));
I am receiving null for header in authentifyResult. Why?
A: The only thing I see wrong with your code is that the @XmlRootElement annotation on AuthentifyResult should not specify a namespace since the XML fragment you posted is not namespace qualified:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="AuthentXML")
public class AuthentifyResult {
private Header header;
public Header getHeader() {
return header;
}
public void setHeader(Header header) {
this.header = header;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Exception while creating mssql database jndi resource in Tomcat I am trying to create a Tomcat JNDI resource for MSSQL database.
This is how my resource string looks in tomcat context.xml file
<Resource
name="jdbc/FI/SD"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://LDIA;databaseName=SD"
validationQuery="Select 1"
maxActive="1" maxIdle="1" maxWait="10000"
user="rels"
password="hidden"
/>
This is the code snippet that i am using in Servlet to check datasource:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/FI/SD");
Connection conn = ds.getConnection();
but i am getting this error while creating connection at line 4,
how can i solve this:
org.apache.tomcat.dbcp.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (Login failed for user ''. The user is not associated with a trusted SQL Server connection.)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at com.MyServlet.doGet(MyServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
A: Maybe user should be username instead?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How I can Call Javascript prototype functions? This is the Javascript code to call
the Function Alerts it is from Stage6 that I will fully rebuild to bring it back to live :)
// Alerts (in the header)
function Alerts(total) {
this.current_page = 1;
this.last_page = Math.ceil(total / 4);
if (this.current_page == this.last_page) {
$('alert-next-button').className = 'alert-next-inactive';
}
}
This is the Prototype Function it is from DivX Stage6:
Alerts.prototype.next = function () {
if (this.current_page == this.last_page) {
return;
}
new Effect.BlindUp('alerts-' + this.current_page, {
scaleFrom:80,
duration:0.4,
queue:{
position:'end',
scope:'alerts'
}
});
new Effect.BlindDown('alerts-' + (this.current_page + 1), {
scaleTo:80,
duration:0.4,
queue:{
position:'end',
scope:'alerts'
}
});
this.current_page++;
if (this.current_page > 1) {
$('alert-prev-button').className = 'alert-prev';
}
if (this.current_page == this.last_page) {
$('alert-next-button').className = 'alert-next-inactive';
}
}
The Second Prototype function:
Alerts.prototype.previous = function () {
if (this.current_page == 1) {
return;
}
new Effect.BlindUp('alerts-' + this.current_page, {
scaleFrom:80,
duration:0.4,
queue:{
position:'end',
scope:'alerts'
}
});
new Effect.BlindDown('alerts-' + (this.current_page - 1), {
scaleTo:80,
duration:0.4,
queue:{
position:'end',
scope:'alerts'
}
});
this.current_page--;
if (this.current_page == 1) {
$('alert-prev-button').className = 'alert-prev-inactive';
}
if (this.current_page < this.last_page) {
$('alert-next-button').className = 'alert-next';
}
}
I need the HTML Code for this functions.
It is reverse engineering :=)
Here is the picture from Stage 6
http://img10.imageshack.us/img10/1733/83630697.png
I have all tested but I have no solution.
Hope someone can help me out.
A: Not sure if you are trying to define a prototype function, or call one:
To make a prototype function:
Alerts.prototype.nameYourFunction = function(total) {
this.current_page = 1;
this.last_page = Math.ceil(total / 4);
if (this.current_page == this.last_page) {
$('alert-next-button').className = 'alert-next-inactive';
}
};
replace nameYourFunction to whatever you would like to call it
then you'll be able to call it like so:
Alerts.nameYourFunction(2);
OR to call the one you added to your question:
Alerts.next();
A: mmm... mmm.... var a = new Alerts(5); a.next()????
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Count users from table 2 in request to table 1 I have table with positions
tbl_positions
id position
1 Driver
2 Lobby
3 Support
4 Constructor
and in other table i have users
tbl_workers
id name position
1 John 2
2 Mike 3
3 Kate 2
4 Andy 1
i do request of positions
SELECT position FROM tbl_positions
but i also need to show how many workers are assigned to each position i tried to do separate request
SELECT id FROM tbl_workers WHERE position = 2
but cannot display all together in table cannot bind number of users to position.
How can i make join this queries into one, so it also show positions without workers assigned?
A: join and group by
SELECT p.id, p.position, count(*) FROM tbl_positions as p
inner join tbl_workers as w on w.position=p.id
group by p.id, p.position
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save only 10 Records but delete all others by ID Huge Database I need a solution to remove all records but save last 10 by ID_URL not BY UNIQUE ID (primary Key)..
MY Database Structure and Records View..
I need to save last 10 ITEM of EVERY URL_ID..
EDIT: Maybe most or are you confused what I am asking about.. actually I just want to save NEW 10 EVERY URL_ID records only..
ID IP TIME(TIMESTAMP) BROWSER Visitor_URL URL_ID
11 xxx.xxx.xx.xx 3/15/2010 14:43 Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 V... link_link TYTIP
12 xxx.xxx.xx.xx 3/15/2010 14:43 Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 V... link_link TITPE
13 xxx.xxx.xx.xx 3/15/2010 14:43 Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 V... link_link XAIP
14 xxx.xxx.xx.xx 3/15/2010 14:44 Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 V... link_link TYTIP
15 xxx.xxx.xx.xx 3/15/2010 14:44 Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 V... link_link TYTIP
.....1000's of Other Records
A: Can you make a predefined list of url_id?
Because then you can do:
DELETE FROM table_name
WHERE url_id = 'TITPE'
ORDER BY time DESC
LIMIT 10,18446744073709551615;
This will delete in reverse order, skipping the first 10 rows (and since it's in reverse, those are the most recent rows).
PS. Be sure to test this before trying it on live data.
A: If you are trying to save a very small subset of records and delete the rest, it's much more efficient (in every database engine I'm familiar with) to select those records you're keeping into a temp table, drop and re-create the original table, and then select the records back in.
So for instance something like this:
DROP TABLE IF EXISTS records_temp;
CREATE TEMPORARY TABLE records_temp LIKE original_table;
INSERT INTO records_temp SELECT * FROM original_table WHERE URL_ID = "TYTIP" ORDER BY ID DESC LIMIT 10;
(then do that again for each type)
DROP TABLE original_table;
CREATE TABLE original_table LIKE records_temp;
INSERT INTO original_table SELECT * FROM records_temp;
DROP TABLE records_temp;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Converting dynamic, nicely formatted tabular data in Python to str.format() I have the following Python 2.x code, which generates a header row for tabular data:
headers = ['Name', 'Date', 'Age']
maxColumnWidth = 20 # this is just a placeholder
headerRow = "|".join( ["%s" % k.center(maxColumnWidth) for k in headers] )
print(headerRow)
This code outputs the following:
Name | Date | Age
Which is exactly what I want - the data is nicely formatted and centered in columns of width maxColumnWidth. (maxColumnWidth is calculated earlier in the program)
According to the Python docs, you should be able to do the same thing in Python3 with curly brace string formatting, as follows:
headerRow = "|".join( ["{:^maxColumnWidth}".format(k) for k in headers] )
However, when I do this, I get the following:
ValueError: Invalid conversion specification
But, if I do this:
headerRow = "|".join( ["{:^30}".format(k) for k in headers] )
Everything works fine.
My question is: How do I use a variable in the format string instead of an integer?:
headerRow = "|".join( ["{:^maxColumnWidth}".format(k) for k in headers] )
A: headers = ['Name', 'Date', 'Age']
maxColumnWidth=21
headerRow = "|".join( "{k:^{m}}".format(k=k,m=maxColumnWidth) for k in headers )
print(headerRow)
yields
Name | Date | Age
*
*You can represent the width maxColumnWidth as {m}, and then
substitute the value through a format parameter.
*No need to use brackets (list comprehension) inside the join. A
generator expression (without brackets) suffices.
A: As it says, your conversion specification is invalid. "maxColumnWidth" is not a valid conversion specification.
>>> "{:^{maxColumnWidth}}".format('foo', maxColumnWidth=10)
' foo '
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: HtmlUnit is throwing Out Of Memory and maybe leaking memory I use Selenium with HtmlUnitDriver with javascript enabled and I get Out Of Memory errors (I use Java). I just browse the same page. I am only using a single GET command. Which is the solution to overcome the situation?
A: I've had a similar issue. It ended up being an issue with auto-loading of frames... a feature that can't be disabled.
Take a look at this: Extremely simple code not working in HtmlUnit
It might be of help.
Update
Current version of HtmlUnit is 2.10. I started using HtmlUnit from version 2.8 and each new version ended up eating more memory. I got to a point in which fetching 5 pages with javascript enabled resulted in a process of 2GB.
There are many ways to improve this situation from a javascript point of view. However, when you can't modify the javascript (eg: if you are crawling a site) your hands are tied. Disabling javascript is, of course, the best way to go. However, this might result in fetched pages being different from the expected ones.
I did manage to overcome this situation, though. After many tests, I noticed that it might not be an issue with HtmlUnit (which I thought was the guilty one from the beginning). It seemed to be the JVM. Changing from Sun's JVM to OpenJDK did the trick and now the process instead of eating 2GB of memory only requires 200MB. I'm adding version information.
Sun's (Oracle) 32-bit JVM:
$java -version
java version "1.6.0.26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Server VM (build 20.1-b02, mixed mode)
OpenJDK 32-bit JVM:
$java -version
java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.13) (6b18-1.8.13-0+squeeze2)
OpenJDK Server VM (build 14.0-b16, mixed mode)
Operative system:
$ uname -a
Linux vostro1015 2.6.32-5-686-bigmem #1 SMP Sun May 6 04:39:05 UTC 2012 i686 GNU/Linux
Please, share your experience with this.
A: Give more memory to the JVM by adding this to the java command line that starts the JVM in which Selenium is running:
-Xmx512m
This example give a maximum of 512 Mb to the JVM.
It depends on where you're running Selenium from. If maven, you can add it to the MAVEN_OPTS environment variable, if Eclipse, you'll need to edit the run configuration for the test class, etc.
A: Related to HtmlUnit:
Do not forget to call webClient.closeAllWindows();. I always put it in a finally-block around the area I use the webclient. This way it is sure that all javascript is stopped and all resources are released.
Aslo useful is setting for the webClient:
webClient.setJavaScriptTimeout(JAVASCRIPT_TIMOUT);
webClient.setTimeout(WEB_TIMEOUT);
webClient.setCssEnabled(false); // for most pages you do not need css to be enabled
webClient.setThrowExceptionOnScriptError(false); // I never want Exceptions because of javascript
JAVASCRIPT_TIMOUT should be not too high long running javascript may be a reason for memory problems.
WEB_TIMEOUT think about how long you want to wait maximal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Gaussian connection pattern between 2 different layers of neurons of different size I have code to solve the following problem, but it seems too slow to use (I think O(n^4)). Help a python beginner turn correct code into usable code!
A neuron can be specified by its layer, and a 2 dimensional index. For example, N{0}(1,1) is the neuron in the first layer, 2nd row, 2nd column.
Each neuron is located in 2 dimensional space, and both layers uniformly fill the same space. We can therefore assign an (x,y) coordinate to each neuron based on its 2-dimensional index, and the number of rows/columns its layer has. For example: Let's say the first layer has s0 rows and columns. Then, N{0}(1,1) would be located at (x,y) = (1.5/s0,1.5/s0)
I have to specify a connection pattern between 2 layers of neurons. Let's say the first layer is s0 by s0, and the next is s1 by s1. For each layer, I can give a neuron a unique index by going column first. The output of my function will then be a matrix with s0*s0 rows, and s1*s1 columns: each entry specifies the strength of a connection from layer 0 to layer 1. I want the strength of this connection to be the value of a gaussian function evaluated at the difference between the spatial location (x,y) of the two neurons.
My first approach was to use nested for loops, but this is horribly slow:
def multiscaleNormalConnection(s0,s1,standardDeviationOfGaussian):
C = zeros((scale1**2),(scale2**2)) #connection matrix
sigma = matrix([[standardDeviationOfGaussian**2, 0],[0, standardDeviationOfGaussian**2]])
coeff = power(2*pi*linalg.det(sigma),-.5)
for i in range(C.shape[0]):
for j in range(C.shape[1]):
inColumn = i/scale1
inX = float(inColumn)/s0
inRow = mod(i,scale1)
inY = float(inRow)/s0
outColumn = j/s1
outX = float(outColumn)/s1
outRow = mod(j,scale1)
outY = float(outRow)/s1
dev = array([outX-inX,outY-inY])
C[i,j] = coeff*exp(-0.5*dot(dot(dev.T,sigma.I),dev))
return C
Perhaps there is some way to calculate all the values you will need beforehand?
Are there any python tricks to help me speed this up? If it were matlab I would try to vectorize the code, but I need to write this in python.
Any ideas welcome! Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ETL sync in every sixth hour I need to make a ETL sync to add new data from relational database to the database DW in SSIS. It should take place in every sixth hour.
*
*How do I do it?
*What component do I need?
*Where can I find more material about it in the Internet?
A: You'll need to build a SSIS Package using Business Intelligence Development Studio (which is installed as part of the SQL Server Development tools). You'll then need to execute that package on a server, using a scheduling mechanism of some kind (either an enterprise scheduler, cron, or a windows scheduled job).
The Microsoft website has good information about SSIS. I would also suggest reading about ETL & Data Warehousing in books by Ralph Kimball or Bill Inmon.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: maven build with war and jar pushing odd artifacts to internal repo I have a maven project where I am building a war file, but I am also using the maven-jar-plugin to build a jar in the same project.
--DISCLAIMER--
I know this is not the 'correct' way to do this, but there are some other issues occurring when splitting this into a jar project and a separate war project with some 3rd party plugins.
I am seeing some strange behavior with this. Below is my project structure.
warproject
-src
--main
---webapp
----WEB-INF
-----web.xml
---java
----com.test.myclass
-----test.java
-pom.xml
When I build this project, i get the correct war and jar file in my target directory, however in my local .m2 repo something strange happens. The war file that is installed is named correctly war-jar-0.0.1-SNAPSHOT.war, however the contents of this file are the contents of my jar file. This also occurs if I do the inverse. i.e. if I setup my project to build a jar and use the maven-war-plugin to build the war, the archives in my target directory are correct, but my local repo has jar file with the contents of my war file. Below is the pom file I am using.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>war-jar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<jarName>${project.artifactId}-${project.version}-client</jarName>
</configuration>
<executions>
<execution>
<id>make-a-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
The console output for this is the following, it shows that the jar is being uploaded as the war.
Installing /home/me/work/src/war-jar/target/war-jar-0.0.1-SNAPSHOT.jar to /home/me/.m2/repository/com/test/war-jar/0.0.1-SNAPSHOT/war-jar-0.0.1-SNAPSHOT.war
--UPDATE
I got this working, but I had to change the phase of my 'make-a-jar' execution to install from package. This works fine and the correct artifacts are uploaded, but I am still confused as to why this makes a difference. Obviously the artifact is generated at a different lifecycle phase, and hence is not around at the time of the original install for the project, hence the wrong file is not uploaded. This seems like a 'hack' and I would like to understand why this is behaving this way.
A: I'm answering my own questions since I didn't get any information that helped me get to my solution. See my update on my original question for my solution.
A: This also works,
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<executions>
<execution>
<!--
When also running maven-jar-plugin correct maven-war-plugin's ID
from "default-war" to "default-jar"
-->
<id>default-jar</id>
<phase>package</phase>
<goals><goal>war</goal></goals>
<configuration>
...
</configuration>
</execution>
</executions>
</plugin>
Refer to http://maven.apache.org/guides/mini/guide-default-execution-ids.html
To figure out why your project behaves as is, analyze the Effective POM.
A: You need to specify the configurations for the maven-install-plugin to achieve this. Add the following plugin config under <build>.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>install-file</goal>
</goals>
<configuration>
<packaging>jar</packaging>
<artifactId>${project.artifactId}</artifactId>
<groupId>${project.groupId}</groupId>
<version>${project.version}</version>
<file>
${project.build.directory}/${project.artifactId}-${project.version}.jar
</file>
</configuration>
</execution>
</executions>
</plugin>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Foursquare userless search iOS is there a way to fetch the venues search in iOS without the user entering his password or showing some foursquare oauth website?
I don't think that this oAuth makes any sense for this kind of request, it should be just an REST api like so "https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=JN00ABQBOCK5V54FQ1TWQFLOOIDU12UAZXURHXGXNK0ESJBY&client_secret=14ES1NXTCL1XC5HSLBUT4LWE4ROEDGNYKKWGGERZQGUKQ5JC"
but this one is deprecated =/
Any thoughts?
A: It's not deprecated, you're just missing the "versioning" parameter that specifies what version of the API you're trying to use.
Requesting https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=JN00ABQBOCK5V54FQ1TWQFLOOIDU12UAZXURHXGXNK0ESJBY&client_secret=14ES1NXTCL1XC5HSLBUT4LWE4ROEDGNYKKWGGERZQGUKQ5JC&v=20111107 will remove the warning you saw in your response
A: Add a query string parameter to your request as follows..
&v=20111119 // Choose a proper version.
Update: this is actually a date. So make sure you send current date in yyyymmdd format against v parameter.
A: According to FourSquare's docs page on venue searching an acting user is no longer necessary:
Some endpoints (e.g. venue search) allow you to not act as any
particular user. We will return unpersonalized data suitable for
generic use, and the performance should be slightly better. In these
cases, pass your client ID as client_id and your client secret as
client_secret. Although the draft 11 of the OAuth2 spec provides a
mechanism for consumers to act via token entitled Client Credentials,
we do not currently support this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tying Model to Query Result in CodeIgniter? Here is what their documentation says
You can also pass a string to result() which represents a class to
instantiate for each result object (note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user) {
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
Despite the fact that they are echoing $row instead of $user... this does not seem to work for me. Here is my version of testing it
Model
class User extends CI_Model{
var $first;
var $last;
..
function getName() {
return $this->first + " " + $this->last;
}
}
Controller
class Tester extends CI_Controller {
public function index() {
$this->load->model('User');
$query = $this->db->query('SELECT * from USERS');
$data = array (
'regular' => $query->result(),
'modeled' => $query->result('User')
);
$this->load->view('test', $data);
}
}
View
foreach ($regular as $row) {
echo "{$row->FIRST} {$row->LAST} <BR/>";
}
echo "<br/>";
foreach ($modeled as $row) {
echo "{$row->getName()} <BR/>";
}
Is there something that I'm doing wrong or misunderstanding? I would assume that based on their documentation, that if I assign a class to the result set, the class should be populated with the results? Now, how it goes on knowing which field to map to is a mystery to me and may very well be the reason why this doesn't work. I thought perhaps I needed to modify the constructor to do this mapping but I didn't see any documentation as to how I would go about doing that. I tried putting in a parameter for the constructor assuming it was an StdClass array but didn't seem to work.
Any clarifications would be great!
A: So it dawned on me to check the actual source code of the db_results function and I figured that it's due to the case of the query result columns. And it seems that CI defaults everything to UPPERCASE unless you specify it as lowercase in your query string.
So in conclusion, whatever the case of columns is in your query, should be the case of values in your Model!
Seems ridiculous though... I'll probably see if I can edit the core class to not be case-sensitive. Unless someone has better alternatives.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SDL and aalib: No SDL_KEYUP event? I have my small project in which I use SDL, and I was playing around with the different available drivers. I came across the aalib driver, and I realized the SDL_KEYUP event was never called.
This, however, happens only in certain conditions. The event is sent when using the X driver, however not when using in console mode (ie. using Ctrl + Alt + F1).
Here is a minimal code to test this:
#include <SDL/SDL.h>
#include <stdio.h>
int main()
{
SDL_Init(0);
SDL_SetVideoMode(64, 64, 32, SDL_SWSURFACE);
while(1)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type == SDL_KEYDOWN)
printf("Key down: %d\n", event.key.keysym.sym);
else if(event.type == SDL_KEYUP)
printf("Key up: %d\n", event.key.keysym.sym);
else if(event.type == SDL_QUIT)
SDL_Quit();
}
}
}
Then, to run it with aalib:
env SDL_VIDEODRIVER=aalib ./a.out
My question is: Is this to be considered a bug? Or is it something aalib cannot know because of the console won't give this information?
If aalib cannot have this information, I find it a shame SDL cannot provide the same features for all it's drivers.
OS: FreeBSD 8.2
SDL version: 1.2.14
A: TTYs (such as the console) don't receive raw keyboard events at all; they only receive a single "character input" event. You may find that modifier keys (e.g, shift) don't fire SDL events at all, because there's no corresponding character sent.
This is an inherent limitation of the TTY layer. SDL isn't really to blame.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: SQL Query to find Parent-Child Child-Parent relationships? o_O
If I have the following records in a table:
Parent Child
1 2 <--
2 1 <--
3 2
3 4
etc...
And I want to identify records that are both the parent of their child AND the child of their parent such as the 2 records identified by arrows above, how would I accomplish this?
I am trying to run some recursive SQL on this table, but these items are causing an infinite loop. I would like to identify these items so they can be addressed manually.
My brain is fried-enough from messing with recursive queries, I have nothing left to solve this one. Please help :)
A: If understood you well, you don't need recursion at all:
SELECT a.parent, a.child
FROM table1 a
INNER JOIN table1 b ON (b.child=a.parent and a.child = b.parent)
You might want to use LEFT JOIN instead of INNER if you also need to display rows that don't satisfy condition .
A: The following query will work in your example case. If it needs more you'll have to extend the demonstration information
;WITH CTE_DATA AS (
Select Parent = 1, Child = 2
union Select Parent = 2, Child = 1
union Select Parent = 3, CHild = 2
union Select Parent = 3, Child = 4
)
select
d1.*
from
CTE_DATA d1
join CTE_DATA d2 on d1.Child = d2.Parent and d2.Child = d1.Parent
A: DECLARE @YourTable TABLE (Parent INT, Child INT)
INSERT INTO @YourTable
SELECT 1, 2
UNION
SELECT 2, 1
UNION
SELECT 3, 2
UNION
SELECT 3, 4
SELECT *
FROM @YourTable A
INNER JOIN @YourTable B
ON A.Parent = B.Child AND A.Child = B.Parent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Writing formatted XML with XmlWriter I'm trying to write to an XML file to the isolated storage but I would like to format it like this:-
<SampleData>
<Item Property1="AliquaXX" />
<Item Property1="Integer" />
<Item Property1="Quisque" />
<Item Property1="Aenean" />
<Item Property1="Mauris" />
<Item Property1="Vivamus" />
<Item Property1="Nullam" />
<Item Property1="Nam" />
<Item Property1="Sed" />
<Item Property1="Class" />
</SampleData>
but I'm buggered if I can work it out, can anyone help?
A: I suspect you need to create an XmlWriterSettings with the behaviour you want (indentation etc) and then pass that to the XmlWriter on creation. Just setting Indent to true may well be enough:
XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
using (XmlWriter writer = XmlWriter.Create(..., settings))
{
...
}
A: You can customize the xml output via the XmlWriterSettings.
You didn't include any code, but you can set the XmlWriterSettings when you create the XmlWriter. You can also just use something like:
var myXmlWriter = new XmlWriterSettings { Indent = true };
A: If, like me, you're implementing your own XmlWriter you can do:
var myXmlWriter = new MyXmlWriter(stream, System.Text.Encoding.UTF8)
{
Formatting = Formatting.Indented
};
or do this.Formatting = Formatting.Indented in it's constructor.
A: You can use DataSet.GetXML()
Dim column As DataColumn
For Each column In DataSet.Tables.Item(0).Columns
column.ColumnMapping = MappingType.Attribute
Next
Dim xml As String = DataSet.GetXml()
It is not related to XmlWriter but you can use it for formatting XML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Obj-c let me change the class of a variable, and its bad: How hunt it? Well, in obj-c have the ability of change the class of a declared var. So if I declare myVar as a NSString, is possible to get back later a NSNUmber.
I have this problem now, but I can't find where in my code is the identity swap... exist a way to find it? For example is possible to set a breakpoint where [myVar class] == [NSString class] and when change know it?
A: You may be confused about the static type of a pointer, and the actual type of the object it points to. Consider this code:
NSString *test = @"test";
NSNumber *notReallyANumber = (NSNumber *)test;
This is valid code, but it didn't "transform" test into an NSNumber. It's still a string, just with an incorrect type on the pointer.
Basically, no, you don't have the ability to change the class of a variable (you do, but it's deep deep magic and almost never occurs).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Template Type input used as Template Type for Member Property C++ So I am trying to have one template class be a container (that will later operate on) a set of contained classes, also generated from a template, and stored in a vector.
The abstracted form of what I'm trying to do would look like this:
template <typename T, size_t numberofapples>
class Apples {
public:
Apples(std::vector<T> appleinfo1, std::vector<T> appleinfo2);
protected:
std::vector<T> apple_stats;
std::vector<T> info1, info2;
};
template <typename T, size_t numberofapples>
Apples<T, numberofapples>::Apples(std::vector<T> appleinfo1, std::vector<T> appleinfo2) : apple_stats(numberofapples, 0){
for (size_t i = 0; i < numberofapples; ++i) {
apple_stats[i] = rand();
}
info1 = appleinfo1;
info2 = appleinfo2;
}
template <typename T, typename FruitType, size_t numberoffruitperbranch>
class Tree {
public:
Tree(size_t numberofbranches, std::vector<T> commonfruitinfo1, std::vector<T> commonfruitinfo2);
protected:
std::vector<FruitType<T, numberoffruitperbranch> > branchset;
};
template <typename T, typename FruitType, size_t numberoffruitperbranch>
Tree<T, FruitType, numberoffruitperbranch>::Tree(size_t numberofbranches, std::vector<T> commonfruitinfo1, std::vector<T> commonfruitinfo2) : {
typename FruitType<T, numberoffruitperbranch> single_fruit(fruitinfo1, fruitinfo2);
branchset.resize(numberofbranches, single_fruit);
//in the un-abstracted version that has nothing to do with fruit, I'd then iterate over the vector and run some internal code on each one
}
The goal is that I'd like to be able to do something like:
Tree<double, Apples, 10> MyFirstTree(5, vectorofdata, secondvectorofdata);
At the moment, however, the compiler is telling me that FruitType is not a valid template inside the constructor function. In fact, everything inside the constructor appears to be out of scope and is being flagged, but I can't figure out why. The unabstracted version also does have a number of other member variables and functions, but the problem is definitely in the constructor of the outer class container.
Where am I going wrong/how could this be done better?
edit: fixed some compiler errors (I think) which I noticed were different from this trivial example that I did not make in the actual application
A: You want to declare FruitType as a template template parameter:
template<..., template <typename, size_t> typename FruitType, ...>
A: As @MSN mentioned, you need to use nested templates. In your case they take the form of:
template<typename T, size_t nr, template <typename, size_t> class FruitType>
class Tree { ... };
And they are used this way:
Tree<double, 20, Apple> someTree;
Real example from the code you have provided (compiles under VC++ 2010):
#include <iostream>
#include <vector>
template <typename T, size_t numberofapples>
class Apples {
public:
Apples(std::vector<T> appleinfo1, std::vector<T> appleinfo2);
protected:
std::vector<T> apple_stats;
std::vector<T> info1, info2;
};
template <typename T, size_t numberofapples>
Apples<T, numberofapples>::Apples(std::vector<T> appleinfo1, std::vector<T> appleinfo2) : apple_stats(numberofapples, 0){
for (size_t i = 0; i < numberofapples; ++i) {
apple_stats[i] = rand();
}
info1 = appleinfo1;
info2 = appleinfo2;
}
template <typename T, size_t numberoffruitperbranch, template <typename, size_t> class FruitType>
class Tree {
public:
Tree(size_t numberofbranches, std::vector<T> commonfruitinfo1, std::vector<T> commonfruitinfo2);
protected:
std::vector<FruitType<T, numberoffruitperbranch> > branchset;
};
template <typename T, size_t numberoffruitperbranch, template <typename, size_t> class FruitType>
Tree<T, numberoffruitperbranch, FruitType>::Tree(size_t numberofbranches, std::vector<T> commonfruitinfo1, std::vector<T> commonfruitinfo2) {
typename FruitType<T, numberoffruitperbranch> single_fruit(commonfruitinfo1, commonfruitinfo2);
branchset.resize(numberofbranches, single_fruit);
//in the un-abstracted version that has nothing to do with fruit, I'd then iterate over the vector and run some internal code on each one
};
int main()
{
Tree<double, 10, Apples> someTree(20, std::vector<double>(), std::vector<double>());
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make Xcode ignore LLVM build warnings in 3rd party project I have a third party project in my Xcode workspace (it's a dependency for my main project) and I want Xcode to ignore all build warnings from that third party project.
Preferably I'd like to ignore all build warnings for the Vendor/* group in my project since that's where I put all my third party code.
Possible?
A: Yes, it's possible, but only if you compile the third-party files in a separate target. This way, you can set different compiler flags.
Let's say your main target is an application. You defined your build settings, as well as the compiler warning flags.
Now you want to use some third-party sources. You import them into your project, but they generate warning. You could of course change your main target's settings, but I'm pretty sure you want to keep your own settings.
Simply create an additional target in your project, which is a static library.
Removes the third-party files from your main target, and add them to the library.
In your main target's build phases, link your application with the static library.
This way, you'll be able to use the third-party code in your application, while having different compiler settings for third-party code.
A: It is possible on a per file basis, see the blog entry at http://blog.bluelightninglabs.com/2011/12/suppressing-xcode-warnings-on-a-per-file-basis/
To summarize: Use the compiler flags on the “Build phases” tab.
A: Go to Build Phases > Compile Sources. Optionally filter the list. Select the ones you want to exclude and then double click in the blank area under the Compiler Flags column. Add -w and hit return:
A: if you are worried only about warning via inclusion, then you can wrap your include statements in this:
#pragma clang diagnostic push
// in reality, you will likely need to disable *more* than Wmultichar
#pragma clang diagnostic ignored "-Wmultichar"
#include <TheirLibrary/include.h>
#pragma clang diagnostic pop
if you also want to disable the build warnings it generates, then you can use -w or GCC_WARN_INHIBIT_ALL_WARNINGS = YES for the third party target which you link to or bundle.
ideally, you will file reports with the vendor if it is closed. if it is open, then maybe you should just patch it yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Object prototype being included in array I'm working on a function that pulls the lat/lng from an MVCArray of markers. The function is below. However, each object in the mapData array contains the prototype of the native object, along with lat/lng. I have played around with hasOwnProperty, but without much luck. Am I doing something obviously wrong here?
function prepareMarkers() {
var mapData = [];
// All we need from our markers list is the coordinates of the marker and title if it has one
markers.forEach(function(elem, index) {
mapData.push({
lat: elem.getPosition().lat(),
lng: elem.getPosition().lng()
});
});
return mapData;
}
A: You are putting native objects into the mapData array. That's what this is. It's an object.
{
lat: elem.getPosition().lat(),
lng: elem.getPosition().lng()
}
So, it's working exactly as it should. Since they are objects, they should have the methods from the prototype of the native object. Is there a particular problem you are trying to solve here? Everything you've described so far sounds correct.
In your array, you can just access things like this:
var latitude = mapData[0].lat;
var longitude = mapData[0].lng;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to format numbers to significant digits using STL I'm trying to format numbers to a specific number of significant digits using C/C++ and preferably STL. I've seen examples of doing this in Javascript (toPrecision()) and .Net, but I can't find anything on doing this in C/C++. I want to create a function something like this:
std::string toPrecision(double value, int significantDigits) {
std::string formattedString;
// magic happens here
return formattedString;
}
So that it produces results like this:
toPrecision(123.4567, 2) --> "120"
toPrecision(123.4567, 4) --> "123.4"
toPrecision(123.4567, 5) --> "123.45"
Does anyone know a good way to do this? I'm considering dumping the whole number into a string and then just scanning through it to find the non-zero digits and count them off in some intelligent way, but that seems cumbersome.
I could also download the source code to one of the browsers and just see what their toPrecision function looks like, but I think it would take me all day to work through the unfamiliar code. Hope someone can help!
A: Stolen from another question:
#include <string>
#include <sstream>
#include <cmath>
#include <iostream>
std::string toPrecision(double num, int n) {
https://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits
if(num == 0) {
return "0";
}
double d = std::ceil(std::log10(num < 0 ? -num : num));
int power = n - (int)d;
double magnitude = std::pow(10., power);
long shifted = ::round(num*magnitude);
std::ostringstream oss;
oss << shifted/magnitude;
return oss.str();
}
int main() {
std::cout << toPrecision(123.4567, 2) << "\n";
std::cout << toPrecision(123.4567, 4) << "\n";
std::cout << toPrecision(123.4567, 5) << "\n";
}
A: Check out setprecision() in iomanip. That should do what you are looking for on the double, then just convert to string
A: Print it to an ostringstream, setting the floating-point formatting parameters as appropriate.
A: The method above with a ceil(log10(x)) is perfectly legit to determine the number of digit of the integer part of a number. But I feel it's a bit heavy on CPU to call for maths functions just to set a number of digit.
Isn't that simpler to convert the floating value into a string with too many digits, then to work on the string itself?
Here is what I'd try (with Qt instead of the STL):
QString toPrecision(double num, int n) {
QString baseString = QString::number(num, 'f', n);
int pointPosition=baseString.indexOf(QStringLiteral("."));
// If there is a decimal point that will appear in the final result
if (pointPosition != -1 && pointPosition < n)
++n ; // then the string ends up being n+1 in length
if (baseString.count() > n) {
if (pointPosition < n) {
baseString.truncate(n);
} else {
baseString.truncate(pointPosition);
for (int i = n ; i < baseString.count() ; ++i)
baseString[i]='0';
}
} else if (baseString.count() < n) {
if (pointPosition != -1) {
for (int i = n ; i < baseString.count() ; ++i)
baseString.append('0');
} else {
baseString.append(' ');
}
}
return baseString ;
}
But the question was about the STL.. So, let's rewrite it that way:
std::string toPrecision(double num, size_t n) {
std::ostringstream ss;
ss << num ;
std::string baseString(ss.str());
size_t pointPosition=baseString.find('.');
if (pointPosition != std::string::npos && pointPosition < n)
++n ;
if (baseString.length() > n) {
if (pointPosition < n) {
baseString.resize(n);
} else {
baseString.resize(pointPosition);
for (size_t i = n ; i < baseString.length() ; ++i)
baseString[i]='0';
}
} else if (baseString.length() < n) {
if (pointPosition != std::string::npos) {
baseString.append(n-baseString.length(),'0');
} else {
baseString.append(n-baseString.length(),' ');
}
}
return baseString ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: From CObArray to ArrayList I have some pieces of C++ code that store objects in CObArray. I want to re-code the same pieces in Java using ArrayList to store the same objects. Will there be any difference in the overall efficiency?
So is ArrayList the exact correspondent class for CObArray?
A: I didn't know what a CObArray was: CObArray is part of MS's C++ implementations.
They description of a CObArray sounds like it behaves in a similar fashion to an ArrayList. That is, in terms of implementation and performance. You should bare in mind that the interfaces will differ for sure. For example, Java's ArrayList does not have anything like GetUpperBound(). If you depend on something like this, you sure ensure you can live without corresponding methods.
In addition, the preferred way to work with ArrayList's in Java is by the use of Generics (specify the type that will exist in the collection at compile-time as opposed to casts performed at run-time). This sounds like it may differ from how it works with CObArray's according to AJG85. You must also ensure that before you begin your conversion to Java that you are aware of differences like this and how they work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: css element margin for Firefox with Linux OS I designed this website, and I have been unable to place an the element ( div#endinglogo ) in a way that renders properly for firefox / Linux operating system users.
http://motivacionenlinea.com/
I am working with all browsers in windows 7, and although the design appears as it should in the firefox with MY operating system, my guesses to fix firefox/Linux have not worked.
My questions is what is proper margin to give to element div#endinglogo for it to appear where it should.
I have attached two images below.
The first shows how I want the header to look:
http://postimage.org/image/rsd27dvo/
The second shows how I been told it appears in browser firefox when using linux operating system:
http://postimage.org/image/rtgr3pqc/
I have a php file that serves firefoxLinux.css file, or at least that is the intent. Is this file being loaded when you see this website through firefox/linux?
Thank you for your help
A: In your firefox.css, you have a different negative top margin for your div#endinglogo. Make it -110px (like it is in your chrome.css file) and it should work.
On a related sidenote though, why are you creating multiple stylesheets for different browsers? For most things there are solutions that work consistently across browsers and operating systems, and only in a few cases do you need special styles (i.e. for IE, maybe some older versions of firefox). I think if you were to consolidate your styles you would run into less problems. Of course that's just my two cents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS browser detection for radial gradient? I'm using a radial gradient as the background for a website. It works great on Safari, Chrome, and Firefox 3.5+, but Opera and Internet Explorer have problems. So, I made a background image to show on those browsers to give the same look. Right now, I'm detecting the browser and version server-side from the user-agent, and then including the correct CSS file. However, I feel like there must be a better way than having to maintain two seperate CSS files to do essentially the same thing (the only difference between the CSS files is html and body).
For good browsers:
html, body {
width: 100%;
height: 100%;
}
html {
background-image: -ms-radial-gradient(center, circle farthest-side, #23395D 0%, #122037 60%, #0A131F 100%);
background-image: -moz-radial-gradient(center, circle farthest-side, #23395D 0%, #122037 60%, #0A131F 100%);
background-image: -o-radial-gradient(center, circle farthest-side, #23395D 0%, #122037 60%, #0A131F 100%);
background-image: -webkit-gradient(radial, center center, 0, center center, 480, color-stop(0, #23395D), color-stop(0.6, #122037), color-stop(1, #0A131F));
background-image: -webkit-radial-gradient(center, circle farthest-side, #23395D 0%, #122037 60%, #0A131F 100%);
background-image: radial-gradient(center, circle farthest-side, #23395D 0%, #122037 60%, #0A131F 100%);
-moz-box-shadow:inset 0 0 100px #080f1a;
-webkit-box-shadow:inset 0 0 100px #080f1a;
box-shadow:inset 0 0 100px #080f1a;
background-attachment: fixed;
}
body {
font-family: arial, sans-serif;
font-size: 14px;
color: #fff;
line-height: 22px;
text-decoration: none;
background: url(/images/portal/checkered_bg.png) repeat;
}
For bad browsers:
html, body {
width: 100%;
height: 100%;
}
body {
font-family: arial, sans-serif;
font-size: 14px;
color: #fff;
line-height: 22px;
text-decoration: none;
background: #09101b url(/images/portal/big_bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/portal/big_bg.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/portal/big_bg.jpg', sizingMethod='scale')";
}
A: Sounds like a job for Modernizr.
Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or not.
A: Rather then browser detection, use feature detection, a JavaScript plugin such as Modernizr will do the job very neatly.
It adds class names to the root element so you can check for it like in your css.
A: When you try to apply css that the browser doesn't recognize, it just reports nothing, so if you do...
//ommiting document ready for brevity
if ($("html").css("background-image").indexOf("radial") < 0) {
$("html").addClass("no-radial")
}
Then you can override the classes in CSS:
.no-radial body {
font-family: arial, sans-serif;
font-size: 14px;
color: #fff;
line-height: 22px;
text-decoration: none;
background: #09101b url(/images/portal/big_bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/portal/big_bg.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/portal/big_bg.jpg', sizingMethod='scale')";
}
A: Modernizr is your friend...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there an opposite command to git archive for importing zip files Our local workflow tends to use a sequence of zip files as the local 'source control' before major revisions are formalised into the 'big' company SCM system. I'm trying to introduce git as a better local SCM method. The current workflow is quite effective for our small team, particularly as test machines are off net, as zip transfer is easy, so I need to be able to dovetail the two methods.
Is there a git command(s) that will import a project zip file and perhaps commit it?
Or is it a case of manually checking that the local working directory/branch is clean git status, remove all current content git rm *, unzip the zip file into the directory, add all git add ., and finally commit git commit -a -m "filename.zip". We are working on Windows, so minimising opportunities for mistakes is important, so the fewer commands the better!
This will at least allow reticent existing users to decide when to make the git switch, while still getting the repo up and running.
Any suggestions on suitable commands or scripts?
A: Why dont you crate a git alias for unarchive which runs all the commands you mentioned in your question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Change KEyBoard Layout via flash ( web )? Is it possible to activate alt+shift ( change language) Via JS and some Flash
like copy to clipboard plugin etc. ( via flash).
A: No. Only the user can change the active keyboard layout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to replace " \ " with " \\ " in java I tried to break the string into arrays and replace \ with \\ , but couldn't do it, also I tried String.replaceAll something like this ("\","\\");.
I want to supply a path to JNI and it reads only in this way.
A: Don't use String.replaceAll in this case - that's specified in terms of regular expressions, which means you'd need even more escaping. This should be fine:
String escaped = original.replace("\\", "\\\\");
Note that the backslashes are doubled due to being in Java string literals - so the actual strings involved here are "single backslash" and "double backslash" - not double and quadruple.
replace works on simple strings - no regexes involved.
A: You could use replaceAll:
String escaped = original.replaceAll("\\\\", "\\\\\\\\");
A:
I want to supply a path to JNI and it reads only in this way.
That's not right. You only need double backslashes in literal strings that you declare in a programming language. You never have to do this substitution at runtime. You need to rethink why you're doing this.
A: It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\" in a regex expression.
here is the link where i found this information: https://www.rgagnon.com/javadetails/java-0476.html
I had to convert '\' to '\\'. I found somewhere that we can use:
filepathtext = filepathtext.replace("\\","\\\\");
and it works.
Given below is the image of how I implemented it.
https://i.stack.imgur.com/LVjk6.png
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How to set up htaccess rewrite for multiple variables? I originally created SEO friendly links for my site. I wanted my links for my coupon code site to look like:
http://www.mydomain.com/site/bodybuilding.com
So I did a rewrite in the htaccess that worked:
RewriteRule ^site/(.*)$ retailertest3.php?linklabel=$1
Now, I'm working on creating a custom affiliate program. I want users to be able to send traffic to a link like:
http://www.mydomain.com/site/bodybuilding.com?ref=john
How would I go about modifying the rewriterule so that the ref variable is passed properly to retailertest3.php?
Also, after I get the value of the ref variable and do some stuff with it, is it possible to do a 301 redirect back to the original URL of:
http://www.mydomain.com/site/bodybuilding.com
I'm trying to avoid possible canonical issues like this, as well as keep everything looking clean.
Any help is greatly appreciated!!!!!
Any help is greatly appreciated!!!!
A: This should do the job:
RewriteRule ^site/(.*)$ retailertest3.php?linklabel=$1&%{QUERY_STRING}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need help posting to my own wall in Facebook with PHP The code below is not working for some reason:
require './facebook.php';
$facebook = new Facebook(array(
'appId' => 'working_app_id',
'secret' => 'working_secret'
));
// Get User ID
$user = $facebook->getUser();
$token = $facebook->getAccessToken();
print $token; // token shows.
$attachment = array
(
'access_token'=>$token,
'message' => 'This is where the message will go.',
'name' => 'Name Text',
'link' => 'http://www.website.com',
'description' => 'Description text.'
);
$result = $facebook->api('/me/feed/','post',$attachment);
exit;
I am getting the following error:
Uncaught OAuthException: An active access token must be used to query information about the current user.
When I print the token, it appears to be a real token. I just have no idea what I could be doing wrong. All I want to do is post a very simple status update to my own page.
I don't know why I can't seem to figure this out. I'm banging my head against the wall on this one because it should just be so simple to post a quick little status update to my wall in Facebook from PHP.
Note: The App Type I created to get my appID and secret was a "Website".
A: Check out this answer, it appears that you are using the wrong method to get your access token.
Howto use FB Graph to post a message on a feed (wall)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535325",
"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.