text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: PHP regex output converting I want to turn a output like 12h 34m 45s to 12:34:45
also it should be possible if one o these is returned empty is will ignore it.
So 34m 45s should be 00:34:45 and off course single digits should bee possible like 1h 4m 1s and a combo off single and double digits like 12h 4m 12s and so on.
Can someone please help ?
This is the actual code
$van = $_POST['gespreksduur_van'];
$tot = $_POST['gespreksduur_tot'];
$regex = '/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/';
if(preg_match($regex, $van, $match) AND preg_match($regex, $tot, $matches))
{
for ($n = 1; $n <= 3; ++$n) { if (!array_key_exists($n, $match)) $match[$n] = 0; }
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; }
$van = printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]);
$tot = printf("%02d:%02d:%02d", $match[1], $match[2], $match[3]);
print($van);
print($tot);
$data['gespreksduurvan'] = htmlspecialchars($van);
$data['gespreksduurtot'] = htmlspecialchars($tot);
$smarty->assign('gsv',$data['gespreksduurvan']);
$smarty->assign('gst',$data['gespreksduurtot']);
}
A: You can use a regex to extract the components, and then a printf() to format the components how you like:
$time = "1h 45m";
preg_match("/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/", $time, $matches);
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; }
printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]);
The regex allows optional components. The for loop there just fills any missing keys with a default value of zero (to prevent undefined key errors when seconds, or both minutes/seconds are missing). The printf always prints all components with two zeros.
A: If you want to use regex, you can use preg_replace_callback
<?php
function callback($matches)
{
var_dump($matches);
if ($matches[2] == "") $matches[2] = "00";
if ($matches[4] == "") $matches[4] = "00";
if ($matches[6] == "") $matches[6] = "00";
return $matches[2] . ":" . $matches[4] . ":" . $matches[6];
}
$str = "12h 34m 45s";
$str = preg_replace_callback("`(([0-2]?[0-9])h )?(([0-5]?[0-9])m )?(([0-5]?[0-9])s)?`", "callback", $str, 1);
echo $str;
A: this is how you can do this without regex
// function for your purpose
function to_time($str){
$time_arr = explode(' ', $str);
$time_h = '00';
$time_m = '00';
$time_s = '00';
foreach($time_arr as $v){
switch(substr($v, -1)){
case 'h': $time_h = intval($v); break;
case 'm': $time_m = intval($v); break;
case 's': $time_s = intval($v); break;
}
}
return $time_h . ':' . $time_m . ':' . $time_s;
}
//test array
$time[] = '1h 45s';
$time[] = '12h 35m 45s';
$time[] = '1m 45s';
// output
foreach($time as $t)
var_dump(to_time($t));
This outputs
string '1:00:45' (length=7)
string '12:35:45' (length=8)
string '00:1:45' (length=7)
A: $string = "12h 34m 45s";
$string = str_replace(array("h","m","s"), array(":",":",""), str_replace(" ", "", $string));
echo $string;
Something like this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get automatic SCHEMA UPDATE on an existing DB with JPA/Hibernate? I am trying to update my existing DB schema automatically with JPA-based app (I am using Hibernate as a Persistence provider). What I did is that I have positioned my hbm2dll param to "update" like this in the persistence.xml :
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
...
</properties>
But it seems that Hibernate can not handle the schema generation.
Can you please tell me how I can automatically update my running DB schema with JPA/Hibernate if any other option than the hbm2dll is available?
A: Don't do that in production. Write your schema manually and then maintain it using Liquibase or something similar.
A: Your setting is correct ,but database must be created manually.Hibernate will create tables.And you can also set value to create,update .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to move object upwards at exact point - Unity I am new in unity. Here is my scenario which I want to implement.
I have a enemy and a tower.
Enemy collides with tower and move to the top of tower to escape from it.
I am unable to move enemy at exact position of towers top.
here is my code:
void OnTriggerEnter(Collider collider) {
moveY = tf.position.y + 6; //6 is the height of tower
tf.Translate(0, moveY, 0, Space.World);
}
If I use position instead of translate it moves to towers top position, but I want to walk the enemy towards top of tower. Using translate moves enemy more towards bottom. Pls help me with this
A: Most probably the problem is your code doesn't recognize tf. try this:
void OnTriggerEnter(Collider collider)
{
moveY = collider.position.y + 6; //6 is the height of tower
collider.Translate(0, moveY, 0, Space.World);
}
If it is gameobject tf that is colliding, tf will be the collider. You will want to put in a if condition check to ensure the collider is tf.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: URL Referer not working on pop up windows I have two pages namely www.abc.com/pg1.aspx and www.abc.com/pg2.aspx
pg1.aspx
response.redirect("www.abc.com/pg2.aspx");
pg2.aspx
string url_refer = Request.UrlReferrer.ToString();
UrlReferrer is working fine.
pg1.aspx
<a href='#' onclick=\"window.open('www.abc.com/pg2.aspx', 'windowname2', 'width=1014, height=709, screenX=1, left=1, screenY=1, top=1, status=no, menubar=no, resizable=no, toolbar=no'); return false;\">
pg2.aspx
string url_refer = Request.UrlReferrer.ToString();
UrlReferrer is NULL
I googled for the solution. but none of them are leading to the solution i want.
My problem is if the window is with no menubar, status or toolbar, UrlReferrer is NULL
if not, UrlReferrer has the previous page's URL.
I also tried url_refer = Request.ServerVariables["HTTP_REFERER"].ToString(); instead of string url_refer = Request.UrlReferrer.ToString();.
the result is the same.
Any solution?
A: My solution is to take it from "document.referrer"
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('hfUrlReferrer').value = document.referrer;
})
A: <a href="javascript:void(0);" onClick="MyWindow=window.open('','gallery','location=no,directories=no,menubar=no,scrollbars=no,width=550,height=550');MyWindow.location.href='yoururl.html;MyWindow.focus(); return false;">
The trick is to use location.href which does record the referer in IE.
A: I found this great workaround on a forum, and adapted it slightly.
Put this code at the top of your page:
<script language="JavaScript">
function goTo(url){
var link = document.getElementById("link");
link.href = url;
link.click();
}
</script>
<a id="link" target="_blank" href="javascript:void(0)"
style="visibility:hidden;position:absolute;"></a>
...and then build your links like this:
<input type="button" value=google onclick="goTo('http://www.google.com')">
What you're doing is creating an invisible <a> element, then using javascript to change that element's address, and programatically "click" it.
A: There's no easy answer to this - in general, the UrlReferrer is a browser-specific behaviour. Chrome, for instance, can process this differently than Internet Explorer.
If you are doing the referring yourself then you'll be best off passing a querystring parameter or using session state to identify the referring URL.
A: I'm not sure.. but I found out..
Session is not working if we call a new page using Javascripts.
I was told that all session values are reset on a new page which is called using javascripts.
As an alternative for my question, I used QueryString.
I really don't want the users to see the URL but I already hide the URL with javascript.
So, I have no problem using querystring, right?
Does anyone hava a better solution?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make this app screen scroll? I've a screen in an app I'm coding structured like this:
View
ScrollView
View
label 1
label 2
label 3
View
UIImageView
WebView
When loaded it adds some html string into the Web View and as the whole content (labels,image,html content) is longer than the screen height, I would like to allow the screen to scroll down/up when user is reading content. This is why I added the SrollView but nothing scroll!
I also did is scroll_view.contentSize = [self.view bounds].size; but it didn't work
Any idea on how to do this ?
Thx in advance for helping,
Stephane
A: By default UIScrollView is set a contentSize equal to its frame size. If you want it to be scrollable, you have to explicitly set the contentSize.
scrollView.contentSize = CGSizeMake(_width, _height);
Mostly you won't be knowing the actual contents size while you create the scroll view. You can assign the contentSize after adding the UIWebview(as web view is the last view in your scroll view). You can do it like this,
// Add other views to scrollView
// Create and configure webView
[scrollView addSubview:webView];
float _width = scrollView.contentSize.width; // No change in width
float _height = CGRectGetMaxY(webView); // Returns (webView.frame.origin.y + webView.frame.size.height)
scrollView.contentSize = CGSizeMake(_width, _height);
A: Below code u observe Here "Height" declare Dynamically as your Requirement
EXample :
if([Myarray length]>25)
{
myString = [myString stringByAppendingFormat:@"<tr><th align=\"left\">%@</tr>",str_owes ];
height += 50;
}
webview.frame=CGRectMake(25, 153, 420, height);
[webview loadHTMLString:myString baseURL:nil];
scrollview.contentSize=CGSizeMake(0, webview.frame.origin.y+webview.frame.size.height+50);
A: You need to set the UIScrollView's contentSize to be the size of the two views + the UIWebView combined.
You will also need to make sure that the UIWebView if of the right size and then turn scrolling off, as you may get scrolling issues otherwise (one scroll view inside another).
More info: http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: subscriberCellularProviderDidUpdateNotifier doesn't work I wrote a Hello World app, and put the following code in ...ViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
networkInfo.subscriberCellularProviderDidUpdateNotifier = ^(CTCarrier *carrier) {
[[[UIAlertView alloc] initWithTitle:@"SIM Alert"
message:@"This is an alert."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
};
}
Then I unplugged the SIM card but no alert was shown as expected. Could someone kindly tell me what's wrong? Thanks.
A: This is the ultimate solution to your question.
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
NSString *mobileNetworkCode = [carrier mobileNetworkCode];
[networkInfo release];
NSLog(@"Mobile Network Code : %@", mobileNetworkCode);
Depending on the mobileNetwork code you can determine whether SIM is present or not on the Device.
A: If you have a look at apples documentation of CTCarrier some properties, for example carrierName, have a short notice like this:
If you configure a device for a carrier and then remove the SIM card, this property retains the name of the carrier.
So I would guess the same happens for the rest of the API, since the SIM card isn't replaced by a new one the updateNotifier isn't called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to change an image from Cartesian to Polar coordinates in Matlab? I am trying to convert the pixels of an image from x-y coordinate to polar coordinate and I have problem with it, as I want to code the function by myself.
Here is the code I did so far:
function [ newImage ] = PolarCartRot
% read and show the image
image= imread('1.jpg');
%%imshow(image);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%change to polar coordinate
[x y z]= size(image);
r = sqrt(x*x+y*y);
theta = atan2(y,x);
for i =0:r
for j= 0:theta
newpixel = [i; j];
newImage(newpixel(1), newpixel(2),:) = image(i,j,:);
end
end
figure;
imshow (newImage);
A: It is not quite clear what you are trying to do, which is why I am making my own example...
So given an image, I am converting the pixel x/y coordinates from Cartesian to polar with CART2POL.
In the first figure, I am showing the locations of the points, and in the second, I plot both the original image and the one with polar coordinates.
Note that I am using the WARP function from the Image Processing Toolbox. Under the hood, it uses the SURF/SURFACE function to display a texture-mapped image.
% load image
load clown;
img = ind2rgb(X,map);
%img = imread(...); % or use any other image
% convert pixel coordinates from cartesian to polar
[h,w,~] = size(img);
[X,Y] = meshgrid(1:w,1:h);
[theta,rho] = cart2pol(X, Y);
Z = zeros(size(theta));
% show pixel locations (subsample to get less dense points)
XX = X(1:8:end,1:4:end);
YY = Y(1:8:end,1:4:end);
tt = theta(1:8:end,1:4:end);
rr = rho(1:8:end,1:4:end);
subplot(121), scatter(XX(:),YY(:),3,'filled'), axis ij image
subplot(122), scatter(tt(:),rr(:),3,'filled'), axis ij square tight
% show images
figure
subplot(121), imshow(img), axis on
subplot(122), warp(theta, rho, Z, img), view(2), axis square
EDIT
As I originally stated, the question is not clear. You have to describe the mapping you want in a well defined manner...
For one you need to think about where the origin is located before converting to polar coordinates. The previous example assume the origin to be the axes base at (0,0). Suppose you want to take the center of the image (w/2,h/2) as origin, then you would do this instead:
[X,Y] = meshgrid((1:w)-floor(w/2), (1:h)-floor(h/2));
with the rest of the code unchanged. To better illustrate the effect, consider a source image with concentric circles drawn in Cartesian coordinates, and notice how they map to straight lines in polar coordinates when using the center of the circles as origin:
EDIT
Here is another example of how to display an image in polar coordinates as requested in the comments. Note that we perform the mapping in the inverse direction pol2cart:
[h,w,~] = size(img);
s = min(h,w)/2;
[rho,theta] = meshgrid(linspace(0,s-1,s), linspace(0,2*pi));
[x,y] = pol2cart(theta, rho);
z = zeros(size(x));
subplot(121), imshow(img)
subplot(122), warp(x, y, z, img), view(2), axis square tight off
Again the effect is better show if you feed it an input image with straight lines, and see how they map in polar coordinates (vertical lines become circles, and horizontal lines become rays emanating from the origin):
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: check if URL contains some text (javascript) how can i use javascript/jQuery to check if a URL contains a specific link/text.
for example :
A user browse to my site and his URL is : "http//www.mywebsite.com/userprofile/abc&from=home"
I have set a variable and its value is "http//www.mywebsite.com/userprofile/abc" , i want to know how to detect if "http//www.mywebsite.com/userprofile/abc" exist in the URL("http//www.mywebsite.com/userprofile/abc&from=home") then execute a function.
Thanks!
A: var urlToCheck = "http//www.mywebsite.com/userprofile/abc";
if (window.location.href.indexOf(urlToCheck) > -1) {
executeAFunction();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting a href of a button in Ruby/Javascript This question is hard to explain so please bear with me. I have a table that contains rows which hold records from the Records table. i can add rows to this table using ajax and when i have entered the hours into a text field on the row and click away, the record gets submitted via ajax.
My problem is that i have a delete button next to each row. The rows delete as youd expect when i have refreshed the page or the rows where already in the Records table when the page was loaded. However if i have just added some hours and havent refreshed the page then i cannot delete the record.
After searching ive narrowed it down to this:
Already present record:
<a rel="nofollow" data-method="delete" data-confirm="Are you sure?" href="/records/2">
Just added:
<a class="delete" title="delete row" rel="nofollow" data-remote="true" data-method="delete" data-confirm="Are you sure?" href="Delete">
Because im using the ruby method "delete" from the Records controller it needs a href with the record id, thus "records/2". this wont change until ive refreshed the page which is not what i want.
Ive thought about setting the href of the button when the record gets submitted but i have know idea how to do that in either js or ruby, plus id have to submit and then grab the record id back again. Or if someone can come up with a better idea other than the one above and "refresh the page when it submits" im all ears.
A: Iam guessing you are using rails so what u need to do is the controller should return a js response. check this question. to render erb code in JavaScript you should use escape_javascript.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Development and production versions of wiki-article (MediaWiki CMS) Is it possible to realize few versions of wiki-article (using MediaWiki CMS) — development version and production version and simple way to switch versions?
A: The FlaggedRevs extension does something similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to copy (or swap) objects of a type that contains members that are references or const? The problem I am trying to address arises with making containers such as an std::vector of objects that contain reference and const data members:
struct Foo;
struct Bar {
Bar (Foo & foo, int num) : foo_reference(foo), number(num) {}
private:
Foo & foo_reference;
const int number;
// Mutable member data elided
};
struct Baz {
std::vector<Bar> bar_vector;
};
This won't work as-is because the default assignment operator for class Foo can't be built due to the reference member foo_reference and const member number.
One solution is to change that foo_reference to a pointer and get rid of the const keyword. This however loses the advantages of references over pointers, and that const member really should be const. They are private members, so the only thing that can do harm is my own code, but I have shot myself in the foot (or higher) with my own code.
I've seen solutions to this problem on the web in the form of swap methods that appear to be chock full of undefined behavior based on the wonders of reinterpret_cast and const_cast. It happens that those techniques do appear to work on my computer. Today. With one particular version of one particular compiler. Tomorrow, or with a different compiler? Who knows. I am not going to use a solution that relies on undefined behavior.
Related answers on stackoverflow:
*
*Does it make sense to implement the copy-assignment operator in a class with all const data members?
The first answer has the amusing line "If that one is immutable, your screwed."
*Swap method with const members
The first answer doesn't really apply here, and the second is a bit of a kludge.
So is there a way to write a swap method / copy constructor for such a class that does not invoke undefined behavior, or am I just screwed?
Edit
Just to make it clear, I already am quite aware of this solution:
struct Bar {
Bar (Foo & foo, int num) : foo_ptr(&foo), number(num) {}
private:
Foo * foo_ptr;
int number;
// Mutable member data elided
};
This explicitly eliminates the constness of number and the eliminates the implied constness of foo_reference. This is not the solution I am after. If this is the only non-UB solution, so be it. I am also quite aware of this solution:
void swap (Bar & first, Bar & second) {
char temp[sizeof(Bar)];
std::memcpy (temp, &first, sizeof(Bar));
std::memcpy (&first, &second, sizeof(Bar));
std::memcpy (&second, temp, sizeof(Bar));
}
and then writing the assignment operator using copy-and-swap. This gets around the reference and const problems, but is it UB? (At least it doesn't use reinterpret_cast and const_cast.) Some of the elided mutable data are objects that contain std::vectors, so I don't know if a shallow copy like this will work here.
A: You can't reseat the reference. Just store the member as a pointer, as it is done in all other libraries with assignable classes.
If you want to protect yourself from yourself, move the int and the pointer to the private section of a base class. Add protected functions to only expose the int member for reading and a reference to the pointer member (e.g to prevent yourself from treating the member as an array).
class BarBase
{
Foo* foo;
int number;
protected:
BarBase(Foo& f, int num): foo(&f), number(num) {}
int get_number() const { return number; }
Foo& get_foo() { return *foo; }
const Foo& get_foo() const { return *foo; }
};
struct Bar : private BarBase {
Bar (Foo & foo, int num) : BarBase(foo, num) {}
// Mutable member data elided
};
(BTW, it doesn't have to be a base class. Could also be a member, with public accessors.)
A: If you implement this with move operators there is a way:
Bar & Bar :: operator = (Bar && source) {
this -> ~ Bar ();
new (this) Bar (std :: move (source));
return *this;
}
You shouldn't really use this trick with copy constructors because they can often throw and then this isn't safe. Move constructors should never ever throw, so this should be OK.
std::vector and other containers now exploit move operations wherever possible, so resize and sort and so on will be OK.
This approach will let you keep const and reference members but you still can't copy the object. To do that, you would have to use non-const and pointer members.
And by the way, you should never use memcpy like that for non-POD types.
Edit
A response to the Undefined Behaviour complaint.
The problem case seems to be
struct X {
const int & member;
X & operator = (X &&) { ... as above ... }
...
};
X x;
const int & foo = x.member;
X = std :: move (some_other_X);
// foo is no longer valid
True it is undefined behaviour if you continue to use foo. To me this is the same as
X * x = new X ();
const int & foo = x.member;
delete x;
in which it is quite clear that using foo is invalid.
Perhaps a naive read of the X::operator=(X&&) would lead you to think that perhaps foo is still valid after a move, a bit like this
const int & (X::*ptr) = &X::member;
X x;
// x.*ptr is x.member
X = std :: move (some_other_X);
// x.*ptr is STILL x.member
The member pointer ptr survives the move of x but foo does not.
A:
that const member really should be const
Well, then you can't reassign the object, can you? Because that would change the value of something that you've just said really should not change: before the assigment foo.x is 1 and bar.x is 2, and you do foo = bar, then if foo.x "really should be const" then what's supposed to happen? You've told it to modify foo.x, which really should not be modified.
An element of a vector is just like foo, it's an object that the container sometimes modifies.
Pimpl might be the way to go here. Dynamically allocate an object (the "impl") containing all your data members, including const ones and references. Store a pointer to that object (the "p") in your object that goes in the vector. Then swap is trivial (swap the pointers), as is move assignment, and copy assignment can be implemented by constructing a new impl and deleting the old one.
Then, any operations on the Impl preserve the const-ness and un-reseatable-ness of your data members, but a small number of lifecycle-related operations can act directly on the P.
A:
This however loses the advantages of references over pointers
There is no advantage. Pointers and reference are different, but none is the better one. You use a reference to ensure that there is a valid instance and a pointer if passing a nullptr is valid. In your example you could pass a reference and store a pointer
struct Bar {
Bar (Foo & foo) : foo_reference(&foo) {}
private:
Foo * foo_reference;
};
A: You can compose your class of members that take care of those restrictions but are assignable themselves.
#include <functional>
template <class T>
class readonly_wrapper
{
T value;
public:
explicit readonly_wrapper(const T& t): value(t) {}
const T& get() const { return value; }
operator const T& () const { return value; }
};
struct Foo{};
struct Bar {
Bar (Foo & foo, int num) : foo_reference(foo), number(num) {}
private:
std::reference_wrapper<Foo> foo_reference; //C++11, Boost has one too
readonly_wrapper<int> number;
// Mutable member data elided
};
#include <vector>
int main()
{
std::vector<Bar> bar_vector;
Foo foo;
bar_vector.push_back(Bar(foo, 10));
};
A: I know this is a relatively old question to dig out, but I have needed something similar recently, and it made me wonder if this is possible to implement using contemporary C++, e.g. C++17.
I've seen this blog post by Jonathan Boccara
and fiddled with it a little, i.e. by adding implicit conversion operators and this is what I have gotten:
#include <optional>
#include <utility>
#include <iostream>
#include <functional>
template <typename T>
class assignable
{
public:
assignable& operator=(const assignable& rhs)
{
mHolder.emplace(*rhs.mHolder);
return *this;
}
assignable& operator=(assignable&&) = default;
assignable(const assignable&) = default;
assignable(assignable&&) = default;
assignable(const T& val)
: mHolder(val)
{}
assignable(T&& val)
: mHolder(std::move(val))
{}
template<typename... Args>
decltype(auto) operator()(Args&&... args)
{
return (*mHolder)(std::forward<Args>(args)...);
}
operator T&() {return *mHolder;}
operator const T&() const {return *mHolder;}
private:
std::optional<T> mHolder;
};
template <typename T>
class assignable<T&>
{
public:
explicit assignable(T& val)
: mHolder(val)
{}
operator T&() {return mHolder;}
operator const T&() const {return mHolder;}
template<typename... Args>
decltype(auto) operator()(Args&&... args)
{
return mHolder(std::forward<Args>(args)...);
}
private:
std::reference_wrapper<T> mHolder;
};
The part some may find controversial is the behaviour of the assignment operator for reference types, but the discussion about rebinding the reference vs the underlying object has been going on there for a while already I think, so I just did according to my taste.
Live demo:
https://godbolt.org/z/WjW7s34jn
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: can i use throw function on android
Possible Duplicate:
Enable Exception C++
when i use throw function ,like as follow:
throw "SobelGradient => cannot allocate memory";
this error come out: exception handling disabled, use -fexceptions to enable
And how to solve this error.
A: You should in your question mention that this is a NDK problem - otherwise it's quite misleading.
Anyway, if the clue in the comment doesn't help have a look here - seems that this was a similar issue:
Enable Exception C++
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: HTML layout design - need better approach I have to design a layout for my project. There are arrangements of divs, upper Div, lower Div, fixed height, scrolling etc. It is difficult to describe the problem in words, hence I have attached an image below. Please refer the screenshots.
What I want to achieve is to arrange panels with respect to the overall height of the browser window. Pink module is absolute positioned at the bottom of the parent Div. Upper Div is precious sibling of pink Div and it contains panels. when browser is resized scrollbars should not appear in UpperDiv. Instead panels should show scroll (show in second).
It can be done using HTML and CSS and not at all I am hesistant using javascript or jquery. I appreciate any of your approach in doing this. Many thanks.
Sorry I couldn't made HTML properly. Currently my html shows scroll in upperDiv (instead scroll should appear in panels). Here I have created a fiddle. Please check.
here
A: Made some changes to the CSS, hope this is kinda what you are looking for.
http://jsfiddle.net/vCVUL/embedded/result/
Regards.
A: You could use ExtJS for this. Have look at the demo page. There you find "Layout Managers" how will do the job for you.
A: I can't think of a much better way than, after page load, setting the dynamic section's height.
And to handle the resize, we can just bind the same function with JQuery.
http://jsfiddle.net/N3HWz/7/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does using Webview to open mobile page count as in-app purchase? I read the agreements on Android Developer site already but I dont clearly understand it.
From what I understand. If I want to allow user to purchase/subscribe my service through my Android application, I must offer Google Checkout as an option. I'm not in a supported country for Merchant account, so that option is not available to me. Am I allow to use third party library without offering Checkout option?
If I use Webview inside that application to open a page on my website, does that count as in-app purchase?
I searched for similar question but not really sure if the Webview violate the agreement or not?
A: This is a legal question. Please address it to Google directly as only they can give you an authoritative answer about android market terms of use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to connect to a database from outside of a web app? I am developing a java web app with Wicket (with jpa). Inside the Wicket Application i can access the database Persistence Unit with Persistence.createEntityManagerFactory() configured in persistence.xml.
Now i want to have a helper script to perform maintenance tasks. I created a java file with a static void main method but if i run this file, I get an Exception:
Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method
that is not native or abstract in class file javax/persistence/Persistence
In the test files, it works fine.
A: You don't have JPA on your classpath.
Depending on your JPA provider, this will be at least javax.persistence-*-.jar plus the provider-specific JARs, e.g. eclipselink-x.y.z.jar or a bunch of JARs for Hibernate. Check out what lives in your WEB-INF/lib folder if you're not sure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: use jmeter to load test a site: the url is different every time while running the script I try to test a site with Jmeter and I used its HTTP Proxy sever to make the script.
Actually, the process of this script is
1. login
2. click a link to another page and fill in some info and click SUBMIT
3. logout.
The problem is: everytime I run the script, everything is going well before hitting the SUBMIT button. 'cuz after hitting it, 8 random numbers or letters will be added to the url. So, everytime i run the script, the url is different from the first time that made the script.
Is there anyone has run into kind of question?
A: Couple things to consider:
*
*Are these "random numbers" in the source code, or just the URL as a
parameter? If so, see below.
*Are they a JSESSION ID? If so - use a cookie manager.
That should solve the issue.
If they are in the source code, you'll need to use a regular expression to extract the value. You'll want it as a child of Step2, making your structure:
Login
Form Page
--- Regex for Submit button
Submit
http://jmeter.apache.org/usermanual/component_reference.html#Regular_Expression_Extractor
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: EF with Azure - Mixing SQL Server and Windows Azure Storage I want to use two different data sources in my Azure project:
*
*a SQL Server that contains basic partial info regarding an item (allows indexable data and spatial search)
*a Windows Azure Storage that contains full remaining info regarding an item (retrieved by key)
In this way I can combine the powerful of SQL Server with the easy scalability of Windows Azure Storage.
Imagine this Domain POCO class:
class Person
{
string Id { get; set; }
string Name { get; set; }
byte[] Picture { get; set; }
string Biography { get; set; }
}
I would like to use Entity Framework with fluent mapping to let EF understand that the properties Picture and Biography must be loaded from Windows Azure Storage (table, blob) instead of SQL Server (possibly Lazy loaded).
There's a way with EF (or NHibernate) to do this or I have to implement my own ORM strategy?
Thanks
A: I don't think you can let EF know about Azure storage but you can map only necessary properties to a specific table. For example,
modelBuilder.Entity<Person>().Ignore(p => p.Picture);
So assuming that you have a repository class for your Person class, what you want can be easily achieved by filling the repository class with Azure storage API and EF.
A: You're trying to solve this problem too early (at the DAL) in my opinion. Look at the web, it fetches large data (e.g. pictures) in a separate call to the server. That has scaled very well. The picture data is not included in the document itself for a reason, it would just slow everything down and it would not be very fault tolerant. If you put them together in one entity you've got the fast entity retrieval that is slowed down by your picture server as they both have to come together before leaving towards your business layer and finally towards the presentation layer. And in the business layer this data is probably just wasting memory (that's why you want to lazy load it). So I think you're making the decision too early. What you describe as your domain object looks like a domain object of the presentation layer to me, similar to a ViewModel. I'm not too big into domain driven design, but while there is a general model of your application, I assume that each part of your application will require a slightly different implementation of that model.
Regarding lazy loading, if you have that enabled and you attempt to send your object over the wire, even if Picture was not loaded, it will get serialized since the data contract serializer (or any other) will call get on your property.
That's probably not the answer you wanted, but I felt that I had to say this. Of course I am open to comments and criticism.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Creating a thread Pool for boost threads There seems to be two approaches to create thread pool for boost threads as boost thread does not provide thread pool directly.
The first one is
asio::io_service io_service;
asio::io_service::work work(io_service);
boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
threads.create_thread(boost::bind(&asio::io_service::run, &io_service));
io_service.post(boost::bind(an_expensive_calculation, 42));
io_service.post(boost::bind(a_long_running_task, 123));
io_service.stop();
threads.join_all();
The second one is using unofficial thread pool from here http://threadpool.sourceforge.net/
void taskfunc();
// later on...
pool my_pool;
my_pool.schedule(&taskfunc);
My question is which is a better approach among these two here? Are there any specific advantages of either over each other? Thanks..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problems getting the Heroku example app for Python run locally with SSL I started out with having the same problem as in this question. As one of the answers suggests one can avoid that particular problem by making the app run without SSL. But as Facebook is set to enforce https for apps in just a few days (October 1 2011) that seems like a solution that won't last. I first tried to enable ssl in app.run (around line 149 in exampleapp.py. Like so:
app.run(host='0.0.0.0', port=port, ssl_context='adhoc')
At first try it failed at start complaining about the missing OpenSSL module. Found a couple of suggestions on how to fix that out there on the net, and choose to do:
(myapp)$ pip install pyopenssl
Now no complaints at start:
(myapp)$ foreman start
10:35:25 web.1 | started with pid 26934
10:35:26 web.1 | * Running on https://0.0.0.0:5000/
10:35:26 web.1 | * Restarting with reloader
But then when trying to access the app:
10:35:31 web.1 | ----------------------------------------
10:35:31 web.1 | Exception happened during processing of request from ('127.0.0.1', 61118)
10:35:31 web.1 | Traceback (most recent call last):
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 284, in _handle_request_noblock
10:35:31 web.1 | self.process_request(request, client_address)
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 310, in process_request
10:35:31 web.1 | self.finish_request(request, client_address)
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 323, in finish_request
10:35:31 web.1 | self.RequestHandlerClass(request, client_address, self)
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 639, in __init__
10:35:31 web.1 | self.handle()
10:35:31 web.1 | File "path_to_myapp/lib/python2.7/site-packages/werkzeug/serving.py", line 189, in handle
10:35:31 web.1 | return rv
10:35:31 web.1 | UnboundLocalError: local variable 'rv' referenced before assignment
10:35:31 web.1 | ----------------------------------------
10:35:31 web.1 | Unhandled exception in thread started by <function inner at 0x10139e050>
10:35:31 web.1 | Traceback (most recent call last):
10:35:31 web.1 | File "path_to_myapp/lib/python2.7/site-packages/werkzeug/serving.py", line 599, in inner
10:35:31 web.1 | passthrough_errors, ssl_context).serve_forever()
10:35:31 web.1 | File "path_to_myapp/lib/python2.7/site-packages/werkzeug/serving.py", line 355, in serve_forever
10:35:31 web.1 | HTTPServer.serve_forever(self)
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 227, in serve_forever
10:35:31 web.1 | self._handle_request_noblock()
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 287, in _handle_request_noblock
10:35:31 web.1 | self.shutdown_request(request)
10:35:31 web.1 | File "/usr/local/Cellar/python/2.7.1/lib/python2.7/SocketServer.py", line 459, in shutdown_request
10:35:31 web.1 | request.shutdown(socket.SHUT_WR)
10:35:31 web.1 | TypeError: shutdown() takes exactly 0 arguments (1 given)
What to do about this? Is it the wrong Python version or just me missunderstanding some other fundamental thing?
A: Difficult to ascertain why "rv" fails without inspecting the local environment, scripts, installed modules and the werkzeug code, which claims SSL is supported from v0.6 onwards.
The easiest solution is to install the grandpa of web servers apache on your local machine, add in mod_ssl module and generate those SSL certs. Lastly, add mod_wsgi as described in Flask's help page to get your app up and running.
Note: installation may be daunting for first timers, but once you get going, apache is a workhorse and been extremely reliable to me over the past 15 yrs.
A: It is a bug in Werkzeug, that got fixed.
Change the Werkzeug version in the requirements.txt file to at least 0.8.2 and run pip install -r requirements.txt to upgrade.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: HTML Tags in GWT internationalization I'm using the internationalization of GWT to manage the different languages of my application. I have a text where some words are in bold. Therefore I did the same thing as described here.
@DefaultMessage("Welcome back, {startBold,<b>}{0}{endBold,</b>}")
String testMessage(String name);
However, when I run the application, I get "Welcome back, < b>Peter< /b>" (the HTML is written out and not interpreted. I intentionally put a space between < b so that this text editor does not interpret the html tag).
Does anyone know how to solve this issue? Many thanks in advance!
P.S.
Code fragment which gets the language string:
Label label = new Label();
label.addStyleName("intro-Text");
label.setText(new HTML(trans.testMessage(name)).getHTML());
A: Instead of using a Label use the HTML widget.
HTML text = new HTML();
text.addStyleName("intro-Text");
text.setHTML(trans.testMessage(name));
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex for number surrounded by slashes Like the title says, I have a (faulty) Regex in JavaScript, that should check for a "2" character (in this case) surrounded by slashes. So if the URL was http://localhost/page/2/ the Regex would pass.
In my case I have something like http://localhost/?page=2 and the Regex still passes.
I'm not sure why. Could anyone tell me what's wrong with it?
/^(.*?)\b2\b(.*?$)/
(I'm going to tell you, I didn't write this code and I have no idea how it works, cause I'm really bad with Regex)
A: Seems too simple but shouldn't this work?:
/\/2\//
http://jsfiddle.net/QHac8/1/
As it's javascript you have to escape the forward slashes as they are the delimiters for a regex string.
or if you want to match any number:
/\/\d+\//
A: You don't check for a digit surrounded by slashes. The slashes you see are only your regex delimiters. You check for a 2 with a word boundary \b on each side. This is true for /2/ but also for =2
If you want to allow only a 2 surrounded by slashes try this
/^(.*?)\/2\/(.*?)$/
^ means match from the start of the string
$ match till the end of the string
(.*?) those parts are matching everything before and after your 2 and those parts are stored in capturing groups.
If you don't need those parts, then Richard D is right and the regex /\/2\// is fine for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Binary search tree doesn't work I'm having a pretty confusing problem in building a binary tree. Apparently this should be an easy task but somehow I may mess up with the pointers in it.
Here's the simplified code (of course it's not the real code) :
#include <string.h>
#include <iostream>
using namespace std;
#define DIM1 2
typedef enum {LEFT,RIGHT} direction;
typedef char tName[MAX_NAME_LEN + 1];
struct Rectangle {
tName _name;
struct Rectangle *_binSon[DIM1];
};
struct Rectangle *recTree;
void insertRectToTree(char str[]){
struct Rectangle rect;
struct Rectangle *point;
struct Rectangle *parent;
strcpy(rect._name,str);
rect._binSon[RIGHT] = NULL;
rect._binSon[LEFT] = NULL;
point = ▭
if (recTree == NULL){
recTree = point;
} else {
struct Rectangle *current;
current = recTree;
while (current){
parent = current;
if (strcmp(point -> _name, current -> _name) > 0){
current = current -> _binSon[RIGHT];
} else {
current = current -> _binSon[LEFT];
}
}
if (strcmp(point -> _name, parent -> _name) < 0){
parent -> _binSon[LEFT] = point;
} else {
parent -> _binSon[RIGHT] = point;
}
}
}
int main(){
recTree = NULL;
char str[] = "LIKE";
insertRectToTree(str);
char str2[] = "GUIDE";
insertRectToTree(str2);
printf(recTree -> _name);
return 0;
}
As you can see, this binary tree tries to organize a record based on its name, so the smallest alphabetical order will go to the left side and so on.
The problem is, after the first insertion "LIKE", I want "GUIDE" inserted to the tree as well, with "LIKE" still as the root. However, the printf() shows that "GUIDE" takes over as its root. (In other word, "GUIDE" is the output). Any good explanation for this? Ask me if I need to add some more thing to this question. Thanks for all of your help.
A: Within the following lines
struct Rectangle rect;
...
point = ▭
...
recTree = point;
you assign a reference to a local variable to a global pointer. After leaving the function it may no longer contain valid data.
A: Howard is correct. But to correct the problem use new.
i.e. instead of
point = ▭
Put
point = new struct Rectangle;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is there any build tool available for linux that takes a web project & compresses text files, remove comments? I am looking for a build tool that can take a dev version of a typical PHP project and can compress files such as HTML files, view files(PHP embedded in html or vice versa), JS & cSS files before they are deployed. I can do this for individual file using some online tools but that is time consuming. I want to automate this process. TIA!
A: For Java script and css you can use libraries like
Closure @ http://code.google.com/closure/compiler/ or
YUI Compressor @ http://developer.yahoo.com/yui/compressor/
These tools can be run through ant tasks and would help to clean up and make the files concise.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: character array handling in c (copy pointer to character array) I have a pointer with type const char* FunctionName , How can I put that into a payload of type char payload[100] without any warning or errors? Also the payload[0] is filled with character value already, so the space starting from payload[1]
update:
I tried like this `strcpy((&payload[1]),FunctionName); is working now.
But Ihave one more question, how can accomodate the pointer(FunctionName) into the payload[1] ratherthan copying the entire string? through any assignment statement?
/R
A: strncpy(&payload[1], FunctionName, 98);
payload[99] = '\0';
should be safe in the case that FunctionName has more than 98 characters before the NULL terminator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problems with creating a file in android i would like to do a simple operation. Create a file in android, but i don't know why. android didn't create this file. Android stop between debug 2 and debug 3.The folder is not created. I don't understand why.
try {
File inventoryDir = new File(Environment.getExternalStorageDirectory()+"/ludovic");
String userfile = "/session.txt";
if (!inventoryDir.exists()){
inventoryDir.mkdirs();
Log.i("debug","debug 1");
}
File userFile = new File(inventoryDir, userfile);
Log.i("debug","file path "+userFile.getAbsolutePath());
Log.i("debug","debug 2");
FileWriter fw = new FileWriter(userFile);
Log.i("debug","debug 3");
BufferedWriter bw = new BufferedWriter(fw);
Log.i("debug","debug 4");
bw.write("teste d'ecriture");
Log.i("debug","debug 5");
bw.close();
Log.i("debug","debug 6");
Log.i("debug","enregistre");
} catch (IOException e) {
Log.i("debug","non enregistre");
e.printStackTrace();
}
i have test this code
try { // catches IOException below
final String TESTSTRING = new String("Hello Android");
// ##### Write a file to the disk #####
/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(TESTSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
Whith this code, i didn't have problem's to create file but i don't find this file if i search with windows explorer.
A: replace
inventoryDir.mkdirs();
to
inventoryDir.mkdir();
Latest:
File inventoryDir = new File(Environment.getExternalStorageDirectory()+"/ludovic");
if (!(inventoryDir.exists())){
inventoryDir.mkdir();
}
and also WRITE_EXTERNAL_STORAGE permission in Manifest file
EDITED:
File inventoryDir = new File(Environment.getExternalStorageDirectory()+"/ludovic/");
String userfile = "session.txt";
if (!(inventoryDir.exists())){
inventoryDir.mkdir();
Log.i("debug","debug 1");
}
File userFile = new File(inventoryDir, userfile);
try {
PrintWriter out = new PrintWriter(mFile);
} catch (IOException e){
e.printStackTrace();
}
out.print("some text");
out.close();
}
A: Can you try this:
File inventoryDir = new File(Environment.getExternalStorageDirectory()+"/ludovic/");
String userfile = "session.txt";
A: <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="byd.eagle"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".EagleBackup"
android:label="@string/app_name">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
Look at this code sample. The location where the uses-permission declared is the key. Just try both in and out the activity!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git diff two repositories, get results from .git dir? I have two versions of a git repo on my computer, I wanted to know which is the differences between them, so I can know whether I should pull or not from the other repo.
I did a "git diff amslib ../workspace/amslib" and instead of showing me the differences between just the committed files in both repositories, it started to give me the differences in the .git directory too.
I suppose I'm not using the commands right, can anyone tell me how I should do it? I just want to know which version of the code has what changes, so I can either merge them, pull them, or manually copy them because I want some changes, but not others.
thanks
A: You should be able to add one respository as a "remote" to the other, fetch the extra commits and then diff them against the current repo.
A: You could do an ordinary recursive diff and ignore any results from the .git directories. I suspect @Noufal's solution is cleaner, but this is an alternative.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting id's on elements in partial views I have a view that - among other things - contains a list of elements. I want to reuse this list, so I move it out to a partial view. My view contains a form, and on post I want to include some values in the list. Therefore I use @Html.EditorFor(m => m.Something) to generate input-boxes which will get a unique Id. The view is strongly typed to use "MyModel" as Model. On post the MVC framework handles everything very well - putting the values back together to a MyModel object containing the input and some fields I used Html.HiddenFor on. All good.
Now I move this to a partial view. The partial view only works on the list and therefore is strongly typed to model List. I include this view from my main view, and pass in the list I want it to render. The table code inside the partial view is exactly what it was before except that it is changed to get values from the list instead of MyModel. All data is displayed perfectly, but there is a problem. The input-boxes doesn't get an Id any more. And because they don't get an Id their value isn't included in the posted form - and hence they don't appear in the model I get as input to my post method. I tried including the partial view using both @Html.Partial("_MyPartial", Model.Items) and @{Html.RenderPartial("_MyPartial", Model.Items);}
So the question is; how can I make this work with a partial view? How can I get that Id back?
Here is some sample code in case anything is unclear:
MyModel.cs
----------
public class MyClass
{
public string Val1 { get; set; }
public string Val2 { get; set; }
}
public class MyModel
{
public List<MyClass> Items {get; set; }
}
MyView.cshtml:
--------------
@model MyModel
using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post))
{
@Html.Partial("_MyPartial", Model.Items)
}
_MyPartial.cshtml:
------------------
@model List<MyClass>
<table>
<tbody>
for (var i = 0; i< Model.Count; i++)
{
<tr>
<td>
@Model[i].Val1
@Html.HiddenFor(model => model[i].Val1)
</td>
<td>@Html.EditorFor(model => model[i].Val2)</td>
</tr>
}
</tbody>
</table>
A: You will have to use EditorFor for your Model.Items as well.
So change the _MyPartial to something more relevant, like MyEditorForMyClass.cshtml.
Make a 'EditorTemplates' folder in the Shared or the folder you're working in and place the 'MyEditorForMyClass.cshtml' file in there.
Then do the following:
MyView.cshtml:
--------------
@model MyModel
using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post)
{
@Html.EditorFor(model => Model.items,"MyEditorForMyClass"}
}
The EditorFor templates/helper methods allows you to render both standard data-types and your own complex objects that contain multiple properties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MySQL: Why does an Order By ID runs much slower than Order By other Columns? I am using MySQL version 5.5.14 to run the following query, QUERY 1, from a table of 5 Million rows:
SELECT P.ID, P.Type, P.Name, P.cty
, X(P.latlng) as 'lat', Y(P.latlng) as 'lng'
, P.cur, P.ak, P.tn, P.St, P.Tm, P.flA, P.ldA, P.flN
, P.lv, P.bd, P.bt, P.nb
, P.ak * E.usD as 'usP'
FROM PIG P
INNER JOIN EEL E
ON E.cur = P.cur
WHERE act='1'
AND flA >= '1615'
AND ldA >= '0'
AND yr >= (YEAR(NOW()) - 100)
AND lv >= '0'
AND bd >= '3'
AND bt >= '2'
AND nb <= '5'
AND cDate >= NOW()
AND MBRContains(LineString( Point(39.9097, -2.1973)
, Point(65.5130, 41.7480)
), latlng)
AND Type = 'g'
AND tn = 'l'
AND St + Tm - YEAR(NOW()) >= '30'
HAVING usP BETWEEN 300/2 AND 300
ORDER BY ak
LIMIT 100;
Using an Index (Type, tn, act, flA), I am able to obtain results within 800ms. In QUERY 2, I changed the ORDER BY clause to lv, I am also able to obtain results within similar timings. In QUERY 3, I changed the ORDER BY clause to ID and the query time slowed dramatically to a full 20s on an average of 10 trials.
Running the EXPLAIN SELECT statement produces exactly the same query execution plan:
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: P
type: range
possible_keys: Index
key: Index
key_len: 6
ref: NULL
rows: 132478
Extra: Using where; Using filesort
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: E
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 3
ref: BS.P.cur
rows: 1
Extra:
My question is: why does ordering by ID in QUERY 3 runs so slow compared to the rest?
The partial table definition is as such:
CREATE TABLE `PIG` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`lv` smallint(3) unsigned NOT NULL DEFAULT '0',
`ak` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `id_ca` (`cty`,`ak`),
KEY `Index` (`Type`, `tn`, `act`, `flA`),
) ENGINE=MyISAM AUTO_INCREMENT=5000001 DEFAULT CHARSET=latin1
CREATE TABLE `EEL` (
`cur` char(3) NOT NULL,
`usD` decimal(11,10) NOT NULL,
PRIMARY KEY (`cur`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
UPDATE: After extensive testing of various ORDER BYs options, I have confirmed that the ID column which happens to be the Primary Key is the only one causing the slow query time.
A: From MySQL documentation at http://dev.mysql.com/doc/refman/5.6/en/order-by-optimization.html
In some cases, MySQL cannot use indexes to resolve the ORDER BY, although it still uses indexes to find the rows that match the WHERE clause. These cases include the following:
. . .
The key used to fetch the rows is not the same as the one used in the ORDER BY:
`SELECT * FROM t1 WHERE key2=constant ORDER BY key1;`
This probably won't help, but what happens if you add AND ID > 0 to the WHERE clause? Would this cause MySQL to use the primary key for sorting? Worth a try I suppose.
(It seems odd that ordering with ak is efficient, since ak does not even have an index, but that may be due to fewer values for ak?)
A: If the condition in the WHERE clause differs from the one in the ORDER BY or it is not part of a composite index, then the sorting does not take place in the storage engine but rather at the MySQL server level which is much slower. Long story short you must rearrange your indexes in order to satisfy both the row filtering and the sorting as well.
A: you can use force index(PRIMARY)
try it, and you will see in explain query that mysql now will use the primary key index when 'order by'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: powershell script to remove multiple folders I would like a script to remove multiple folders from beneath each users douments and settings.
Example folders:
Desktop
Favorites
mmerge
my documents
nethood
printhood
recent
sentto
start menu
windows
application data
local settings
I would like it to delete everything except the following.
my documents
mmerge
desktop
favorites
Is there a way to scropt this or remove all with an exception list perhaps?
This is the same for all users.
path e:\redirected\%username%\
A: You probably need to employ the Remove-Item cmdlet but before doing so, you seriously need to review your requirements. For example, removing all folders under local setting or application data is likely to break stuff (i.e. installed applications). You'll also need to test for file locks and define a strategy for dealing with files and folders that can't be deleted whilst the user is logged in.
A: Try something like:
ls '\Documents and Settings' | ? { ! ($_.psiscontainer -and $_ -match "my documents|mmerge|desktop|favorites") } | rm -rec -force -whatif
Obviously you need to be very careful with the rm -rec and remove the -whatif. ;) Add -force to the ls (Get-ChildItem) if you want to make hidden folders visible to your destruction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iAd : latency and ad inventory issues I added iAd in my most successful application a few weeks / months ago and I noticed some weird issues.
Latency
I noticed a speed issue : adding a banner to a view, I sometimes gets a response after 10 seconds, sometimes it's pretty normal (like 1 second); I guess it ain't good for revenues since some of my views are displayed only a few seconds, depending on the user. I get this latency issue both on wifi and 3G connections. Did any of you guys noticed the same issue?
PS : most of my users are in France (I don't know if the iAd architecture is scaled for both USA and Europe)
Ad inventory
The AdBannerViewDelegate calls bannerView:didFailToReceiveAdWithError: with the "Ad inventory unavailable" pretty often. I don't know the exact meaning but I wonder if a request receiving this error is registered on Apple side : since i use AdMob to display an ad when iAd is unable to get one, I have this weird issue of having more requests registered on AdMob than on iAd!
Thanks for any tips :)
A: It's normal that there is some latency and it's unusual each time - Internet speeds differs a lot in each country, so, don't worry.
And about this error "Ad inventory unavailable" is okay too, in my apps there are lots of them, it's not a bug - just iAd isn't very gainful. I think and use it like a bonus for free version of paid application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Microsoft Hex dates I have the following from a Microsoft SQL Server database for date/time value:
0x00009CEF00A25634
I found this post:
Help me translate long value, expressed in hex, back in to a date/time
Which seemed to be on the right track but by using the code I didn't get the right dates, are my hex dates in a different format? How would I convert them to a normal date, I am using PHP/PostgreSQL.
A: select CAST (0x00009CEF00A25634 as datetime) gives 2009-12-30 09:51:03.000
This is two integers. One for the date part 0x00009CEF (decimal 40175) and one for the time part 00A25634 (decimal 10638900). The date part is a signed integer giving number of days since 1 Jan 1900. The time part is an integer representing number of ticks.
There are 300 ticks in a second.
It can be seen that the following also returns the same result
SELECT DATEADD(MILLISECOND,10638900*10/3.0, DATEADD(DAY,40175, '19000101'))
You will need to figure out how to apply this to postgres.
Edit: an answer here apparently does this. I haven't tested it myself.
A: This works for me while migrating from SQL to MySQL :
SELECT (CAST('1900-01-01 00:00:00' + INTERVAL CAST(CONV(substr(HEX( 0x0000A249004576D0 ),1,8), 16, 10) AS SIGNED) DAY + INTERVAL CAST(CONV(substr(HEX( 0x0000A249004576D0 ),9,8), 16, 10) AS SIGNED)* 10000/3 MICROSECOND AS DATETIME)) AS newdate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to use I'm trying to use:
<script type="text/javascript">
function myfunc() {
var param = 4;
alert("OK");
}
</script>
I call the function like this:
<a4j:jsFunction name="myfunc">
<a4j:actionparam name="param" assignTo="#{MyBean.myfield}"/>
</a4j:jsFunction>
But it does not work. In what may be the reason?
A: <a4j:jsFunction
is not used to call an function, it is used to define an function.
So, if MyBean.myfield is an int-field you can set the value 2 using:
<script>myfunc(2);</sript>
A: You misunderstood the purpose of <a4j:jsFunction>. It autogenerates a JavaScript function which you can then call from any JavaScript code in your view.
Your example,
<a4j:jsFunction name="myfunc">
<a4j:actionparam name="param" assignTo="#{MyBean.myfield}"/>
</a4j:jsFunction>
will autogenerate the following function
<script>
function myfunc(param) {
// Here some specific JSF Ajax script which assigns "param"
// to a managed bean property #{MyBean.myfield}
}
</script>
You do not need to define it yourself. You only need to invoke it yourself from some JavaScript code elsewhere. For example,
<span onclick="myfunc(4)">click here to set 4 in MyBean.myfield</span>
or
<script>
function someOtherFunction() {
var param = 4;
myfunc(param);
}
</script>
which is in turn to be used like
<span onclick="someOtherFunction()">click here to call someOtherFunction() which will in turn set 4 in MyBean.myfield</span>
See also:
*
*<a4j:jsFunction> component reference
*<a4j:jsFunction> showcase example
A: There's a bunch of different ways to call that function.
Two you will find particularly useful are:
This:
<body onload="myfunc();">
Example: http://ultimatemmo.webege.com/Test.html
and this:
<a href="#" onclick="myfunc();">Click here to execute function</a>
Example: http://ultimatemmo.webege.com/Test2.html
Edit: added examples.
A: According you snippet of code, you have never called your function. Add myfunc(); within your script tag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: UITableView - Load large UIImages from NSBundle without blocking main thread In UITableViewController, the UI freezes when this method is called:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
where an image is being loaded into the UITableViewCell.
cell.imageView.image = [UIImage imageWithContentsOfFile:@"filePath"];
The files are locally stored in the documents folder - this is not a remote call.
I understand that image-loading while the cell is created cusses the main thread to freeze, if this was a remote call i would have uses a-synchronic loading but how would you
do it for local files?
*images are around 500k.
Need help. Thanks.
A: For example, make separate thread where you will load images and save reference to them in some array. When all images will be prepared (or some part of them), you can reload cells that should contains that messages.
In table view controller you should check if image is already loaded for that cell and if it is just take reference and set cell.imageView.image with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it considered bad practice to use InternalsVisibleTo for Unit Test Code? Sample code in framework's AssemblyInfo.cs:
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo
("Test.Company.Department.Core")]
Is this a bad practice?
A: No, it is not considered bad practice. There is no other way, if the classes you want to test are internal to your assembly for good reasons. Just not testing them would be a lot worse.
A: InternalsVisibleTo could be useful if you need to test sub parts of your API which you don't want to expose.
However, testing through the public API is preferable since it makes refactoring internal APIs easier. Use InternalsVisibleTo with care and only when appropriate, e.g. the size of the API is significant.
A: Personally I think it's fine. I've never gone along with the dogma of "only test public methods". I think it's good to also have black box testing, but white box testing can let you test more scenarios with simpler tests, particularly if your API is reasonably "chunky" and the public methods actually do quite a lot of work.
Likewise, in a well-encapsulated project you may well have several internal types with only internal methods. Now presumably those will have a public impact so you could do all the testing just through the public types - but then you may well need to go through a lot of hoops to actually test something that's really simple to test using InternalsVisibleTo.
A: I think it's perfectly reasonable to do that.
I find it very useful for dependency injection. If I have a class with a constructor that takes in a few dependencies to allow it to be unit tested I often mark it internal and expose it in my unit test project. Then I'd have a public (parameterless, or at least with far fewer parameters) constructor. This keeps the public interface clean and still allows for testable code.
A: No, when used correctly, because in some scenarios it's necessary. For instance, you have unit test A that needs to test a public member of assembly B that uses some internal type also defined in assembly B. The unit test needs this type, thus you must use InternalsVisibleTo.
It is also useful for protecting code. A for instance is an Activation assembly. You may only want one module in your solution to access your activation assembly, and prevent anyone from adding a reference to it and calling methods. You can make the types and members internal, expose them only to a signed assembly with a public key token, and its hidden from the rest of the world.
A: I would say it is bad practice because if you have used the SOLID principles then you really shouldn't have to use "InternalsVisibleTo". However i know in the "real world" you get all sorts of code.....so the pragmatic approach is best.
Also "InternalsVisibleTo" is not ideal in scenarios where you use obfuscation. Obfuscators tend to obfuscate the "internal" stuff. Therefore any external dll that attempts to reference the internals of an obfuscated dll will fail. You can obviously configure the obfuscator to ignore externally referenced items, but that would reduce the effectiveness of any obfuscator.
In my opinion, avoid "InternalsVisibleTo" if you can. But if you have to use it, then there's something wrong with how the code is structured (which you tend to get a lot of).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: NSString to char[] in Objective-c I have to convert a NSString to a null ended char[].
The way Im doing it is like this:
NSString *regC = @"1234"
char REG[[regC length] +1];
BOOL result = [regC getCString:REG maxLength:32 encoding:NSUTF8StringEncoding];
and I dont know if is it the correct way.
REG has to be a 5 chars array, with a null in the last one/
Thanks.
A: char *REG = [@"test" UTF8String];
You can't allocate the length of a char[] at runtime unless you use malloc/free. but with the above way you won't need to manage memory.
A: This is the correct way to convert as long as you use ASCII characters in your NSString. They are representer as single byte characters in UTF-8 encoding.
If you use some non-ASCII characters you should make your REG bigger.
Upd: one more: you should put your actual buffer size into "maxLength:" parameter in order to avoid buffer overrun. Not 32 but [regC length] +1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Traverse XML document using asp I'm trying to find if a certain element is present in a XML file and if it is, remove it. However I keep getting this error:
Description: Type mismatch: 'NodeList'
My code looks like this:
<%@ Language=VbScript%>
<%
Dim address
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
xmlDoc.load (Server.MapPath("XML/sensor.xml"))
Set Root = XMLDoc.documentElement
Set NodeList = Root.getElementsByTagName("sensor")
For Each i In NodeList
if ((NodeList(i).getElementsByTagName("Address")(0).childNodes(0).nodeValue)=request.form("remove_address")) then
NodeList.parentNode.removeChild NodeList
End if
Next
NodeList.parentNode.removeChild NodeList
xmlDoc.Save "\www./XML/sensores.xml"
Response.Redirect("remove_sensor_modbus.html")
%>
And the XML file looks like this:
<?xml version="1.0"?>
<sensors>
<sensor>
<Address>40000</Address>
</sensor>
<sensor>
<Address>46999</Address>
</sensor>
</sensors>
The form is a dropdown menu populated with this same XML file.
Does anyone knows what could be causing this error?
A: It looks like you have several errors in your loop. Try this:
Dim removeAddress
Set removeAddress = Request.Form("remove_address")
For Each sensorNode In NodeList
Dim addressNode
Set addressNode = sensorNode.GetElementsByTagName("Address")(0)
If (addressNode.Text = removeAddress) Then
sensorNode.RemoveChild(addressNode)
End if
Next
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Given a fixed cel width, can I change the fontsize so that the text will fit inside the cell? I have code that will automatically adjust the height of a cell, so that text will fit inside that cell.
However now I want to change the fontsize of the text inside the cell, so that the font will shrink and grow to make the text fit inside the cell, so I don't have to make the cell width a fixed size.
How do I do this in VBA?
I need to know the width of text, given a font size
Option 1.
TextWidth = WidthOfAText(Range("A1").Value)
FontAdjustmentFactor = Range("A1").EntireColumn.ColumnWidth / TextWidth
FontSize = Range("A1").Font.Size * FontAdjustmentFactor
Range("A1").Font.Size = Max(4, Min(10, FontSize))
or I need to know whether the text will fix and do some sort of trial and error routine.
Option 2.
Range("A1").Font.Size = 10
While (Text_does_not_fit AND Range("A1").Font.Size >= 5)
Range("A1").Font.Size = Range("A1").Font.Size - 1
Wend
How do I do this? (Preferably using code like in option 1)
A: Non programatically just right click on the cell -> Format Cells -> Alignment -> Shrink to Fit
Code wise is:
Sheet1.Range("A1").ShrinkToFit = True
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: caching kills links (jquery mobile on iPad) I am working on a webapplication that uses caching to make it available offline. Everything works fine when running it chrome (offline and online). But when I run it on iPad the links don't work anymore and I get failed to load page everywhere. Removing the caching makes the links work again so it obviously has something to do with the caching. Navigating directly to the seperate pages of the webapp also works fine in Safari, its the link that causes the error. By default all links are loaded with AJAX in jQuery Mobile. Changing this by adding rel="external" also fixes the problem, but obviously I don't want to do that.
To enable caching I added this code: and created a manifest file with ALL the files (scripts, css, images, html). Does anyone know what the problem could be?
A: I've experienced this as well while working with caching using manifests. What I discovered was that there Chrome has no limits. iPad and iPhone do. This appears to be pretty small, around 5mb. Try removing images as much as possible and using YUI Compressor on your scripts.
Ajax requests can be cached actually, the system doesn't care if the request is by AJAX or normal full request. All you have to do is put the URLs you wanted to retrieve by ajax into the manifest like the rest of the assets.
Hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Blackberry appworld support device I've uploaded an app in blackberry app world. Its support from 4.5
Now i have changed some changes in my app. I've added browser field. Its support from 5.0.
My question is,
Is there anyway to upload that,
old app for 4.5 to 5
new app for 5 to 7
A: You might want to confirm this with AppWorld support, but my understanding is that folks with older devices will still get the old version and folks with newer devices will get the new version. You don't have to re-upload the old version, it "just works" that way. I had a different problem -- I didn't want my old version to still be available for old OS versions once I updated/upgraded to a newer OS and had to actually make a special request to have the older versions deactivated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i check whether the current time in between tonight 9pm and 9am(tomorrow) in Ruby on Rails I need to check whether my current times is between the specified time interval (tonight 9pm and 9am tomorrow). How can this be done in Ruby on Rails.
Thanks in advance
A: Create a Range object having the two Time instances that define the range you want, then use the #cover? method (if you are on ruby 1.9.x):
now = Time.now
start = Time.gm(2011,1,1)
stop = Time.gm(2011,12,31)
p Range.new(start,stop).cover? now # => true
Note that here I used the explicit method constructor just to make clear that we are using a Range instance. You could safely use the Kernel constructor (start..stop) instead.
If you are still on Ruby 1.8, use the method Range#include? instead of Range#cover?:
p (start..stop).include? now
A: require 'date'
today = Date.today
tomorrow = today + 1
nine_pm = Time.local(today.year, today.month, today.day, 21, 0, 0)
nine_am = Time.local(tomorrow.year, tomorrow.month, tomorrow.day, 9, 0, 0)
(nine_pm..nine_am).include? Time.now #=> false
A: Obviously this is an old question, already marked with a correct answer, however, I wanted to post an answer that might help people finding the same question via search.
The problem with the answer marked correct is that your current time may be past midnight, and at that point in time, the proposed solution will fail.
Here's an alternative which takes this situation into account.
now = Time.now
if (0..8).cover? now.hour
# Note: you could test for 9:00:00.000
# but we're testing for BEFORE 9am.
# ie. 8:59:59.999
a = now - 1.day
else
a = now
end
start = Time.new a.year, a.month, a.day, 21, 0, 0
b = a + 1.day
stop = Time.new b.year, b.month, b.day, 9, 0, 0
puts (start..stop).cover? now
Again, use include? instead of cover? for ruby 1.8.x
Of course you should upgrade to Ruby 2.0
A: This might read better in several situations and the logic is simpler if you have 18.75 for "18:45"
def afterhours?(time = Time.now)
midnight = time.beginning_of_day
starts = midnight + start_hours.hours + start_minutes.minutes
ends = midnight + end_hours.hours + end_minutes.minutes
ends += 24.hours if ends < starts
(starts...ends).cover?(time)
end
I'm using 3 dots because I don't consider 9:00:00.000am after hours.
Then it's a different topic, but it's worth highlighting that cover? comes from Comparable (like time < now), while include? comes from Enumerable (like array inclusion), so I prefer to use cover? when possible.
A: Here is how I check if an event is tomorrow in Rails 3.x
(event > Time.now.tomorrow.beginning_of_day) && (event < Time.now.tomorrow.end_of_day)
A: if time is between one day:
(start_hour..end_hour).include? Time.zone.now.hour
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: creating a jQuery plugin, help selecting a parent I am creating a plugin for jQuery to create pretty select boxes (I know there are some out there, but this is learning experience for me).
If all goes well I realease the plugin to the public, so I am trying to build it as flexible as possible, and for this reason I am struggling to select the parent form element that houses the select that I am trying to target. Regardless of how a user sets up there HTML, I want to be able to select the parent form element.
Below is my HTML,
<div class="grid_6 alpha quick_search">
<h3>Quick Search Talent</h3>
<form action="http://urbantalent.tv.local/search/quick" method="post" accept-charset="utf-8" class="quick_form"><div style="display:none">
<input type="hidden" name="csrf_urbantalent" value="a8db11249b37322da84d3a211a933b19" />
</div>
<div class="formRow drop_down">
<select name="type">
<option value="0" selected="selected">I'm looking for...</option>
<option value="1">actors</option>
<option value="2">presenters</option>
<option value="3">voice overs</option>
</select>
</div>
<button type="submit" name="submit_search"><img src="http://urbantalent.tv.local/media/images/site/quick_submit.png" /></button>
</form>
</div>
As you can see from this HTML the selects parent is actually, .formRow how can I select the just the parent form, I have tried doing this,
$(this).parent('form') however this doesn't work as we know that form is not actually the parent.
A: You need this:
$(this).closest("form")
jQuery reference: http://api.jquery.com/closest/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server - Find duplicates in table We got big table with nearly 100+ millions rows. Can someone help how to find duplicate data within the table and may be move it to ARCHIVE
Table Name: CustomerData
NumberofFields: 10
Latest one should stay (which is identified by END_DATE mentioned as NULL in that record)
Regards
A: You just need to move the rows where END_DATE isn't NULL?
In a single transaction:
INSERT INTO archive (column1, column2, ... column10)
SELECT column1, column2, ..., column10
FROM CustomerData
WHERE END_DATE IS NOT NULL
DELETE CustomerData
WHERE END_DATE IS NOT NULL
A: Assuming CustomerData Table structure as:
CustomerDAta(cust_id,Cust_name,Address_ID,start_time,End_Date,.....,other 7 columns);
And assuming 2 customers have SAme Address ID to get Duplicates.
To insert Into Archive Table:-
INSERT INTO archive (column1, column2, ... column10)
SELECT cust_id, start_Date, ...,End_Date
FROM CustomerData
WHERE END_DATE IS NOT NULL
AND Address_ID IN(
SELECT Address_ID FROM
(
SELECT Address(ID),count(Address_ID)
FROM customerDAta
GROUP BY Address_ID
HAVING count(Adddress_ID)>1
)
)
)
To Delete From:- CustomerDAt Table:-
DELETE CustomerData
WHERE END_DATE IS NOT NULL
AND
Address_ID IN(
SELECT Address_ID FROM
(
SELECT Address(ID),count(Address_ID)
FROM customerDAta
GROUP BY Address_ID
HAVING count(Adddress_ID)>1
)
)
INNER SubQuery to Extract Duplicates BAsed on same Address_ID column similar to DeptID column in employees table provided with oracle database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Printing in Java I just want to ask, We are creating a web-based system using JSF and Java. is there any way that I can Access the client's printer setting? or is it possible to configure programatically the printer settings of Acrobat Reader? because we created a Pdf file using IText and then print it by the client. Thanks
A: No.
A webbrowser does not offer that functionality.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: js function calling another js function and returning a value problem i have this JS function:
function ax_get_new_msg_cnt()
{ var mTimer;
var last_msg_id;
mTimer = setTimeout('ax_get_new_msg_cnt();',30000);
$.getJSON('/apps_dev.php/profile/newMessageCheck', function(data)
{
$('#newMessageDiv').text("You have " + data.msg_cnt + " new ");
last_msg_id = data.msg_id;
});
return last_msg_id;
}
then i have the js function where i call ax_get_new_msg_cnt():
function ax_get_new_msg_details()
{
var mTimer;
mTimer = setTimeout('ax_get_new_msg_details();',30000);
$.getJSON('/apps_dev.php/messagebox/newMessageDetails', function(data)
{
var str='<tr>';
str += "<td class='td_show_contact_item' align='left' id='td_date'>"+data.td_date+'</td>';
str += "<td align='left' id='td_subject'><a href='#' style='color:#ff0000 !important' class='spn_small_red_rbc'>"+data.td_subject+"</a></td>";
str += "<td class='td_show_contact_item' align='left' id='td_from'>"+data.td_from +"</td>";
//str += "<td id='block_url'>"+data.block_url+"</td>";
str +='<tr>';
var tbl = $('#td_date').parents('table');
var msg_id = ax_get_new_msg_cnt();
console.log(msg_id);
if (msg_id == data.td_id)
{
}
else
{
$(tbl).append(str);
}
});
}
in the above function i get msg_id as undefined...
can i do it the way i have it or is there another way please?
only if msg_id != data.td_id i want to do the append
thank you
A: You need to understand the asynchronous way of programming.
In your first method, when it gets called it starts an async JSON request to the webserver, which will return later in time, but your $.getJSON call return immediately, so your last_msg_id variable will be untouched and this untouched (undefined) variable will be returned by ax_get_new_msg_cnt function.
Later when the webserver returned with the answer and the answer is read by your browser it passes back to your callback function which sets the last_msg_id.
You can write console.log debug messages to see the timings:
*
*if you insert a console.log('JSON start'); to your ax_get_new_msg_details method before the $.getJSON call
*then one console.log('Response arrived'); to inside the function(data) part
*and an another one right before the end with console.log('JSON request sent');
then, you'll probably see the way of executing.
A: What ever you want to do with msg_id you need to do it in $.getJSON callback function. You can not return it. The Ajax call is asyncron, so you have to wait till it is finished to get the value.
A: Because the $.getJSON() method is asynchronous, your ax_get_new_msg_cnt() function will return before the data is received, leaving last_msg_id as undefined.
Moreover, I think that the URL parameter for $.getJSON() should point to a file, not to a folder.
Note: you could improve your code by using the $.ajaxSetup method to set a default timeout for all your jQuery ajax requests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can we replace the purpose of init method to the servlet constructor? Can we replace the pupose of init method to the servlet constructor?
My question is why does servlet need a separate method int(ServletConfig config) for the pupose of initialization we could have achieve the same thing by having a parameterised constructor let XServlet(ServletConfig config) and the container can invoke the same .
A: Probably because you cannot specify the parameter signature for constructors in an interface.
A: It is generally considered a bad practice to perform logic in constructor (it should only initialize the field and create object in consistent state). It also makes testing harder.
Also it is much harder to perform injection - when using init the container can create a servlet, inject dependencies and run init. With constructor you would expect to have all the dependencies already set. Wicket works around this problem by injecting Spring beans into page class from superclass constructor - because superclass constructor runs first. However modifying subclass fields from superclass constructor seems wrong.
That being said using separate init method some things simpler and easier to maintain. Also note that EJB promotes @PostConstruct annotation as well.
A: I guess this choice was made to simplify the coding of servlets. In the current situation, a servlet having no need for specific initialization can be coded like this:
public class MyServlet extends HttpServlet {
// doGet, doPost, etc.
}
If the servlet was initialized using the constructor, it would need to be coded like this:
public class MyServlet extends HttpServlet {
public MyServlet(ServletConfig config) {
super(config);
}
// doGet, doPost, etc.
}
BTW, they even introduced a no-arg init method that can be used to avoid being forced to call super.init(config).
A: Short answer: NO.
Long answer:
If a servlet contains a constructor and a init method, you will see the constructor is called first, and then the init method (try it out with sysout statements).
A servlet is a java class, so it must follow the java process, so constructor is called first and then the init method (note that the init method is called by your servlet container like tomcat because that's how servlet's are supposed to be initialized; read the servlet specification).
So, if you need to do some operation that is specific to your business need (say create an DB connection or read a set of user details etc); constructors are not the best place to put these things in.
Usually constructors should never have any complex logic/business processing. They should initialize bare minimum member variables and leave the complex things to later; in case of servlets the heavy lifting can be done by init method.
Also note that by the time the init() is called the servlet container is up and ready with it's system resources, i.e it would have initialized the JNDi name bindings, data sources so on and so forth.
So in a way it guarantees you that when you call the init(), it will have the system resources ready for you to work on.
The servlet 3 spec says this:
2.3.1 Loading and Instantiation The servlet container is responsible
for loading and instantiating servlets. The loading and instantiation
can occur when the container is started, or delayed until the
container determines the servlet is needed to service a request. When
the servlet engine is started, needed servlet classes must be located
by the servlet container. The servlet container loads the servlet
class using normal Java class loading facilities. The loading may be
from a local file system, a remote file system, or other network
services. After loading the Servlet class, the container instantiates
it for use.
2.3.2 Initialization After the servlet object is instantiated, the
container must initialize the servlet before it can handle requests
from clients. Initialization is provided so that a servlet can read
persistent configuration data, initialize costly resources (such as
JDBC APIbased connections), and perform other one-time activities. The
container initializes the servlet instance by calling the init method
of the Servlet interface with a unique (per servlet declaration)
object implementing the ServletConfig interface. This configuration
object allows the servlet to access name-value initialization
parameters from the Web application’s configuration information. The
configuration object also gives the servlet access to an object
(implementing the ServletContext interface) that describes the
servlet’s runtime environment. See Chapter 4, Servlet Context for more
information about the ServletContext interface.
Read this part:
The servlet container loads the servlet class using normal Java class loading facilities.
so, the container will have to use standard java class loading mechanism. Which means it can not do what Duncan have just suggested.
A: int(ServletConfig config) is a life cycle method of Servlet.and it is being called by servlet container.
We can replace the init method code in parameter constructor of super class servlet.
but we can't force the developer to call super class constructor
for example
/*If generic servlet has a constructor like this*/
public GenericServlet(ServletConfig config){
....
}
/*And Developers servlet is calling only default servlet.*/
public MyServlet(){
super();
}
So in this scenario initialization never happens for that servlet. it cause issues problem. because ServletConfig obj is not initialized.
And we cant force the user to call specifict super class constructor.
A: The simple answer is that you have to have a no-arg ctor and an init method because that is what the spec requires...
Why the spec is written like that is probably a matter of history. These days I think that we might defer construction until the ServletContext is available and call a ctor with that argument. But looking back there was a ServletContext.getServlet(name) method, so that one servlet could look up another on initialisation and communicate with it. For this to work they would all have had to be created up-front and then init'd.
getServlet was deprecated and now returns null (I think it was a security hole for containers that were running multiple apps).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android simple way to record sound and stream that to a server? Is there a simple way to record sound and stream it to a server in real time?
Thanks,
Leslie
A: No, there is no direct API that would do that..
What people usually do is read the media file as it is being saved, and upload it progressively to server.
See how some open-source projects do it:
http://code.google.com/p/sipdroid/
http://code.google.com/p/ipcamera-for-android/
http://code.google.com/p/camdroiduni/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In Apple Numbers, how can I calculate a difference between two dates? I have a spreadsheet with data in Apple Numbers. I have a column of dates, and I would like to create a second column which displays the difference in number of days between the two dates.
Example:
Date..................Difference
May 1, 2011......NA
May 3, 2011......2
May 8, 2011......5
My first inclination is applescript, but perhaps applescript might be overkill for this task.
In any case, please fwd as needed.
A: Applescript and Automator is definitely overkill. All you need to do given two dates is reference the cells in an equation and Pages handles the rest. So, given...
'A' 'B'
'1' '2011 September 28' ''
'2' '2011 September 27' ''
'3' '2011 September 20' ''
...you only need to do then...
'A' 'B'
'1' '2011 September 28' ''
'2' '2011 September 27' '=A2-A1' --> gives "1d"
'3' '2011 September 20' '=A3-A1' --> gives "8d"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASIHTTPRequestErrorDomain Code=8. Cannot move file from temp directory to docs I download files with ASIHTTPReqeust. Everything downloads fine but it can't move file from temp directory to documents. When i implement
-(void) request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
request fails with an error. But file is downloaded.
If i remove this implementation, everything is fine, and files are moving to docs.
Here is Error text:
Error Domain=ASIHTTPRequestErrorDomain Code=8 "Failed to move file from '/var/folders/Qu/Qu0o0VcpEY4npJr2C1yPzE+++TI/-Tmp-/Skrillex feat. Nero - Wobbleland.mp3' to '/Users/Timur/Library/Application Support/iPhone Simulator/4.3/Applications/34389282-4013-4354-95D9-DF2847B4EE55/Documents/Audio/Skrillex feat. Nero - Wobbleland.mp3'" UserInfo=0x5949520 {NSUnderlyingError=0x59992a0 "The operation couldn’t be completed. (Cocoa error 4.)", NSLocalizedDescription=Failed to move file from '/var/folders/Qu/Qu0o0VcpEY4npJr2C1yPzE+++TI/-Tmp-/Skrillex feat. Nero - Wobbleland.mp3' to '/Users/Timur/Library/Application Support/iPhone Simulator/4.3/Applications/34389282-4013-4354-95D9-DF2847B4EE55/Documents/Audio/Skrillex feat. Nero - Wobbleland.mp3'}
Who had similar problem?
A: Something that often catches people out is that you have to create the directory that you're downloading into yourself (ASIHTTPRequest won't create it automatically).
However given you say it's related to the implementing didReceiveData it's not that.
If you look at ASIHTTPRequest.m, you'll see it sets 'dataWillBeHandledExternally' if you implement 'didReceiveData' in the delegate - this will be preventing the data being written to disk. You can either write the data yourself, or you could change the ASIHTTPRequest.m code to add a flag to force it to handle the data internally too.
A: I encountered same error, but the reason was different. I will post my problem - just in case anyone else has similar situation.
I was trying to delete old images, before saving new ones.
NSString *mImgName = [managedObj valueForKey:@"aImgName"];
NSString * mFilePath = [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:mImgName];
if ([mFileManager fileExistsAtPath:mFilePath])
{
[mFileManager removeItemAtPath:mFilePath error:nil];
}
Problem was - in case mImgName is nil, mFileManager will delete whole directory.
By adding extra checking for nil or too short mImgName value, it solved problem.
Hopefully it will help someone!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Strange (for me) behavior of pointers I'm reading about pointers, but i'm confused about their nature. Here is what I mean.
int x = 4;
//Here I declare p as integer pointer
int *p;
// Here I assign memory address of x to pointer p
p = &x;
// The line below prints result 4 which is expected. If I miss asterisk before p I'll get memory address instead of data which that memory address holds.
printf("%d", *p)
Summarizing when asterisk is mising before pointer it "points" to memory address. If asterisk preceded pointer it "points" to actual data.
So far so good.
But why that segment of code works correctly ?
int someIntVariable = 10;
const int *p = &someIntVariable;
printf("%d", *p);
If I miss asterisk the compiler gives me an warning " warning: initialization makes integer from pointer without a cast"
I expected p (if the compiler allows me to use p without asterisk) to hold memory address of someIntVariable instead of it's "value";
What is happening here ?
A: In the declaration:
const int *p = &someIntVariable;
The asterisk is not the dereference operator. It simply states p is a pointer. That line has the same effect as
const int *p;
p = &someIntVariable;
A: Here you are declaring a pointer and assigning a value to the pointer in one step.
It is equivalent to the following code:
const int *p;
p = &someIntVariable;
Here the * is not used as a de-referencing operator. It is used in the context of pointer declaration.
A: The const int * is a datatype - i.e. pointer to a const int. p is the name of the variable. It is on the LHS.
When asterik is on the RHS it has a different meaning. It means dereference.
A: I belive you got the warning:initialization makes integer from pointer without a cast,
when you tried these way
int someIntVariable = 10;
const int p = &someIntVariable;
printf("%d", p);
What your trying to do is , Your assigning a address to a normal variable and your expecting it to work but that is not how the normal variables used thats why pointers came into act to do that job and your trying to replace a pointer with normal variable
I still did not find the real answer to it but Just check out these question that I asked I wonder what really the &a returns?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change the post login target on FOSuserBundle Symfony2 When I log in /login, I'm sent to the root url /, however I'd like to send users straight to another page /dashboard - is this a configurable option?
I'm using FOSUserBundle and Symfony2.
A: It seems that login is handled by SecurityBundle, not by FOSUserBundle. The solution is to put the login target here:
#app/config/security.yml
security:
firewalls:
somename:
form_login:
default_target_path: /your-desired-path
Symfony2 documentation here http://symfony.com/doc/current/reference/configuration/security.html#form-login-configuration
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenCV. Drawing rectangle when matching i use OpenCv to find an area witch match a template on a reference image. When the code find the area witch match a template draw a rectangle around the area but what i want is when the code doesnt find the area the code doesnt draw any rectangle
code:
IplImage *res;
CvPoint minloc, maxloc;
double minval, maxval;
int img_width, img_height;
int tpl_width, tpl_height;
int res_width, res_height;
NSString *path = [[NSBundle mainBundle] pathForResource:@"reference" ofType:@"jpg"];
reference.image = [UIImage imageWithContentsOfFile:path];
NSString *pathPatron = [[NSBundle mainBundle] pathForResource:@"template" ofType:@"jpg"];
template.image = [UIImage imageWithContentsOfFile:pathPatron];
IplImage *img = [self CreateIplImageFromUIImage:original.image];//
IplImage *tpl = [self CreateIplImageFromUIImage:patron.image];
img_width = img->width;
img_height = img->height;
tpl_width = tpl->width;
tpl_height = tpl->height;
res_width = img_width - tpl_width + 1;
res_height = img_height - tpl_height + 1;
res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
/* choose template matching method to be used */
cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF );
cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );
/* draw red rectangle */
cvRectangle( img,
cvPoint( minloc.x, minloc.y ),
cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );
/* display images */
reference.image = [self UIImageFromIplImage:img];
cvReleaseImage(&img);
cvReleaseImage(&tpl);
cvReleaseImage(&res);
Thanks in advance
A: cvMatchTemplate does not really find the match - it just calculates similarity map for your image and template. Next you need to decide if there is a real match or there are no matches. The simplest solution is a comparison with some threshold:
if (minval < THRESHOLD)
{
//draw rectangle
}
You need to make some experiments to find a working value of the THRESHOLD.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I create a mock using reflection with parameters using Moq? I am trying to build a Generic testbuilder for generating objects, that i want to use in tests. One of the things I want to create is Mock implementations of interfaces. I want these Mocks to have Strict mockbehaviour, and the only way to set that afaik is by constructor parameter. I am using this code to create my interface mock:
public object Build(Type type)
{
if (type.IsInterface)
{
List<object> mockParameters = new List<object>();
mockParameters.Add(MockBehavior.Strict);
Mock mock = (Mock)Activator.CreateInstance(typeof(Mock<>).MakeGenericType(type), mockParameters);
return mock.Object;
}
}
This gives me an ArgumentException: Constructor arguments cannot be passed for interface mocks.
How can i set MockBehavior.Strict on my mock created with reflection?
A: Your code can be greatly simplified to this:
public T Build()
{
if (typeof(T).IsInterface)
{
return new Mock<T>(MockBehavior.Strict).Object;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JAX-WS and version conflicts As test project I've create a very simple WebService using wsdl and jax-ws. The client runs very well if it is deployed as web application in GlassFish but if I start the same (WebService-)Code in Eclipse directly, I get the following error:
WARNUNG: Input Action on WSDL operation AddNumbers and @Action on its associated Web Method addNumbers did not match and will cause problems in dispatching the requests
Exception in thread "main" java.lang.NoClassDefFoundError: org/glassfish/ha/store/api/BackingStoreException
at com.sun.xml.ws.rx.mc.runtime.McConfigurationFactory.createInstance(McConfigurationFactory.java:66)
at com.sun.xml.ws.rx.mc.runtime.McTubeFactory.createTube(McTubeFactory.java:68)
at com.sun.xml.ws.assembler.TubeCreator.createTube(TubeCreator.java:84)
at com.sun.xml.ws.assembler.TubelineAssemblerFactoryImpl$MetroTubelineAssembler.createClient(TubelineAssemblerFactoryImpl.java:130)
at com.sun.xml.ws.client.Stub.createPipeline(Stub.java:228)
at com.sun.xml.ws.client.Stub.<init>(Stub.java:205)
at com.sun.xml.ws.client.Stub.<init>(Stub.java:178)
at com.sun.xml.ws.client.sei.SEIStub.<init>(SEIStub.java:85)
at com.sun.xml.ws.client.WSServiceDelegate.createEndpointIFBaseProxy(WSServiceDelegate.java:608)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:348)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:330)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:312)
at javax.xml.ws.Service.getPort(Service.java:134)
at mnm.namedesdienstes.webservice.service.NameDesDienstesService.getNameDesDienstesPortTypePort(NameDesDienstesService.java:56)
at webserviceClient.NameDesDienstesClient.myTest(NameDesDienstesClient.java:12)
at webserviceClient.NameDesDienstesClient.main(NameDesDienstesClient.java:25)
Caused by: java.lang.ClassNotFoundException: org.glassfish.ha.store.api.BackingStoreException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 16 more
After some research I found out that it must have something to do with different versions of some library files. So now my question is, how can I "fix" my eclipse java execution to run my webservice client correctly? I've found some tips to copy some jar to an endorsed-directory, but which jars into which directory :-)
I'm using Max OS 10.6.8, Eclipse Project uses JVM 1.6. My Mac Java Version is
xmacbook:~ cstraube$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03-384-10M3425)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-384, mixed mode)
UPDATE: My first try (thanks to the link from remipod) I performed the following steps:
*
*Get the directory of endorsed lirbaries with System.out.println(System.getProperty("java.endorsed.dirs"));
*Next, I copied the two files JAXWS2.1.7-20090419.jar and JAXB2_20080513.jar (both Version 2.1.7) into this directory
*Unfortunately I get still the same error
A: You have to copy the fitting versions of jaxws-api.jar and jaxb-api.jar into the directory /Library/Java/Home/lib/endorsed (Mac).
A: I have similar problem with yours when deploying web service (JAX-WS) in tomcat 7.
The missing class definition could be found in ha-api.jar.
org/glassfish/ha/store/api/BackingStoreException
You should add the ha-api.jar (From JAX-WS distribution) into server lib. For my case, the eclipse run tomcat 7, so the location is (Tomcat 7.0\lib).
A: Have a look at this link JAX WS with WS 2.1.1. You will need to give precedence to your version of jaxws to the provided jaxws from the jre 1.6.
Edit:
Glassfish already includes some libraries, as well as java 6. I had to track down version conflicts with jaxws in glassfish 3.1 / 3.1.1 and java 6 / 7. You might check the exact java runtime eclipse uses to start the application and look for duplicate jars on the effective classpath.
The endorsed mechanism just provides an easy and error prone way to override the included jaxws distribution. Error prone, because your colleague will suffer from the same problem.
I havn't seen the exception org.glassfish.ha.store.api.BackingStoreException in the context of jaxws. Your version conflict could be created by another library than jaxws...
A: I experienced the exact same exception
org.glassfish.ha.store.api.BackingStoreException
And after ensuring my JAX-WS and JAX-B jars were all the same version the issue was still occurring.
THE FIX: I then added the ha-api.jar to the WEB-INF\lib directory and this solved the issue.
The clue here was the "ha" package in the exceptions class path as seen above. Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: gzip with webserver without content-coding I have a webserver without content-coding (boa and not enough ressources). is there a possibility to put ziped javascript-file on the webserver and unzip it at the browser after downloading like content-coding?
A: In theory yes. You would need to add the Content-Encoding: deflate header to your http response.
You can not place a zip file created by a zip program on the server to be transferred, as it contains a header with the file structure before the deflate payload begins.
Also mind the differences between gzip and deflate. With gzip, similar is possible, too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hibernate & postgreSQL with Grails There is an easy way to set hibernate to use different primary key ids for each table with postgres?
I tried to use postgres dialect in DataSource:
dialect = org.hibernate.dialect.PostgreSQLDialect
or
dialect = net.sf.hibernate.dialect.PostgreSQLDialect
But it doesn't work.
Thanks
A: The short answer is no, there isn't a easy way to do this. However, I have found a solution that does work. Basically you need to implement a custom dialect. Here is an implementation (please note the original source of the implementation within the comments).
package com.my.custom;
import java.util.Properties;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.SequenceGenerator;
import org.hibernate.type.Type;
/**
* Creates a sequence per table instead of the default behavior of one sequence.
*
* From <a href='http://www.hibernate.org/296.html'>http://www.hibernate.org/296.html</a>
* @author Burt
*/
public class TableNameSequencePostgresDialect extends PostgreSQLDialect {
/**
* Get the native identifier generator class.
* @return TableNameSequenceGenerator.
*/
@Override
public Class<?> getNativeIdentifierGeneratorClass() {
return TableNameSequenceGenerator.class;
}
/**
* Creates a sequence per table instead of the default behavior of one sequence.
*/
public static class TableNameSequenceGenerator
extends SequenceGenerator {
/**
* {@inheritDoc}
* If the parameters do not contain a {@link SequenceGenerator#SEQUENCE} name, we
* assign one based on the table name.
*/
@Override
public void configure(
final Type type,
final Properties params,
final Dialect dialect) {
if (params.getProperty(SEQUENCE) == null
|| params.getProperty(SEQUENCE).length() == 0) {
String tableName = params.getProperty(PersistentIdentifierGenerator.TABLE);
if (tableName != null) {
params.setProperty(SEQUENCE, "seq_" + tableName);
}
}
super.configure(type, params, dialect);
}
}
}
The above implementation is should be stored as TableNameSequencePostgresDialect.java under src/java/com/my/custom within your Grails project.
Next, update your DataSource.groovy to use this new custom dialect.
dialect = com.my.custom.TableNameSequencePostgresDialect
That's pretty much about it. Not easy but it can be done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Parse C# string to DateTime I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
A: You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
A: Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
A: string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: SnapsToDevicePixels issue In my WPF app, I have created few Line elements and added inside a StackPanel. The thickness for all lines is set to 0.5. But when I render it, sometimes few lines are appearing blur. I tried setting SnapsToDevicePixels in the StackPanel but this makes the lines completely invisible. Now if I increase the line thickness to 1 or greater than 1 then SnapsToDevicePixels is working properly.
I am creating Line as shown below:
private void CreateLine(Double y1, Double y2, Double x1, Double x2, Double width, Double height)
{
Line line = new Line() { Y1 = y1, Y2 = y2, X1 = x1, X2 = x2, Width = width, Height = height };
}
Here, if LineThickness is set to 0.5, x1 and x2 values will be 0.25 (LineThickenss / 2) and width is 0.5 (LineThickness).
Is there any minimum pixel value required to be set in order to make the SnapsToDevicePixels work in WPF?
A: I solved many of my SnapToDevicePixels issues by using UseLayoutRounding instead:
In your case:
<StackPanel UseLayoutRounding="True">
...
</StackPanel>
I don't know if this will solve your issue, but from my experience, it's worth a try!
A: No, there isn't a minimum per se. The blurriness you are experiencing is due to how WPf handles drawing in general. According to my experience you can't really do anything about it. Snapping to device pixels may give some reprieve, but can still be unpredictable.
Also there is a difference between a pixel and a WPF unit that makes things more complicated, though many techniques exist to translate between them.
A common approach to translating the pixel to WPF unit is:
Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
double dpiFactor = 1/m.M11;
double lineThickness = dpiFactor * 1; // Repace '1' with desired pixel size.
Here is a useful article on the topic:
http://www.wpftutorial.net/DrawOnPhysicalDevicePixels.html
A: It is not recommended to set fractional positions.
What means the half of WPF point?
WPF will interpret 1 point as 1/96 inch. It differs in pixels for distinct monitors (96 DPI, 300 DPI).
WPF considers 1 point as 1 pixel in the usual monitors with 96 DPI. And
UIElement.SnapsToDevicePixels works great. It tries to snap 0.5 pixel to the monitor grid. There are two results: enlarged version two one pixel or shortened version to 0 pixel (disappears).
If for some reason there is a need for exact 1 pixel (not 1 point) positioning then use GuidelineSet.
With .NET 4 or higher it is better to use Layout Rounding. It calculates pixel offsets at the UI position measuring level. While SnapsToDevicePixels works at the render level. The minus for Layout Rounding is that it is bad for dynamic moving.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Hooking Generic Repository With IOC container I am trying to create a generic repository pattern where i can swtich ORM technogies , But i stumbled upon this problem when trying to hook with IOC container
public interface IRepository<T>
{
//members
}
For NHbernate this works fine
public class FNHRepository<T>: IRepository<T>
{ //members }
But for Entity i am forced to add where clause
public class EFRepository<T> : IRepository<T> where T : class
{
if i am omiting the "where clause" i am not able to do
dbset = DataContext.Set<T>() ;
saying only reference type can be used as T
The problem comes when i am trying to hook IRepository with an IOC , like this
.RegisterType(typeof(IRepository<>), typeof(EFRepository<>));
I am not able to hook the interface if the implemeting class is having where T : class , I am getting the following execption
xception is: InvalidOperationException - The current type, System.Web.Mvc.IControllerFactory, is an interface and cannot be constructed. Are you missing a type mapping?
Any help appriciated , i tried this with Unity and Autofac and getting the same error
A: Not sure about Unity, but you should be able to register a generic class with constraints just fine.
builder.RegisterGeneric(typeof(EFRepo...))
.AsImplementedInterfaces();
The problem though is this: without the same constraint on the interface, this is bound to fail:
container.Resolve<IRepo<int>>();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Native Methods - java where to find the source code of the machine specific native methods declared in java...
For example private static native Class forName0(String name, boolean initialize,
ClassLoader loader)
A: Use Google code search (see here for the search results).
You'll be looking for C code from the JDK implementation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem displaying images obtained in byte format from server I am getting a few icon files (92X92) from a server. I need to parse them and store them in a dictionary and later display them on the UI. I am using the following code for obtaining the File Name and for other action:
System.Windows.Media.Imaging.BitmapImage icon = null;
using (AutoResetEvent are = new AutoResetEvent(false))
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MemoryStream byteStream = new MemoryStream(resp);
byteStream.Write(resp, 0, resp.Length);
icon = new BitmapImage();
icon.SetSource(byteStream);
Console.WriteLine(icon.PixelHeight + ":" + icon.PixelWidth);
string[] iconname = entry.Name.Split(new char[] { '-' });
string newimagename = iconname[1];
are.Set();
string[] newname = entry.Name.Split(new char[] { '-', '.' });
iconDict.Add(newimagename, icon);
});
are.WaitOne();
//string[] newname = entry.Name.Split(new char[] { '-', '.' });
//string newFileName = newname[1];
//iconDict.Add(newFileName, icon);
}
Now my problem is that I am not able to obtain the Uri and am not even getting the icon(but when i put breakpoint n chk the height and width are 92X92); when I try to display it I end up displaying blank space instead of images. I am binding these images to a listbox along with their name that I receive. Names are getting displayed without any problem.
A: changes i made are ;
using (AutoResetEvent are = new AutoResetEvent(false))
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MemoryStream byteStream = new MemoryStream(resp);
byteStream.Write(resp, 0, resp.Length);
string[] iconname = entry.Name.Split(new char[] { '-' });
string newimagename = iconname[1];
Uri icon_url = new Uri(newimagename, UriKind.RelativeOrAbsolute);
icon = new BitmapImage(icon_url);
imag = new Image();
imag.Source = icon;
sourceofImage = icon.UriSource.ToString();
icon.SetSource(byteStream);
Console.WriteLine(icon.PixelHeight + ":" + icon.PixelWidth);
are.Set();
// string[] newname = entry.Name.Split(new char[] { '-', '.' });
// iconDict.Add(sourceofImage, icon);
});
are.WaitOne();
string[] newname = entry.Name.Split(new char[] { '-', '.' });
string newFileName = newname[1];
iconDict.Add(newFileName, icon);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert a week number to a date in Javascript I had tried to find some work done but I haven't had luck. Any ideas?
Examples:
Week, 1, 2001 => 2001-01-01
Week, 26, 2007 => 2007-06-01
A: Someone might be still interested in a more contained version:
function firstDayOfWeek (year, week) {
// Jan 1 of 'year'
var d = new Date(year, 0, 1),
offset = d.getTimezoneOffset();
// ISO: week 1 is the one with the year's first Thursday
// so nearest Thursday: current date + 4 - current day number
// Sunday is converted from 0 to 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// 7 days * (week - overlapping first week)
d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000
* (week + (year == d.getFullYear() ? -1 : 0 )));
// daylight savings fix
d.setTime(d.getTime()
+ (d.getTimezoneOffset() - offset) * 60 * 1000);
// back to Monday (from Thursday)
d.setDate(d.getDate() - 3);
return d;
}
A: As Kevin's code does not implement ISO 8601 properly (first day of the first week of year must be a Monday), I've corrected it and ended up with (also check it on jsfiddle):
function firstDayOfWeek(week, year) {
if (year==null) {
year = (new Date()).getFullYear();
}
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = date.getTime() + weekTime;
return date.setTime(targetTime);
}
function weeksToMilliseconds(weeks) {
return 1000 * 60 * 60 * 24 * 7 * (weeks - 1);
}
function firstWeekOfYear(year) {
var date = new Date();
date = firstDayOfYear(date,year);
date = firstWeekday(date);
return date;
}
function firstDayOfYear(date, year) {
date.setYear(year);
date.setDate(1);
date.setMonth(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
/**
* Sets the given date as the first day of week of the first week of year.
*/
function firstWeekday(firstOfJanuaryDate) {
// 0 correspond au dimanche et 6 correspond au samedi.
var FIRST_DAY_OF_WEEK = 1; // Monday, according to iso8601
var WEEK_LENGTH = 7; // 7 days per week
var day = firstOfJanuaryDate.getDay();
day = (day === 0) ? 7 : day; // make the days monday-sunday equals to 1-7 instead of 0-6
var dayOffset=-day+FIRST_DAY_OF_WEEK; // dayOffset will correct the date in order to get a Monday
if (WEEK_LENGTH-day+1<4) {
// the current week has not the minimum 4 days required by iso 8601 => add one week
dayOffset += WEEK_LENGTH;
}
return new Date(firstOfJanuaryDate.getTime()+dayOffset*24*60*60*1000);
}
function assertDateEquals(effectiveDate, expectedDate, description) {
if ((effectiveDate==null ^ expectedDate==null) || effectiveDate.getTime()!=expectedDate.getTime()) {
console.log("assert failed: "+description+"; effective="+effectiveDate+", expected="+expectedDate);
}
}
function assertEquals(effectiveValue, expectedValue, description) {
if (effectiveValue!=expectedValue) {
console.log("assert failed: "+description+"; effective="+effectiveValue+", expected="+expectedValue);
}
}
// expect the first day of year to be a monday
for (var i=1970; i<2050; i++) {
assertEquals(firstWeekOfYear(i).getDay(), 1, "first day of year "+i+" must be a monday"); // 1=Monday
}
// assert some future first day of first week of year; source: http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
assertDateEquals(firstWeekOfYear(2013), new Date(Date.parse("Dec 31, 2012")), "2013");
assertDateEquals(firstWeekOfYear(2014), new Date(Date.parse("Dec 30, 2013")), "2014");
assertDateEquals(firstWeekOfYear(2015), new Date(Date.parse("Dec 29, 2014")), "2015");
assertDateEquals(firstWeekOfYear(2016), new Date(Date.parse("Jan 4, 2016")), "2016");
assertDateEquals(firstWeekOfYear(2017), new Date(Date.parse("Jan 2, 2017")), "2017");
assertDateEquals(firstWeekOfYear(2018), new Date(Date.parse("Jan 1, 2018")), "2018");
assertDateEquals(firstWeekOfYear(2019), new Date(Date.parse("Dec 31, 2018")), "2019");
assertDateEquals(firstWeekOfYear(2020), new Date(Date.parse("Dec 30, 2019")), "2020");
assertDateEquals(firstWeekOfYear(2021), new Date(Date.parse("Jan 4, 2021")), "2021");
assertDateEquals(firstWeekOfYear(2022), new Date(Date.parse("Jan 3, 2022")), "2022");
assertDateEquals(firstWeekOfYear(2023), new Date(Date.parse("Jan 2, 2023")), "2023");
assertDateEquals(firstWeekOfYear(2024), new Date(Date.parse("Jan 1, 2024")), "2024");
assertDateEquals(firstWeekOfYear(2025), new Date(Date.parse("Dec 30, 2024")), "2025");
assertDateEquals(firstWeekOfYear(2026), new Date(Date.parse("Dec 29, 2025")), "2026");
console.log("All assertions done.");
I included test cases for some dates to check that the first day of the first week of year is a Monday and checked some dates based on http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
A: I took the original idea from Kevin, with some tweaks, coz the original code is returning milliseconds. Here you go:
var d = firstDayOfWeek(9, 2013);
console.log(d.format("yyyy-MM-dd"));
////////////////////////////// Main Code //////////////////////////////
function firstDayOfWeek(week, year) {
if (typeof year !== 'undefined') {
year = (new Date()).getFullYear();
}
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = date.getTime() + weekTime - 86400000;
var result = new Date(targetTime)
return result;
}
function weeksToMilliseconds(weeks) {
return 1000 * 60 * 60 * 24 * 7 * (weeks - 1);
}
function firstWeekOfYear(year) {
var date = new Date();
date = firstDayOfYear(date,year);
date = firstWeekday(date);
return date;
}
function firstDayOfYear(date, year) {
date.setYear(year);
date.setDate(1);
date.setMonth(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
function firstWeekday(date) {
var day = date.getDay(),
day = (day === 0) ? 7 : day;
if (day > 3) {
var remaining = 8 - day,
target = remaining + 1;
date.setDate(target);
}
return date;
}
A: Take a look at this fiddle. First, it gets the first week of the specified year. This takes into account that according to ISO 8601 the first week of the year is the first week containing a wednesday. Then it adds the weeks to the acquired date and returns the result.
function firstDayOfWeek(week, year) {
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = weekTime + date.getTime();
return date.setTime(targetTime);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Differences between Google NFC API and Open NFC API? As the title suggests I am looking for information that would allow me to differentiate and choose one of both possibilities in order to develop of NFC on Android.
link NFC Google API:http://developer.android.com/resources/samples/NFCDemo/index.html
link NFC Open API: http://www.open-nfc.org/opennfc_library/overview-summary.html
Can you tell me what you know about this?
Thanks in advance!
A: please check this link - there is in a quite detailed way described the difference between both solutions. The answer written here by Sebastien is the official Open NFC stack statement. Also Nikolay Elenkov is right about the fact, that unless you are doing your own device or you are re-flashing it somehow you will use the Google API only.
BR
STeN
A: At the moment (Android 2.3.4), the Android platform does not integrate the Open NFC stack. This stack has several advantages: not limited to one particular NFC hardware, portable to many different environments (not only Android), many additional features compared to the current stack. On the other hand, because Open NFC is not part of the standard Android environment, it requires some work (but it is actually quite easy) to use this stack in an Android platform. The Open NFC documentation describes this process.
The Open NFC stack is parallel activity and is optional replacement to the current stack. Due to its description it overcomes some limits of the Google NFC stack implementation and makes new HW adaptions (i.e. support for new tag types) easier…
This stack is intended to by used by device manufacturers, not mobile developers, because the standard Android kernel does not support modules loading, the Open NFC stack cannot be simply installed as another application, it requires a kernel change. But once the kernel is replaced, it is quite easy to deploy and use the Open NFC stack.
An application developer should probably stick to the OS features, even if more limited, since they assure the portability of the code over any NFC-enabled phone. But if you are trying to use "more" features than what comes with Android, Open NFC is a good candidate.
In Conclusion :
Until some phone manufacturer will integrate the stack into device, it does not make too much sense to be interested in Open NFC stack. An app developer cannot make use of Open NFC unless it is on hardware.
A: You already have the links, how about reading them?
Unless you are flashing your own firmware, you have to stick to the APIs available in the Android SDK. If you are building/customizing your own device you can flash an image and kernel that supports Open NFC. I haven't actually used it, but it looks like Open NFC offers lower level APIs, thus giving you more control.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Script to change ip address on windows I use my computer to communicate with a piece of hardware via ethernet. To communicate with this device I set my ip to 192 168 0 11, subnet mask to 255 255 255 0, and default gateway to 192 168 0 1 for IPv4. To use the internet, I choose "Obtain an IP address automatically" via control panel.
I'd like to have a script that allows my to quickly choose one or the other ethernet setting - hardware or internet.
I program mostly in python but maybe there is a batch file solution.
Thanks,
Barry.
A: You can use the subprocess module to start
netsh interface ip set address [params]
Start this from the commandline (without[params]) to get some help how to use it. Then you can do
import subprocess
subprocess.call("netsh interface ip set address ....".split())
Update:
For those who's too busy to rtfm,
netsh interface ip set address lan static 192.168.0.100 255.255.255.0
netsh interface ip set address lan dhcp
here lan is the name of the network interface to configure, 192.168.0.100 is ip address, 255.255.255.0 is network mask. The first command sets static address, the second reverts to dhcp.
A: You can use the Python WMI module to do this (install the PyWin32 extensions and the WMI module before running these scripts). Here is how to configure things to talk to the hardware device:
import wmi
# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
# First network adaptor
nic = nic_configs[0]
# IP address, subnetmask and gateway values should be unicode objects
ip = u'192.168.0.11'
subnetmask = u'255.255.255.0'
gateway = u'192.168.0.1'
# Set IP address, subnetmask and default gateway
# Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
nic.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
nic.SetGateways(DefaultIPGateway=[gateway])
Here is how to revert to obtaining an IP address automatically (via DHCP):
import wmi
# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
# First network adaptor
nic = nic_configs[0]
# Enable DHCP
nic.EnableDHCP()
Note: in a production script you should check the values returned by EnableStatic(), SetGateways() and EnableDHCP(). ('0' means success, '1' means reboot required and other values are described on the MSDN pages linked to by the method names. Note: for EnableStatic() and SetGateways(), the error codes are returned as lists).
Full information on all the functionality of the Win32NetworkAdapterConfiguration class can also be found on MSDN.
Note: I tested this with Python 2.7, but as PyWIn32 and WMI modules are available for Python 3, I believe you should be able to get this working for Python 3 by removing the "u" from before the string literals.
A: You can use vbscript to change IP Address,
Dim strIPAddress, strSubnetMask,strGateway, intGatewayMetric, strDns1, strDns2, objWMIService, colItems, stradaptername, objFSO
Const ForReading = 1
Const ForAppending = 8
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set OutPutFile = objFSO.CreateTextFile("C:\ProgramData\test.txt" ,2 , True)
Set InterfaceName = objWMIService.ExecQuery ("Select * From Win32_NetworkAdapter Where NetConnectionStatus >= 0")
If objFSO.FileExists("C:\ProgramData\test.txt") Then
Set OutPutFile = objFSO.CreateTextFile("C:\ProgramData\test1.txt" ,2 , True)
End If
For Each objItem in InterfaceName
If objFSO.FileExists("C:\ProgramData\test.txt") Then
arrInterfaces = objItem.NetConnectionID
'wscript.echo "test: " &arrInterfaces
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\ProgramData\test.txt",8,true)
ObjFileToWrite.WriteLine(arrInterfaces)
objFileToWrite.Close
Set objFileToWrite = Nothing
End If
next
If objFSO.FileExists("C:\ProgramData\test.txt") Then
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\ProgramData\test.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
Set objFileToRead = Nothing
'wscript.echo "obtained" &strFileText
End If
Result = inputbox("Enter the AdapterName: " &vbCrLf &strFileText)
If Result = "" then
'wscript.echo "user selected cancel"
Else
strIPAddress=InputBox("Enter Static IP Adrress: ")
strSubnetMask =InputBox("Enter SubnetMask: " )
strGateway=InputBox("Enter Default Gateway: ")
strDns1=InputBox("Enter Preferred DNS: ")
strDns2=InputBox("Enter Alternate DNS: ")
Set objShell = WScript.CreateObject("Wscript.Shell")
objShell.CurrentDirectory = "C:\Windows\System32"
objShell.Run "netsh interface ip set address name=""" & Result & """ static " & strIPAddress & " " & strSubnetMask & " " & strGateway & " " & intGatewayMetric, 0, True
objShell.Run "netsh interface ip set dns name=" & Result & " static "& strDns1, 0, True
objShell.Run "netsh interface ip add dns name=" & Result & " addr="& strDns2, 0, True
Set objShell = Nothing: Set obj=Nothing
End If
WScript.Quit
A: Actually very simple to do (windows only) (uses preinstalled libraries only):
import os; os.system("ipconfig /renew")
A: import os
import subprocess
from subprocess import PIPE
def find_net_device():
cmd ='netsh interface ipv4 show interfaces'.split()
result = subprocess.run(cmd, universal_newlines = True,
stdout = subprocess.PIPE)
result = result.stdout
result = result.split('connected')[2]
result = result.split('\n')[0]
result = result.strip()
return result
def change_ip(ip):
adapter = find_net_device()
change =f'netsh interface ip set address {adapter} static {ip} 255.255.255.0'
change = change.split()
change_ip('165.22.64.68')
#again back to normal
def back2normal():
adapter = find_net_device()
normal = f'netsh interface ip set address {adapter} dhcp'
subprocess.run(normal,stdout=PIPE, universal_newlines=True)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How do I get the dimensions of the ImageRectangle in PictureBox? Background
I want to be able to get the drawn dimensions of a zoomed image inside the picturebox (I'll explain below).
The PictureBox.ImageRectangle property seems to be exactly what I'm looking for because it shows the height and width of the resized image, as well as it's relative top, left position inside the control.
The trouble is PictureBox.ImageRectangle is private and so I can't read the values without using reflection (which is obviously not ideal).
Actual Question
My question is, is there another way that I can easily get to these values without writing a method to calculate what the values "ought" to be? I can do that easily enough, but I feel I'd be reinventing the wheel.
Context:
I'm writing a simple image processing app in C# and one of the things it has to do is allow the user to draw a selection around a portion of the image (a lot like the Marquee tool in Photoshop).
I need to know the dimensions of the rendered image so I know where to set the bounds of my marquee tool and also to translate the values of the drawn rectangle to points on the scaled bitmap inside the control.
A: My answer look simple so maybe I'm missing something, but I think Control.DisplayRectangle suits your need.
EDIT
OK, missed the point; however see How to get the value of non- public members of picturebox?
A: if you want to access dimension of the image in picture box you can use
GraphicsUnit units = GraphicsUnit.Point;
RectangleF imgRectangleF = pictureBox1.Image.GetBounds(ref units);
Rectangle imgRectangle = Rectangle.Round(imgRectangleF);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Zend File Upload and Element Decorators I have the problem, that the following Zend Form throws an error.
The problem is the "file"-element and using setElementDecorators.
class Products_AddForm extends Zend_Form
{
function init() {
// other form elements...
$uploadElement = new Zend_Form_Element_File('Excel');
$uploadElement->setLabel('Excel');
$this->addElement($uploadElement);
$this->setElementDecorators(array(
'ViewHelper',
'Errors',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'th')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
));
}
}
This throws an error.
(Warning: Exception caught by form: No file decorator found... unable to render file element Stack Trace: #0 )
Adding $uploadElement->addDecorator('File'); at the end after the SetElementDecorators will work, but this will give me the file element twice!
Can anybody help, please?
TIA
Matt
A: The File element requires it's own decorator - Zend_Form_Decorator_File.
$this->setElementDecorators(array(
'File',
'Errors',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'th')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
));
[edit]
Have just noticed that you are also using other form elements.
After your original code, add:
$this->getElement('Excel')->setDecorators(
array(
'File',
'Errors',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'th')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
)
);
That way, ViewHelper is added to all other elements, and for your File element File is used instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Packing Rectangles Algorithm I need to solve the following problem:
I have multiple rectangles of sizes: width height, width/2 height/2, width/4 height/4 , width/8 height/8 ... etc
I need to pack these rectangles in a big rectangle of size x*width y*height such that no rectangles overlap, the rectangles are distributed randomly in the packing and any rectangle should at least touch another rectangle. I tried a fairly basic greedy algorithm but it fails.
Can you give me some suggestions on how to solve the problem?
Thanks!
EDIT: You can have more than one rectangle of each size
This is not homework. I'm trying to create an effect similar to the effect on ted.com
By random I mean that there might exist more than one packing of the rectangles that satisfies the constraints. The algorithm should not produce the same packing at each run.
A: This sounds like a rectangle packing problem. There is a link there to an algorithm. That code packs the rectangles as tightly as possible. You said you want the rectangles to be distributed randomly, which I'm guessing means not all rectangles of one size next to each other and all rectangles spread out to fill the big rectangle. Maybe the code at the link above would be a good starting point to get some ideas.
A: You can use a spatial index or a quadtree to subdivide the 2d-plane. The idea is to reduce the 2d problem to a 1d-problem. Once you got the spatial index (or space-filling-curve) and you can discretize the 2d into 1d you can use the 1d to search for similarity or to sort from low to high or the reverse for example by the length. If you got this order you can then compute the index back to a 2d represenation and to pack them in most efficent way in your container. There are many ways to make a spatial index. Some of the best but difficult to make is the hilbert curve. Another one is the z-curve or morton-curve. It's different from zizag-curve because it's subdivide the plane into 4 squares (not rectangles).
EDIT: Here is a link for an Jquery-Plugin: http://www.fbtools.com/jquery/treemap/
Here with world poplulation: http://www.fbtools.com/jquery/treemap/population.html
EDIT: http://people.csail.mit.edu/konak/papers/socg_2008-circular_partitions_with_applications_to_visualization_and_embeddings.html
EDIT: http://lip.sourceforge.net/ctreemap.html
A:
At each step you divide the surface of your new rectange by 4.
SUM(1/4n for n in [0,inf]) = 4/3**
So the best you can do is fit your rectangle in a rectangle of surface
4/3 (height*width)
(that's a lower bound)
@mloskot algorithm gives a possible solution that will be in a rectangle of surface 3/2*(height*width) : Here is an illustration:
I don't see how you can do better.
A: Assuming you have only one rectangle of each size, you can try to replicate the arrangement of paper sizes. Sort the rectangles by size from the biggest to the smallest, then
*
*Take first rectangle and place it at the corner of the target plane.
*Take next rectangle (assert it's smaller than the previous rectangle)
*Rotate about 90 degrees
*Place so
*
*its shorter size is adjacent to the longer size of the last bigger neighbour
*and its longer side is adjacent to the edge of the target plane or edge of neighbour of the same
size
*Repeat 2 - 4
I realise the description might be unclear, so here is picture presenting the solution - it should help to grasp it:
A: This is a lot like MIP-mapping
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Should unit tests use different managed object context to the main app? All the managed object context code is located in my app delegate. Should I have similar code in my unit test classes?
A: For unit tests, I create an in memory managed object context specifically for the test(s). That way it can be destroyed and recreated for each test in the setUp code and because it's in memory, saves are fast.
** Edit **
The MOC stuff is encapsulated in a class called ModelLoader. I call it from -setUp of my test like this:
- (void)setUp
{
[super setUp];
loader = [[ModelLoader alloc] initWithName: @"MyDocument"];
NSError* error = nil;
if (![[loader context] save: &error])
{
@throw [NSException exceptionWithName: @"MOCSave"
reason: [error localizedDescription]
userInfo: nil];
}
}
The name is the name of the data model without the .mom extension. The save and exception throw just rovides a sanity check that makes sure it's all initilised property. By the way, this is GC code. For non GC, you need to release the loader in -tearDown
Relevant code from ModelLoader:
-(id) init
{
return [self initWithName: @"MyDocument"];
}
-(id) initWithName: (NSString*) modelName
{
self = [super init];
if (self != nil)
{
NSBundle* theBundle = [self bundle];
NSURL* modelURL = [theBundle URLForResource: modelName
withExtension: MOM_EXTENSION];
if (modelURL == nil)
{
// log error
}
else
{
model = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL];
if (model == nil)
{
// log error
}
}
}
return self;
}
// Create or return the context
-(NSManagedObjectContext*) context
{
if (context == nil)
{
context = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator* coordinator
= [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self model]];
[context setPersistentStoreCoordinator: coordinator];
NSError* error = nil;
NSPersistentStore* newStore
= [coordinator addPersistentStoreWithType: NSInMemoryStoreType
configuration: nil
URL: nil
options: nil
error: &error];
if (newStore == nil)
{
NSLog(@"Failed to create store, reason %@", error);
context = nil;
}
}
return context;
}
A: Create a subclass of the code where you create the NSPersistentStoreCoordinator and override it with a memory store:
- (NSPersistentStoreCoordinator*) coordinator {
if (!_coordinator) {
NSError *error = nil;
_coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self model]];
[_coordinator addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil URL:nil options:nil error:&error];
}
return _coordinator;
}
Or change the path to the store in your persistent manager:
NSPersistentStore *persistentStore = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
Or use the same class, but the downside is that testing requires a known initial state, meaning you want to reset the database before testing, erasing the data you created while using your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to draw a horizontal line at the SOUTH position of the BorderLayout of a Container? I have a Container whose Layout is BorderLayout. I want to draw a horizontal line at the SOUTH position because this Container is drawn repeatedly so I want to delimit each by the horizontal line.
Here is the code:
tList = new List(tModel);
tList.setListCellRenderer(new CTable(listclient));
public class CTable extends Container implements ListCellRenderer {
private Label pic = new Label("");
private Container cnt;
private Label name = new Label("");
private Label credit = new Label("");
private ligneHorizontal ligne;
private Font fontLibelle = (MenuPrincipalForm.r).getFont("FontTextFieldBold");
private Label focus = new Label("");
public CTable(Vector valeur)
{
setLayout(new BorderLayout());
addComponent(BorderLayout.WEST, pic);
cnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
name.getStyle().setBgTransparency(0);
name.getStyle().setFont(fontLibelle);
credit.getStyle().setBgTransparency(0);
cnt.addComponent(name);
cnt.addComponent(credit);
ligne = new ligneHorizontal(100);
cnt.addComponent(ligne);
addComponent(BorderLayout.CENTER, cnt);
focus.getStyle().setBgTransparency(100);
}
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected)
{
if ("-".equalsIgnoreCase(String.valueOf(value)))
{
name.setText(" - ");
credit.setText("Encours : - Impayés : -");
pic.setIcon(null);
}
else
{
if (index%2 == 0)
this.setUIID("evenRowsCell");
else
this.setUIID("oddRowsCell");
name.setText("123456789012 - Rasolofomanana Marc");
credit.setText("Crédits : 15.000 (Ar) Impayés : 10.000 (Ar)");
pic.setIcon(null);
}
return this;
}
public Component getListFocusComponent(List list)
{
return focus;
}
}
public class ligneHorizontal extends Label {
public ligneHorizontal(int l)
{
String t = "";
do
{
t.concat(new String("-"));
}
while(t.length()<l);
this.setText(t);
this.setPreferredH(5);
this.getStyle().setBgColor(0);
}
}
And also I want to know how to coloriate even rows and odd rows of the List because I tried but the color is not get until I click on the cell.
A: Ok , I found the solution : I derived BackgroundPainter where in the public void paint(Graphics g,Rectangle rect) method I draw the line ( g.drawLine(rect.getX(), rect.getY()+h-1, rect.getX()+w, rect.getY()+h-1); ).
So when I want to draw a line in the container then I write myContainer.getStyle().setBgPainter(new derivedClassName(myContainer));
A: add Label with preferred height 5, with black bg color between containers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Prolog programming - path way to a solution I am studying prolog at university and facing some problems. What I already found out is just solution to a problem. However, I'm more interested in the way to think, i.e. how to get such solution.
Can somebody give me an advise on this field. I would really appreciate your help.
I give an example I am coping with and also, found a solution on stackoverflow here, but what I looking for is how does he do that, how does he find the answer :)
Write a predicate flatten(List,Flat) that flatten a list, e.g. flatten([a,b,[c,d],[[1,2]],foo],X) will give X=[a,b,c,d,1,2,foo].
This is the answer I found on stackoverflow:
flatten(List, Flattened):-
flatten(List, [], Flattened).
flatten([], Flattened, Flattened).
flatten([Item|Tail], L, Flattened):-
flatten(Item, L1, Flattened),
flatten(Tail, L, L1).
flatten(Item, Flattened, [Item|Flattened]):-
\+ is_list(Item).
this answer belongs to user gusbro and asked by user Parhs, I have try to find a way to contact user gusbro to ask him how he can derive such answer but I cannot.
Thank you very much.
A: Well, all I can say is that the way to solve a problem depends largely on the problem itself. There is a set of problems which are amenable to solve using recursion, where Prolog is well suited to solve them.
In this kind of problems, one can derive a solution to a larger problem by dividing it in two or more case classes.
In one class we have the "base cases", where we provide a solution to the problem when the input cannot be further divided into smaller cases.
The other class is the "recursive cases", where we split the input into parts, solve them separately, and then "join" the results to give a solution to this larger input.
In the example for flatten/2 we want to take as input a list of items where each item may also be a list, and the result shall be a list containing all the items from the input. Therefore we split the problem in its cases.
We will use an auxiliary argument to hold the intermediate flattened list, and thats the reason why we implement flatten/3.
Our flatten/2 predicate will therefore just call flatten/3 using an empty list as a starting intermediate flattened list:
flatten(List, Flattened):-
flatten(List, [], Flattened).
Now for the flatten/3 predicate, we have two base cases. The first one deals with an empty list. Note that we cannot further divide the problem when the input is an empty list. In this case we just take the intermediate flattened list as our result.
flatten([], Flattened, Flattened).
We now take the recursive step. This involves taking the input list and dividing the problem in two steps. The first step is to flatten the first item of this input list. The second step will be to recursively flatten the rest of it:
flatten([Item|Tail], L, Flattened):-
flatten(Item, L1, Flattened),
flatten(Tail, L, L1).
Ok, so the call to flatten(Item, L1, Flattened) flattens the first item but passes as intermediate list an unbound variable L1. This is just a trickery so that at the return of the predicate, the variable L1 still remain unbounded and Flattened will be of the form [...|L1] where ... are the flattened items of Item.
The next step, which calls flatten(Tail, L, L1) flattens the rest of the input list and the result is bounded with L1.
Our last clause is really another base case, the one that deals with single items (which are not lists). Therefore we have:
flatten(Item, Flattened, [Item|Flattened]):-
\+ is_list(Item).
which checks whether item is a list and when it is not a list it binds the result as a list with head=Item and as tail the intermediate flattened list.
A: First, I'll show you my approach to the problem, then I've got some resources for learning to think recursively.
Here's my solution to the problem "flatten a list of lists (of lists ...)". I've annotated it to show how I got there:
*
*First, let's define the public interface to our solution. We define flatten/2. It's body consists of a call to the internal implementation flatten/3, which takes an accumulator, seeded as an empty list.
flatten ( X , R ) :-
flatten ( X , [] , R ) ,
.
That was easy.
*The internal predicate flatten/3 is a little more complex, but not very.
*
*First, we have the boundary condition: the empty list. That marks the end of what we need to do, so we unify the accumulator with the result:
flatten( [] , X , X ).
*The next (and only) other case is a non-empty list. For this, we examine the head of the list. Our rule here is that it needs to flattened and appended to the result. A good rule of programming is to write descriptive code, and Prolog is itself a descriptive, rather than procedural, language: one describes the solution to the problem and lets the inference engine sort things out.
So...let's describe what needs to happen now, and punt on the mechanics of flattening the head of the list:
flatten( [X|Xs] , T , Y ) :-
flatten_head(X,X1) ,
append( T,X1,T1) ,
flatten( Xs , T1 , Y )
.
That, too, was easy.
That's the essence of the entire solution, right there. We've broken our problem into 3 pieces:
*
*a special case (the empty list)
*the normal case (a non-empty list)
*what to do with each element in the list (not yet defined).
Let's move on to the implementation of how to flatten a single list element. That's easy, too. We've got two cases, here: the list item might be a list, or it might be something else.
*
*First, the list element might be an unbound variable. We don't want untowards behaviour, like unbounded recursion happening, so let's take care of that straightaway, by disallowing unbound terms (for now). If the element is bound, we try to flatten it by invoking our public interface, flatten\2 again (oooooooh...more recursion!)
This accomplishes two things
*
*First, it tells us whether we've got a list or not: flatten/2 fails if handed something other than a list.
*Second, when it succeeds, the job of flatten_head/2 is done.
Here's the code:
flatten-head( X , Y ) :-
nonvar(X) ,
flatten( X , Y )
.
*Finally, the last case we have to consider is the case of list elements that aren't lists (unbound vars, atoms or some other prolog term). These are already "flat"...all we need to do is wrap them as a single element list so that the caller (flatten\3) gets consistent semantics for its "return value":
flatten-head( X , [X] ).
Here's the complete code:
flatten ( X , R ) :-
flatten ( X , [] , R )
.
flatten( [] , X , X ) .
flatten( [X|Xs] , T , Y ) :-
flatten_head(X,X1) ,
append( T,X1,T1) ,
flatten( Xs , T1 , Y )
.
flatten-head( X , Y ) :-
nonvar(X) ,
flatten( X , Y )
.
flatten-head( X , [X] ) .
Each individual step is simple. It's identifying the pieces and weaving them together that's difficult (though sometimes, figuring out how to stop the recursion can be less than obvious).
Some Learning Resources
To understand recursion, you must first understand recursion—anonymous
Eric Roberts' Thinking Recursively (1986) is probably the best (only?) book specifically on developing a recursive point-of-view WRT developing software. There is an updated version Thinking Recursively With Java, 20th Anniversary Edition (2006), though I've not seen it.
Both books, of course, are available from the Usual Places: Powell's, Amazon, etc.
*
*http://www.amazon.com/Thinking-Recursively-Eric-S-Roberts/dp/0471816523
*http://www.amazon.com/Thinking-Recursively-Java-Eric-Roberts/dp/0471701467
*http://www.powells.com/biblio/61-9780471816522-2
*http://www.powells.com/biblio/72-9780471701460-0
You might also want to read Douglas Hofstadtler's classic Gödel, Escher, Bach: An Eternal Golden Braid Some consider it to be the best book ever written. YMMV.
Also available from the Usual Suspects:
*
*http://www.powells.com/biblio/62-9780140289206-1
*http://www.amazon.com/Godel-Escher-Bach-Eternal-Golden/dp/0465026567
A new book, though not directly about recursive theory, that might be useful, though I've not seen it (it's gotten good reviews) is Michael Corballis' The Recursive Mind:
The Origins of Human Language, Thought, and Civilization
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .NET Socket Cannot Detect Disconnect Event under Windows 7 I'm using System.Nets.Sockets.Socket to play the client side to connect our server. Everything works fine under Windows XP. But recently, our client report that the UI cannot alarm when it disconnect from the server side (by un-plug the network cable) under Windows 7. I've debug this situation, and found this case only happen in Windows7, but under Windows XP, it does work.
Then my question is, why this socket disconnect event hasn't been raised up under Windows 7 but XP do? Is there any way to fix this problem?
Thank you.
A: ehh, what event?
The only way to be sure that a socket is connected is by sending or receiving.
More info:
http://nitoprograms.blogspot.com/2009/05/detection-of-half-open-dropped.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Screenshot of Control is white My question is related to this one: How to get a screen capture of a .Net WinForms control programmatically?
I want to take a screenshot of a System.Windows.Forms.Control in C#. I'm using the DrawToBitmap method suggested in the question linked above and that works most of the time. However there are a few problems.
Problem 1:
I have two tabpages, let's call them A and B. The Control I want to take a screenshot of is in tabpage B. I want to take the screenshot when a button in tabpage A is pressed. This works most of the time, except when tabpage B hasn't been accessed yet: then the screenshot is just white. If I first access tabpage B, then go back to tabpage A and click the button to take the screenshot then it works fine. I'm guessing this is because of some loading or building of the control in the tab that hasn't been done yet, but I'm not sure what exactly (or it could be something else entirely). I've been trying to force that loading or building using ResumeLayout, PerformLayout, Show, Update, Invalidate but that doesn't work.
EDIT: Managed to solve this by using DrawToBitmap on the containing tabpage control instead of the Control itself and doing a Show on that tabpage.
Problem 2:
When I take a screenshot of a certain custom Control (a subclass of UserControl) there is a small rectangular white area in the screenshot (where there shouldn't be one obviously). The rectangular area isn't on one particular part of the control like a button or textbox so I'm not sure what's causing this. On other custom Controls (also subclasses of UserControl) it works fine, so that couldn't be the problem itself.
EDIT: Solved it, there was an empty control there that was being drawn on top of it. Setting Visible to false for that control solved it.
A: You can do with this code, the rest of the work and finding the correct coordinates is for the reader to do the homework.
int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
bmpScreenShot.Save("test.jpg", ImageFormat.Jpeg);
A: For problem 1: If "If I first access tabpage B, then go back to tabpage A and click the button to take the screenshot then it works fine" then add in formloadevent imitating of that actions:
tabControl.SelectedIndex = IndexOfTabB;
tabControl.SelectedIndex = IndexOfTabA;
That is trick but it will work.
For problem 2: Can you compare sizes of your control and screenshot of It and give results to us? If Control.Width is not equal wirdth of bitmap screen then It is a real problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Special character in Search in PostgreSQL I am trying to retrieve the contact names based on the keyed search string. It performs good for the English alphabets and behaves strangely for special chars such as _,/,\,%
My query in the function is similar to
SELECT contact_name FROM contacts WHERE LOWER(contact_name) LIKE LOWER('_McDonald%') ORDER BY LOWER(contact_name) ASC LIMIT 1;
It looks like, during searching, it retrieves all the contact names instead of the desired. The similar bizarre happens for the above mentioned special chars. I need to support these. How do I educate postgres to consider these chars? Please guide me.
Thanks and Regards,
Siva.
A: I don't know what PostgreSQL version you are using, but make sure you escape any special characters (_, %, \, ...) if you want to match them literally as it is described in the docs.
Assuming you want to search for any contact names that start with _McDonald:
SELECT contact_name FROM contacts
WHERE LOWER(contact_name) LIKE LOWER(E'\\_McDonald%')
ORDER BY LOWER(contact_name) ASC LIMIT 1;
A: Just to complete the picture:
You can also use the ESCAPE clause to specify the character for escaping the wildcards. This is useful if you'd like to include e.g. a \ in your search string.
SELECT contact_name
FROM contacts
WHERE LOWER(contact_name) LIKE LOWER('@_McDonald%') ESCAPE '@'
ORDER BY LOWER(contact_name) ASC
LIMIT 1;
Btw: I would recommend to turn on the configuration option standard_conforming_strings to avoid confusion (Haes' answer avoids this problem by using the E' syntax).
Since 9.1 this is the default mode anyway.
A: You can use a prepended E in the where clause before the string using double backslashes to escape the following character:
WHERE LOWER(contact_name) LIKE LOWER(E'\\_McDonald%')
OR you may do the appended escape clause as below:
WHERE LOWER(contact_name) LIKE LOWER('@_McDonald%') ESCAPE '@'
Note the former method will work with the clauses LIKE, SIMILAR TO and NOT SIMILAR TO, but the above method will work as well with more powerful POSIX regular expressions like ~, ~,
!~, !~
In the docs you can also see some functions that may be of use as well such as regexp_replace where you could try this to escape special characters in the contact_name field:
SELECT
regexp_replace(contact_name, '([!$()*+.:<=>?[\\\]^{|}-])', '\\\1', 'g')
FROM
contacts
WHERE
LOWER(contact_name) LIKE LOWER('_McDonald%')
ORDER BY
LOWER(contact_name) ASC LIMIT 1;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: fb:login-button ignores scope? I changed my Facebook App to OAuth 2.0. Now the Login window ignores the user permissions.
The new login button code is as follows:
<fb:login-button show-faces="true" width="400" max-rows="2" scope="read_stream, publish_stream, email"></fb:login-button>
when I use perms instead of scope it works.
I have oauth:true in FB.init(). In the app settings oauth2 is active.
A: (Everything I did and learned was in an effort to be able to publish to a Facebook Timeline from a 3rd party website. I don't know your motive/goal. It might not be the same as mine.)
I am using JS SDK with javascript commands, not xfbml markup.
I am using the beta version of the JS SDK: set the host to connect.beta.facebook.net instead of connect.facebook.net
I have oauth:true in my FB.init() function.
I have app settings for OAuth 2.0 enabled at developers.facebook.com.
This is my FB.login():
FB.login(
function(response) {
if (response.authResponse) {
// handle a successful login
}
},
{
scope: 'publish_stream' // I need this for publishing to Timeline
}
);
One thing I did to debug this was to check the value of FB._oath. If it is undefined, you have a problem. If it is true, you can proceed to the next challenge.
So after lots of trial and error, I finally got FB._auth===true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which version of libstdc++.so.6 to use? I'm using a third party shared library (libsw_api.so) on Solaris, which when I try to load, produces the following error:
fatal: relocation error: file libsw_api.so:
symbol _ZNKSt9bad_alloc4whatEv: referenced symbol not found
The program exited with error code 1
When I run ldd on libsw_api.so, all references seem to be fulfilled, specifically the C++ standard library which points to libstdc++.so.6.0.3:
glispa02(fostopr)$ ldd libsw_api.so
...
libstdc++.so.6 => /usr/sfw/lib/libstdc++.so.6
...
glispa02(fostopr)$ ls -l /usr/sfw/lib/libstdc++.so.6
lrwxrwxrwx 1 root root 18 Jun 21 2010 /usr/sfw/lib/libstdc++.so.6 -> libstdc++.so.6.0.3
However that library does not export _ZNKSt9bad_alloc4whatEv,
glispa02(fostopr)$ nm /usr/sfw/lib/libstdc++.so.6 | grep bad_alloc
[7592] | 752340| 64|FUNC |GLOB |0 |2653 |_ZNSt9bad_allocD0Ev
[7324] | 752284| 56|FUNC |GLOB |0 |2652 |_ZNSt9bad_allocD1Ev
[8077] | 752228| 56|FUNC |GLOB |0 |2651 |_ZNSt9bad_allocD2Ev
[7519] | 356736| 76|FUNC |GLOB |0 |473 |_ZSt17__throw_bad_allocv
[7341] | 983588| 12|OBJT |WEAK |0 |3842 |_ZTISt9bad_alloc
[6569] | 777008| 13|OBJT |WEAK |0 |3317 |_ZTSSt9bad_alloc
[7299] | 983568| 20|OBJT |WEAK |0 |3841 |_ZTVSt9bad_alloc
What could be the problem? Wrong version? I'm not really good with C++ on Unix so I'ld appreciate any help.
Could this SPARC32PLUS vs. SPARC mismatch be the cause of the problem?
glispa02(fostopr)$ file libsw_api.so
libsw_api.so: ELF 32-bit MSB dynamic lib SPARC32PLUS Version 1, V8+ Required, dynamically linked, not stripped
glispa02(fostopr)$ file /usr/sfw/lib/libstdc++.so.6.0.3
/usr/sfw/lib/libstdc++.so.6.0.3: ELF 32-bit MSB dynamic lib SPARC Version 1, dynamically linked, not stripped, no debugging information available
My system:
glispa02(fostopr)$ cat /etc/release
Solaris 10 10/09 s10s_u8wos_08a SPARC
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved.
Use is subject to license terms.
Assembled 16 September 2009
glispa02(fostopr)$ uname -a
SunOS glispa02 5.10 Generic_141444-09 sun4u sparc SUNW,SPARC-Enterprise
A: Hi I'm also upgrading these files, I noticed that I should be using the libstdc++.so.6.0.9 file that comes with the distribution rather than the one in /usr/sfw/lib/
A: If you use pvs on the libstdc++.so.6 file, it will give you a bunch of entries matching: GLIBCXX, if you don't have an entry matching GLIBCXX_3.4.9, then the symbol bad_alloc::what is not in that library i.e. the library is older than the dependent object libsw_api.so
If this is the case then you probably need a newer version of libstdc++ - it would come with a newer version of g++
A: I encounter the same issue.
The cause is we export the wrong LD_LIBRARY_PATH
So that our shared library link to the original gcc's library (3.3) instead of our compiler (gcc 4.4).
Fix the linker problem should solve the issue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Symfony 2 and facebook login error I am using fos_facebook bundle to integrate facebook login system with my web app. I am getting following error.
"The Facebook user could not be retrieved from the session"
Has anyone come across this problem? Could anyone successfully integrate facebook with symfony? Please provide your configuration and userInterface class.
A: You have to give the browser a little time to handle the Facebook cookie.
<script>
function goLogIn(){
window.location = "{{ path('_security_check') }}";
}
function onFbInit() {
if (typeof(FB) != 'undefined' && FB != null ) {
FB.Event.subscribe('auth.statusChange', function(response) {
setTimeout(goLogIn, 500);
});
}
}
</script>
this is a snip from the FOSFacebookBundle documentation. Where the proces is described :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ProcessBuilder to execute custom executable Okay, I have tried a dozen different ways and no success. I want to execute a custom exe and grab the output. It runs fine from the command prompt. I get the "dir" to work fine, but not custom.exe. Here is the code:
List<String> command = new ArrayList<String>();
command.add("cmd"); // Even removed these two lines
command.add("/c"); // aka hail mary coding.
//command.add("dir");
command.add("custom.exe"); // even tried "c://custom.exe"
String line;
Process p = new ProcessBuilder(command).start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
I get no output at all. If I place it in a batch file, i get output. I have a feeling it has something to do with %PATH%. Back at it...
EDIT--> So turns out that the output from this custom exe goes to error, so to see what is happening i have the code:
List<String> command = new ArrayList<String>();
command.add(System.getenv("ProgramFiles(x86)") + "\\mydir\\custom.exe";
String line;
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
And it works like a hot damn. :)
A: You don't need the lines
command.add("cmd");
command.add("/c");
That would only be required for a batch file. I would rather specify the full path to the executable.
Maybe the output is on stderr? Try replacing p.getInputStream() with p.getErrorStream().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generic Performance Testing Framework For .NET I have a client/server application written in C#/.NET 3.5 that I want to do a bit of performance testing on. I've been looking for a generic framework to help me but not had much luck. I would like something that can manage a set of clients and perform random actions for them based on some settings. I would also then like to record some data relating to this to help me work outsome rough thresholds for my system, e.g. I can support n users performing x actions per second.
I would write code specific to my application to perform tasks such as:
*
*Login/logout a client.
*Send messages to the server to perform various actions.
*Record acknowledgements and other messages from the server.
*Measure statistics specific to the system.
I'm hoping the framework will then be able to take a set of parameters to describe a testing scenario such as:
*
*Number of clients logged in at a given time.
*Perform a given number of actions per second for each client.
It would then run the scenario, manage and track all of the users and actions and collate all of the data. (This is the boring bit I'm trying to avoid coding myself...) Ideally it would have some general measurements built in, e.g. time between sending a message and receiving a response, but I could code them myself if not.
I don't want to do any profiling of my code; I can always attach a profiler whilst running these tests later on. Instead I want to make some rough conclusions about my system, i.e. how many users can I throw at it before it breaks. (If there is a better term for this than 'performance testing' please let me know... Stress testing maybe?)
I realise I'm not giving very many specifics about the system here. It strikes me as a fairly general situation - I'm sure there are lots of client/server systems out there that people need to do similar tests on. I've found lots of web based frameworks to do similar things but they seem to be pretty web ingrained and don't lend themselves easily to non-HTTP based systems.
Anyone know of anything that might help? My searching hasn't found anything yet. I should point out that I'm stuck with Visual Studio 2008 Professional for the foressable future so if 2010 can do this it's out of bounds for me. I guess it doesn't have to be a .NET framework provided I can still plugin my .NET code fairly easily.
EDIT To be clear my application isn't a website, it's a Windows Forms client application that connects via a custom protocol to a .NET service. I can write code to perform the relevant client actions, I just need a framework to put it in.
A: The keyword you are looking for is "Distributed testing".
Smart Bear have a product called TestComplete which supports distributed testing. I don't think it can run multiple instances of your client on a single machine though (maybe it can, but I guess it's not a good idea any way since it would impact the performance results).
They also have an open source project called LoadUI, it is built to integrate with SoapUI, however you might be able to hook it up to your own client-test tool. I have no idea how much effort that would cost.
These are the tools I know of, but there are many more distributed testing tools out there. While most are indeed for web-bases testing, they often are extensible enough to simply kick off a different (GUI-based) testing framework (my favorite is QAliber) which runs the tests on your client app.
A: To my knowledge, such a framework does not currently exist (and it is likely it won't exist because everyones scenarios are so different). Because "Performance" means different things to different people and different projects, you will usually have to roll your own. Thankfully, with the advent of .NET4 and the TPL this has become easier than ever before.
There are three aspects a Performance test needs to cover:
*
*Define "Load"
*Measure "Performance"
*Evaluate the Results
As you can imagine, both of these are totally lax definitions. Load could be measured in Requests per Second, Logged In Users etc... Performance could be measured in Response Time, Memory Usage... you get the picture.
So your first step is to define a "unit load", that you can easily scale up. For example you could create a ClientUnitLoad class, that simulates a client and periodically performs actions against your service. The TPL makes it easy to scale your ClientUnitLoad (except you are bound by hardware constraints of course).
The next step is to measure Performance. How you measure heavily depends on the metric you want to collect: Simple Stopwatching is fine 90% of the cases but can only measure time. Building a custom tracing and metrics collection infrastructure is definitely worth it, as you will also need it in production to verify your system performs as expected in the real world.
The last step is to evaluate your Metrics. The largest issue with Performance Tests is that: a) they are slow, and b) unreliable. Theres no way around that. In general, you need large sample sizes (repeated test runs) and some sort of statistical analysis on your metrics to ignore outliers. The processed results should then be compared to a configurable performance baseline.
Depending on the desired level of sophistication, that performance baseline may have simple acceptance criteria (such as: Repsonse Time under 100ms) or advanced, specific criteria (such as: Repsonse Time does not decrease by more than 10% when the amount of logged in users is 10 vs. 1).
A: I've not tried it myself but this may be suitable for your needs.
https://browsermob.com/performance-testing
A: Can't really say if there is a testing framework for such a specific purpose, but maybe you could use a simple console application (since the main idea is to test server performance)? You could make multiple calls to the server in different threads and use, for example, Stopwatch class to measure response times.
Or, you could try overloading the service by just increasing the number of calls (likely the service will slow down before threadpool runs out of threads?).
A: Kindly check at the following link.This may help you.
http://msdn.microsoft.com/en-us/library/aa337591.aspx
I guess you will get the feature even in VS2008 but for ultimate edition.
A: http://blog.maartenballiauw.be/post/2008/02/code-performance-analysis-in-visual-studio-2008.aspx
Available in Developer and Team-based Visual Studio 2008. I think the feature has been improved in Visual Studio 2010 though.
I should clarify - this doesn't provide support for all the test cases you want to run. You would have to write that logic yourself in a separate project, set that as the startup project, then run the Performance Analysis.
A: I've done some performance tests a while ago in a client/server application using Microsoft Visual Studio Load Test
When you add unit tests to a load test, you exercise the performance
of non-Web based server components
You have to code your load generators as "Visual Studio Unit Tests", so that later you can add them into the Load Test project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Detecting swipe gestures on UITableViewCell inside UIScrollView I am hoping someone will be able to help me with a problem that is doing my head in at the moment!
Given the following view hierarchy
I want to be able to detect swipe gestures on my custom UITableViewCell.
I have subclassed the UIScrollView and have a hitTest:withEvent: method that checks whether I am touching the tableview cell (or its content) or not, in which case I set the following scroll view properties:
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView* result = [super hitTest:point withEvent:event];
if ([result.superview isKindOfClass:[UITableViewCell class]] || [result.superview tag] == SUBVIEW_TAG)
{
self.canCancelContentTouches = NO;
self.delaysContentTouches = YES;
} else {
self.canCancelContentTouches = YES;
self.delaysContentTouches = NO;
}
return result;
}
I have also implemented:
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
if (view.tag == SUBVIEW_TAG || [[view superview] isKindOfClass:[UITableViewCell class]])
return NO;
return YES;
}
And am returning NO in case the view being touched is the table view cell.
These methods are all getting called and performing their actions as expected, but I am still unable to stop the UIScrollView from "hogging" the swipe gesture.
The interesting thing is that if I include the UIView that contains the tableview and cell on both of the methods above (the one with SUBVIEW_TAG) it works perfectly so I am guessing it must be something to do with the fact that UITableView inherits from UIScrollView.
My main goal is to be able to swipe on the cell to reveal more options for the cell. A horizontal swipe anywhere else on that view would be captured by the scroll view and shift the content horizontally as per its normal behaviour.
Any ideas would be very much appreciated!
Thanks!
Rog
A: I had a similar problem with a swipe detect for a component inside a scrollview and I was able to resolve it with
[scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipeGesture]
Where scrollView is the scroll view object that acts like container and swipeGesture is the component swipe gesture object inside scrollview.
So, you can define a swipe for the cell object like this (for right swipe in the example, custom it as you want)
UISwipeGestureRecognizer* rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(yourMethod)];
[rightSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
[cell addGestureRecognizer:rightSwipeRecognizer];
and then do
[scrollView.panGestureRecognizer requireGestureRecognizerToFail:rightSwipeRecognizer]
The documentation of requireGestureRecognizerToFail says:
This method creates a relationship with another gesture recognizer
that delays the receiver’s transition out of
UIGestureRecognizerStatePossible. The state that the receiver
transitions to depends on what happens with otherGestureRecognizer:
If otherGestureRecognizer transitions to
UIGestureRecognizerStateFailed, the receiver transitions to its normal
next state.
if otherGestureRecognizer transitions to
UIGestureRecognizerStateRecognized or UIGestureRecognizerStateBegan,
the receiver transitions to UIGestureRecognizerStateFailed.
An example where this method might be called is when you want a
single-tap gesture require that a double-tap gesture fail.
Availability Available in iOS 3.2 and later.
Hope helps!
A: The solution is pretty simple. All you need to do is add UIScrollView inside you UITableViewCell. It will prevent "hogging" effect during swipe gesture.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Extras based REORDER_TO_FRONT In an app I have very reused Activity, that shows a list of stuff happening on a specific day. The day is specified using Intent Extras.
My problem is, that if the user starts at day=1, then chooses day=2 and then day=1, from the menu, then I would like the back button to go to day=2 and then home. That is, I want to do REORDER_TO_FRONT, but not just based on the name of the activity, but also its extras.
There doesn't seam to be any intent flags suitable for this purpose. I've considered implementing my own 'sub activity stack' using onNewIntent, but it probably wouldn't work very well.
Have you tackled similar problems in your apps? Is there perhaps a way to programmatically access the activity stack, and choose which one is suitable to return to?
A: Manage your own Activity stack! If I'm not mistaken, you use the same Activity to display each day. Make it single top (FLAG_ACTIVITY_SINGLE_TOP). In the launching intent, pass on the current stack, in your example "121".
Respond to the back button event by launching your Activity with a smaller stack: "12" - or if stack is already "", then just let the Activity handle Back event. Then as you mentioned, use the onNewIntent function to update your Activity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Matlab- zero padding(2) Anyone can help? Don't know why got error? ???
Assignment has more non-singleton rhs dimensions than non-singleton
subscripts Error in ==> create_padded_image at 17
padded_image(padding+1:padding+image_size(1),
padding+1:padding+image_size(2)) = image; Error in ==>
create_padded_image at 9 padded_image = create_padded_image(image)
function padded_image = create_padded_image(image, padding)
if nargin < 2
% if no padding passed - define it.
padding = 5;
end
if nargin < 1
% let's create an image if none is given
image = imread('GreyScale.bmp');
padded_image = create_padded_image(image)
end
% what are the image dimensions?
image_size = size(image);
% allocate zero array of new padded image
padded_image = zeros(2*padding + image_size(1), 2*padding + image_size(2));
% write image into the center of padded image
padded_image(padding+1:padding+image_size(1), padding+1:padding+image_size(2)) = image;
end
A: Try
image_size = size(image);
padded_image = zeros(2*padding + image_size(1), 2*padding + image_size(2), size(image,3), class(image));
padded_image(padding+1:padding+image_size(1), padding+1:padding+image_size(2), :) = image;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to express queries in Tuple Relational Calculus? Problem:
Consider a relation of scheme Building(Street, Number, No.Apartments, Color, Age).
TRC: find the oldest building in Downing Street.
The associated SQL statement would be:
SELECT MAX(Age) AS ‘Oldest building’, Street FROM Building WHERE Street = ‘Downing Street’;
My answer using TRC: (B stands for Building relation)
{V.*|V(B) | V.BAge >=Age ^ V.Bstreet = ‘Downing Street’}
V.* (it returns evry single tuple of Building)
V(B) (it maps variables V to Building’s tuples)
V.BAge >=Age ^ V.Bstreet = ‘Downing Street’(here I set the condition…maybe..)
A: If this is still relevant: the hint would be to realize that the oldest building is the one such that no other building is older than it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: android camera stretched in landscape mode The app I'm writing requires camera functionality.
So to learn about how to operate the camera, I followed this script:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html
I have put the activity in my manifest, set the screen orientation for it on landscape mode.
The problem I'm having is, when the camera is held sideways (so I hold my Galaxy Tab P1000 in landscape position) the view is stretched out.
To be more specific about my script, I used an exact copy of code that Google made. It can be found in the android-sdk\samples\android-8\ApiDemos\src\com\example\android\apis\graphics\
The file itself is called CameraPreview.
I really have no clue why the screen looks so stretched. Of course, the format is weird and not square, but still, when using the default camera app installed on the device, it doesn't deform at all. This camera deforms the image when I hold it sideways and move the camera even a little.
What I did was: I held my galaxy tab to take a picture of an object (laptop in this case) then took a picture with my phone of my Galaxy. On the Galaxy I have the camera screen open in the app i'm making. This counts for both images. One I hold sideways and one I hold in portrait view. The pics are a bit unclear but you can see that in the landscape picture, the camera has become massively wide.
A: public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
camera = Camera.open();
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(holder);
Camera.Parameters parameters = camera.getParameters();
List<Size> sizes = parameters.getSupportedPictureSizes();
parameters.setPictureSize(sizes.get(0).width, sizes.get(0).height); // mac dinh solution 0
parameters.set("orientation","portrait");
//parameters.setPreviewSize(viewWidth, viewHeight);
List<Size> size = parameters.getSupportedPreviewSizes();
parameters.setPreviewSize(size.get(0).width, size.get(0).height);
camera.setParameters(parameters);
camera.startPreview();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need only getSupportedPreviewSizes() and save it to a List:
List<Size> size = parameters.getSupportedPreviewSizes();
parameters.setPreviewSize(size.get(0).width, size.get(0).height);
camera.setParameters(parameters);
camera.startPreview();
I hope this helps you.
A: I faced the same problem yesterday. After a researching "Camera" sources I found a reason for camera preview being stretched.
The reason is: SurfaceView aspect ratio (width/height) MUST be same as Camera.Size aspect ratio used in preview parameters. And if aspect ratio is not the same, you've got stretched image.
So, the fastest workaround is to set SurfaceView to size like 320px x 240px - smallest supported size from Parameters.getSupportedPreviewSizes().
Also, you can look at Camera standard application sources, it uses the custom layout for controlling the SurfaceView size (see PreviewFrameLayout.java, onMeasure() function).
Use
git clone https://android.googlesource.com/platform/packages/apps/Camera.git
to get Camera sources.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: LIBRTMP Delphi: mapping of the DLL When I call the function RTMP_SetupURL from Delphi the URL is not updated in the record RTMP, I tanslated the DLL function like that:
int RTMP_SetupURL(RTMP *r, char *url);
function RTMP_SetupURL(var r:RTMP; url:PAnsichar):integer;
and the record AVal is declared like that:
AVal = record
av_val: PansiChar;
av_len: integer;
end;
Before to set the URL there a init problem, my record (RTMP) is not initialized correctly, below my record:
PChar = PAnsiChar;
uint32_t = LongWord;
uint8_t = Byte;
int8_t = char;
int32_t = LongInt;
unsigned_int = LongWord;
unsigned_short = Word;
int16_t = smallint;
cchar = Char;
cint = LongInt;
RTMP = record
m_inChunkSize : cint;
m_outChunkSize : cint;
m_nBWCheckCounter : cint;
m_nBytesIn : cint;
m_nBytesInSent : cint;
m_nBufferMS : cint;
m_stream_id : cint;
m_mediaChannel : cint;
m_mediaStamp : uint32_t;
m_pauseStamp : uint32_t;
m_pausing : cint;
m_nServerBW : cint;
m_nClientBW : cint;
m_nClientBW2 : uint8_t;
m_bPlaying : uint8_t;
m_bSendEncoding : uint8_t;
m_bSendCounter : uint8_t;
m_numInvokes : cint;
m_numCalls : cint;
m_methodCalls : PRTMP_METHOD;
m_vecChannelsIn : array[0..(RTMP_CHANNELS)-1] of PRTMPPacket;
m_vecChannelsOut : array[0..(RTMP_CHANNELS)-1] of PRTMPPacket;
m_channelTimestamp : array[0..(RTMP_CHANNELS)-1] of cint;
m_fAudioCodecs : double;
m_fVideoCodecs : double;
m_fEncoding : double;
m_fDuration : double;
m_msgCounter : cint;
m_polling : cint;
m_resplen : cint;
m_unackd : cint;
m_clientID : AVal;
m_read : RTMP_READ;
m_write : RTMPPacket;
m_sb : RTMPSockBuf;
Link : RTMP_LNK;
end;
PRTMP = ^RTMP;
then I call:
var MY_RTMP: RTMP;
MY_RTMP := RTMP_Alloc;
RTMP_Init(MY_RTMP);
all the record is initialized excepted the "Link" record that is used when initializing the URL.
I guess the record is not properly declared
A: I would try this. Here is the source I've used as a base.
function RTMP_SetupURL(var R: RTMP; Url: PAnsiChar): Integer; cdecl;
external 'librtmp.dll' name 'RTMP_SetupURL';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XmlTextWriter and null strings I want to serialize an object where some of the member variables are of type string and have the value null.
I use the following code:
var writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
var s = new XmlSerializer(typeof(model.GetType()));
s.Serialize(writer, model);
The strings with value null don't appear in the Xml file (which is obviously intended behavior), although I don't want that.
How can I make null strings appear in the Xml file by overriding the XmlTextWriter class?
EDIT: I can't modify the object model that needs to be serialized, so Xml attributes are no option.
A: You could use:
[XmlElement(IsNullable = true)]
on any member you want to be written on file even if null.
A: you can use this attribute on you member :
[XmlElement(IsNullable = true)]
it will set an attribute on your element specifying that it is null instead of not serializing it.
A: I suggest cloning the ObjektModleTree and replacing "null" String with empty ones.
Inherit the XmlSerializer in a new class and clone the ObjectModelTree without the "null" strings.
So if you are able to change the ObjektModel you can remove your own Serializer and use the .NET Serializer to do the work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Table does not have an inverse; this is an advanced setting (no object can be in multiple destinations for a specific relationship) I have three tables in my Core Data db. EntityManagedObject, InitiativeManagedObject, ObjectiveManagedObject. There is a 1-2-M relationship between Entity and Initiative; Entity and Objective and Entity and Entity.
I have configured the relationship to be 'to many' but I have not set an inverse relationship because I don't want an inverse relationship. I can't have an inverse relationship anyway for initiatives and objectives the designer doesn't allow it, however it does allow it for entity to entity.
The problem is I am getting these warnings:
EntityManagedObject.entities does not have an inverse; this is an
advanced setting (no object can be in multiple destinations for a
specific relationship)
EntityManagedObject.initiatives does not have an inverse; this is an
advanced setting (no object can be in multiple destinations for a
specific relationship)
EntityManagedObject.objectives does not have an inverse; this is an
advanced setting (no object can be in multiple destinations for a
specific relationship)
A: I was a bit confused by the inverse relationships at first but it makes sense. I know you are not supposed to think too much in terms of relational databases but in this case I find it helps me.
+--------+ +------------+
| | /| |
| Entity |-----| Initiative |
| | \| |
+--------+ +------------+
Looking at the diagram you would say
*
*An Entity has many Initiatives
*An Initiave has one Entity
So those are the two relationships you need to set up.
*
*Entity 'to many' Initiatives
*Initiative 'to one' Entity
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Basic: Where to initialize/set the function I am working on a .Net project(solution) which is having 25 projects. I want to set the value in some function/method so that It can be set once for the entire application. Where to set this method so that I dnt need to set it again in the individual winforms. That function/method is in some dll so i required to set that like this:
Logger obj = Logger.GetInstance();
obj.SetLogLevel(1);
I need to use the above code only once.
Kindly help?
Thank You...
A: Since you talk about pages, I assume you have a web site or a web application.
What you can do, in this case is to create a static class in App_Code and do this in it's static constructor. This way the first time any page accesses the static class the code will run and it won't run again.
public static class AStaticClass {
public static Logger Obj;
static AStaticClass() {
Obj = Logger.GetInstance();
Obj.SetLogLevel(1);
}
}
EDIT:
In case this is a window application, just put this static class in one of the libraries. It doesn't really matter where the class is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Effective search of number pairs I have a problem, where i have big list of number pairs. something like that:
(0, 1)
(10, 5)
(5, 6)
(8, 6)
(7, 5)
.....
I need to make that i can make very fast lookups if the pair exist in list.
My first idea was make map< std::pair<int,int> > container. and do searches using container.find().
Second idea was to make vector<vector<int> container where i can search is the pair exist by using std::find(container[id1].begin(),container[id1].end(),id2);
The second way is a bit faster than first, but i need more effective way if that possible.
So question is there more effective way to find is a number pair exist in list?
The number of pairs i know when starting program, so i dont care a lot about pair insertion/deletion, i just need very fast searches.
A: If you do not care about insertion you could use a sorted std::vector and std::binary_search, or std::lower_bound.
int main()
{
using namespace std;
vector<pair<int, int>> pairs;
pairs.push_back(make_pair(1, 1));
pairs.push_back(make_pair(3, 1));
pairs.push_back(make_pair(3, 2));
pairs.push_back(make_pair(4, 1));
auto compare = [](const pair<int, int>& lh, const pair<int, int>& rh)
{
return lh.first != rh.first ?
lh.first < rh.first : lh.second < rh.second;
};
sort(begin(pairs), end(pairs), compare);
auto lookup = make_pair(3, 1);
bool has31 = binary_search(begin(pairs), end(pairs), lookup, compare);
auto iter31 = lower_bound(begin(pairs), end(pairs), lookup, compare);
if (iter31 != end(pairs) && *iter31 == lookup)
cout << iter31->first << "; " << iter31->second << "at position "
<< distance(begin(pairs), iter31);
}
A: std::set is probably the way to go, and it should perform reasonably well even if the number of elements increase (whereas the performance of std::vector will slow down quite quickly unless you sort it beforehand and do some sort of binary or tree search). Keep in mind you'll have to define a < operator to use std::set.
If you can use c++0x, std::unordered_set might be worth a try also, particularly if you don't care about order. You'll find unordered_set in Boost. This doesn't require a < operator to be defined. If you make your unordered_set an appropriate size and define your own simple hash function that does not produce many collisions it might be faster than even a binary search on a sorted vector.
A: If you want faster-than-set lookups (faster than O(lg n)) and don't care about items being in a random order, then a hashtable is the way to go.
This is not part of the standard, but a hash_set is available in most compilers. The reference for it is here.
If you want to have really fast searches, you can try a Bloom filter. However, they sometimes result in false positives (i.e. detecting that there is an item pair when there is none), and require lots of memory. A suitable Bloom filter implementation would be:
const int MAX_HASH = 23879519; // note it's prime; must be 2-5 times larger than number of your pairs
vector<bool> Bloom(MAX_HASH); // vector<bool> compresses bools into bits
// multiply one by a large-ish prime, add the second, return modulo another prime
// then use it as the key for the filter
int hash(long long a, long long b) {
return (a*15485863LL + b) % MAX_HASH;
}
// constant-time addition
void add_item(pair<int,int> p) {
Bloom[hash(p.first, p.second)] = true;
}
// constant-time check
bool is_in_set(pair<int,int> p) {
return Bloom[hash(p.first, p.second)];
}
A: You could use some implementation of hash_set to get it faster
for instance boost::unordered_set where the key is the std::pair.
This is the fastest from the easiest approaches.
A: Here's another solution iff your individual numbers are ints.
*
*Construct a long long with the two ints (the first int could be the high 32 bits and the second int the lower 32 bits)
*Insert this into an unorderd_set (or set, or sorted vector - profile to find your match)
*find.
Should be some percentage faster than working with pairs/tuples etc. esp.
A: Why not sorting the tuples according to 1st element, then 2nd, then a binary search should be O(log(n)).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to intergrate IQEngine API in upload page in Node JS Here is IQengine API
So I upload an image through upload page in node js and api send the image to the engine and get a result then the result is displayed in the page.
Can you write the simple code?
Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Whether generated WCF Service Client is Synchronous or Asynchronous by default? I am new to WCF Service. I read that both ASP.NET and WCF Services are synchronous by default. However we can implement both the ASP.NET and WCF Services asynchronously. I want to know whether the generated Web Service Client (Proxy Class) is synchronous or asynchronous by default ?
A: The default is synchronous.
If you want the async method signatures, too, you need to either specify /async for svcutil.exe
C:\> svcutil (some URL here) /async
or you need to check the Generate asynchronous operations option in your Add Service Reference dialog in Visual Studio.
And of course - once you have generated the async methods, you also need to call those, obviously..... (they are called Begin(YourMethodName) and End(YourMethodName) for each of your service methods)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android sending JsonObject with json array I need to post one request to server.
Format i need to send is : { “userId”: , “array”: ("A,"b","c",...) }
I can send the jsonobject but i don't know how to send JsonObejct and Jsonarray together in one request.
A: Is it that easy how I think?
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
for (String string : new String [] {"A", "b", "c", ...}) {
array.put(string);
}
json.put("userId", theId);
json.put("array", array);
sendYourRequest(json);
// This is wrong! Code corrected. Thank you for the Feedback!!!
// json.put("array", new String [] {"A", "b", "c", ...});
A: You need to create a JSONObject and a JSONArrayObject. Add all the items you want in your json array. Then add the json array into the JsonObject. See below:
JSONArray array = new JSONArray();
array.put("1st array item");
array.put("2nd array item");
JSONObject holder = new JSONObject();
holder.put("array", array);
holder.put("other_params", ...);
Then you can also verify that the json looks valid by doing the following:
String jsonString = holder.toString(); //verify that the json is in the correct format
A: Here is a nice JSON Encoding Tutorial refer this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting WP7 Softwares on mac I want to know can we install WP7 software on Mac machine.
I found that virtual machine is an option but Windows Phone emulator will not run from within a VM.
Another thing I found is Boot Camp software can be used to install window device drivers.
I want to know will this serve my purpose?
A: As you already mentioned, virtual machine is not an option.
You need to dual boot your Mac with bootcamp. Through which it is possible to develop for WP7.
A: You can actually use a virtual image to install Windows 7 and the Windows Phone Tools and SDK. If you are developing XNA app the emulator might not work. You need to make sure DirectX 10 is supported.
Hope this help.
Dani
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: FQL event_member query returns nothing I want to select if a specific user (ie. the user logged in) is attending at a specific event. Because I don't want to use Graph API for getting always all the events a user is attending, I tried FQL SELECT rsvp_status from event_member where eid = {0} and uid = {1}, but it returned nothing. But when I tried this information getting from Graph API, I succeeded.
One thing came to my mind, maybe I gave access_token in a wrong way to the FB.Data.query function, because I only saw examples in blogs and articles, not on FB documentation.
Any help appreciated,
Tamas
A: I've found the problem. As I tested, FB.Data.query.wait is an asynchronous call, that means when FB gives back the results, it waits the main rendering to finish and then runs the callback, so it seems that it hasn't run, because the variables I set in there are set after the page is rendered.
Now I have to find a way to asynchronously write back in the rendered page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implement "Down for maintenance" page I know we could simply use an app_offline.htm file to do this.
But I want to be able access the website if my IP is 1.2.3.4 (for example), so that I can do a final testing.
if( IpAddress != "1.2.3.4" )
{
return Redirect( offlinePageUrl );
}
How can we implement this in ASP.NET MVC 3?
A: You can define a global filter that stop all the requests if they don't come from your IP. you can enable the filter by configuration.
A: I got an infinite loop on colemn615's solution, so I added a check for the offline page.
Also, for later versions of ASP.NET this is split into a FilterConfig.cs file in the App_Start folder.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CheckForDownPage());
}
public sealed class CheckForDownPage : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Request.RawUrl.Contains("Down.htm"))
{
return;
}
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Down.htm");
if (System.IO.File.Exists(path) && IpAddress != "1.2.3.4")
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.Redirect("~/Down.htm");
return;
}
base.OnActionExecuting(filterContext);
}
}
A: You can use a catch-all route with a RouteConstraint with the IP check:
Make sure you put the offline route first.
routes.MapRoute("Offline", "{controller}/{action}/{id}",
new
{
action = "Offline",
controller = "Home",
id = UrlParameter.Optional
},
new { constraint = new OfflineRouteConstraint() });
and the constraint code:
public class OfflineRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// return IpAddress != "1.2.3.4";
}
}
A: Per Max's suggestion here is an actual implementation.
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CheckForDownPage());
}
//the rest of your global asax
//....
}
public sealed class CheckForDownPage : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Down.htm");
if (System.IO.File.Exists(path) && IpAddress != "1.2.3.4")
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.Redirect("~/Down.htm");
return;
}
base.OnActionExecuting(filterContext);
}
}
A: I add an AppSetting in the Web.Config file:
<add key="MaintenanceMsg" value="We are currently performing some routine maintenance. We expect to be back up at around 01:00." />
I then update the global.asax file's Application_BeginRequest method to check if the appsetting has a value, if it does, I redirect everything to the maintenance page:
private void Application_BeginRequest(object sender, EventArgs e)
{
if(!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["MaintenanceMsg"]) && !Request.Url.ToString().Contains("UndergoingMaintenance"))
Response.Redirect("~/Home/UndergoingMaintenance");
** Do whatever you do when you don't want to show your maintenance page here**
}
Finally, create your view and controller action.
If you use Azure you can simply add and delete the value for the AppSetting in the portal so you can suspend your site in a matter of minutes without a deployment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: asp.net convert utf-8 from webservice request I get some string data from a webservice in utf-8. How do I convert it in an aspx vb to a readable format? The website is german.
A: UTF-8 is readable. ASP.NET should be able to read it just fine. If it's transmitted with a Content-Type whose charset parameter is set to something other than UTF-8 you might need to instruct ASP.NET to force the decoding to UTF-8. Use Fiddler and figure out how the HTTP request looks like and pay special attention to the Content-Type parameter.
If you have a different output-encoding than UTF-8, you should still be able to output the characters correctly if you decode them with the correct encoding. What is your output encoding? What encoding is the web service you're communicating with using? Figure the answer to these questions (using Fiddler) and your solution should be obvious.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Handling timeout exceptions when calling WCF services from Silverlight I am calling an ASMX web service using WCF from within my application - when a call to the web service fails, for example due to a timeout or connectivity issues, then the exception gets caught in the ApplicationUnhandledException method and does not pass to the Completed event handler.
What can I do to ensure that processing is passed to the Completed event handler on the web service proxy? Frustratingly there is an Error property on the xxxCompletedEventArgs class which leads me to believe it should pass back to this event handler rather than just throw an exception!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: InfoWindow on Marker using MarkerClusterer This is my html code. I've try anything to add an infowindow on the markers but it don't wanna work. My data is loading from the "Alle_Ortswahlen.page1.xml" file.
Do anyone have an idea how can I add infoWindow to each marker?
<script type="text/javascript">
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
</script>
A: Before the for cycle, make an empty infowindow object.
var infowindow = new google.maps.InfoWindow();
Than in the for cycle, after the marker, add an event listener, like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
There is some closure magic happening when passing the callback argument to the addListener method. If you are not familiar with it, take a look at here:
Mozilla Dev Center: Working with Closures
So, your code should look something like this:
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var infowindow = new google.maps.InfoWindow();
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
A: So what you need to do is add some code, inside your for-loop, associating an infowindow onclick event handler with each marker. I'm assuming you only want to have 1 infowindow showing at a time, i.e. you click on a marker, the infowindow appears with relevant content. If you then click on another marker, the first infowindow disappears, and a new one reappears attached to the other marker. Rather than having multiple infowindows all visible at the same time.
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
// just create one infowindow without any content in it
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent(markers[i].getAttribute("Field123"));
infowindow.open(map, this);
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Append json messages when multiple json arrays are echo'd with jQuery I have 2 classes that return a json encoded array if an error message is added to the $_error array:
Validate.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
UserTools.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
Then in ajax.php I check if either of those classes return true, if so a new user can be added by a User class, then the user class will return a success response, if they don't return true, the json encoded errors in either UserTools.class.php or Validate.class.php are returned by either of those classes:
ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}
else {
echo $user_tools->showResponse();
echo $validate->showResponse();
}
Firebug shows that everything get's returned as expected, UserTools.class.php returns the usernameexists error and Validate.class.php returns the others:
{"error":{"usernameexists":"Username already taken"}}
{"error":{"password":"This field is required","password_again":"This field is required","email":"This field is required"}}
Yet I can't display either of those messages via jQuery, if I remove 'echo $user_tools->showResponse();' from 'else' in ajax.php, the error messages do get appended correctly, when I want to display both errors, nothing get's appended.
jQuery file:
if(msg.error) {
if(msg.error['usernameexists']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['username']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['password']) {
$('#msg-password').show().html('<p></p>').addClass('error');
$('#msg-password p').append(msg.error['password']);
}
if(msg.error['password_again']) {
$('#msg-password_again').show().html('<p></p>').addClass('error');
$('#msg-password_again p').append(msg.error['password_again']);
}
if(msg.error['email']) {
$('#msg-email').show().html('<p></p>').addClass('error');
$('#msg-email p').append(msg.error['email']);
}
}
A: The reason its not working is because there are 2 seperate json objects
One way is to combine them, for that put this in your ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}else {
$r1 = $user_tools->showResponse();
$r2 = $validate->showResponse();
if($r1 !== true && $r2 !== true){
$r1 = json_decode($r1);
$r2 = json_decode($r2);
foreach($r2['error'] as $k => $v)
$r1['error'][$k] = $v;
$r1 = json_encode($r1);
}else if($r1 === true){
$r1 = $r2;
}
echo $r1;
}
Other easier way would be to return the error object itself instead of json_encoded one from Validate.class.php and UserTools.class.php and combine them in ajax.php then output the json_encoded string. this would save the 2 json_decode calls in the above code.
A: Your return string contains two objects and i think that is what (rightly) confuses the json parser. Try prepending a { and appending a } to the else output, and separate the two objects with a comma
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySqlDataReader: DataTable.Fill(reader) throws ConstraintException I have two tables orders and orderdetails
table orders (PK = id, UNIQUE index on orderno)
|id|orderno|
| 1|1000 |
| 2|1001 |
table orderdetails (PK = id)
|id|orderid|item|qty|
| 1| 1|ABC | 3|
| 2| 1|XYZ | 4|
Now I want to query the data with:
SELECT o.orderno, od.item, od.qty
FROM orders o
INNER JOIN orderdetails od ON o.orderno = od.order
which returns:
|orderno|item|qty|
|1000 |ABC | 3|
|1000 |XYZ | 4|
However If I use the following code to load the result into a DataTable it fails:
var connectionString = "Server=localhost;Database=orders;Uid=root;";
var commandText = "SELECT o.orderno, od.item, od.qty" + Environment.NewLine +
"FROM orders o" + Environment.NewLine +
"INNER JOIN orderdetails od ON o.orderno = od.order";
var reader = MySqlHelper.ExecuteReader(connectionString, commandText);
var table = new DataTable("OrdersQuery");
table.Fill(reader); // throws ConstraintException
The problem is, that
table.Constraints[0]
is a UniqueConstraints on the orderno column. Propably because
reader.GetSchemaTable()
has a IsUnique=true entry for orderno (which is true in the base table, but not true for the join query).
Even worse, that doesn't help either:
table.BeginLoadData(); // msdn docs claim that this should disable constraints
table.Load(reader);
table.EndLoadData();
Any ideas how to fix this?
StackTrace:
System.Data.ConstraintException Was Unhandled.
Message=Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Source=System.Data
StackTrace:
bei System.Data.DataTable.EnableConstraints()
bei System.Data.DataTable.set_EnforceConstraints(Boolean value)
bei System.Data.DataTable.EndLoadData()
bei System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
bei System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
bei System.Data.Common.LoadAdapter.FillFromReader(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
bei System.Data.DataTable.Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler)
bei System.Data.DataTable.Load(IDataReader reader)
A: I just figured out, that
table.Fill(reader)
does not create the constraint, if I already added the columns.
So I fixed this by using a nice little extension method:
public static void Load(this DataTable table, IDataReader reader, bool createColumns)
{
if (createColumns)
{
table.Columns.Clear();
var schemaTable = reader.GetSchemaTable();
foreach (DataRowView row in schemaTable.DefaultView)
{
var columnName = (string)row["ColumnName"];
var type = (Type)row["DataType"];
table.Columns.Add(columnName, type);
}
}
table.Load(reader);
}
Usage:
table.Fill(reader, true);
A: There is simple dirty way how to fix it - surround column in query with unique contraint with concat function:
var commandText = "SELECT CONCAT(o.orderno, ''), od.item, od.qty ...";
A: I had the same error today and want to share.My problem was a column with a LONGTEXT type. If I include LONGTEXT column in my query and tried to load dataset without specifying column names exception was thrown. Based on SchlaWiener's code I rewrote the code as follows and everything is fine now.
MySqlDataReader resultSet = cmd.ExecuteReader();
dt.Columns.Clear();
for (int i = 0; i < resultSet.FieldCount; i++)
{
dt.Columns.Add(resultSet.GetName(i));
}
dt.Load(resultSet);
A: I had the same problem but got it fixed by using the workaround from this post: http://bugs.mysql.com/bug.php?id=65065 (at bottom):
cmd.CommandText = "SELECT cam.no_serie, t.mnt FROM trx t LEFT JOIN camn cam USING(id_camn) ";
MySqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
DataTable dataTable = new DataTable();
ds.Tables.Add(dataTable);
ds.EnforceConstraints = false;
dataTable.Load(dr);
dr.Close();
A: MySQL allows multiple null values in unique indexes. This causes ConstraintException on fill. How to fix: find this constraint in the 'table.Constraints' list and remove it or just clear all constraints.
A: I had a similar problem with the queries, when loading the Datatable () with the MYSQL Reader it generated error NON-NULL, UNIQUE or FOREIGN-KEY.
In the end I solved it by changing the MySQL Connector.NET version.
https://dev.mysql.com/downloads/connector/net/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Android: Opening wrong Activity from the widget I have been struggling with this problem for a while now. I have a widget which displays summary of a cooking recipe. The widget is clickable so whenever user clicks on it the new activity is opened with a full description of that recipe. The problem is that sometimes when the widget is clicked it opens a wrong activity. Let me give you an example:
*
*User clicks on widget and activity A is opened
*User starts activity B (e.g. recipe index) from the activity A.
*User starts activity C from activity B.
*User presses Home button.
*User clicks on the widget again and the activity C is displayed instead of A
I tried setting a compibation of those three flags which helps in solving only a half of the problem:
openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
By using above flags I managed to display a correct activity (A) until I do the following:
*
*User opens activity A from the widget
*User moves to activity B and opens activity A by clicking on new recipe
*New recipe is displayed to the user
*User clicks Home button and clicks on the widget.
*Activity A is displayed (the right one) but with different recipe.
*From now on if I move to different activities B or C and click Home and then widget again the activity A is not displayed but the one which was visible before pressing Home button.
I hope I explained it in enough details. I would be really grateful for your help because this thing drives me crazy!
Updated:
This is my pendingIntent:
Intent openIntent = new Intent(context, ProfanityDefinition.class);
openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
openIntent.setData(Uri.parse(openIntent.toUri(Intent.URI_INTENT_SCHEME)));
Bundle bundle = new Bundle();
bundle.putBoolean("widgetRequest", true);
openIntent.putExtras(bundle);
PendingIntent openPendingIntent = PendingIntent.getActivity(context, 0, openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_content, openPendingIntent);
Thanks
A: Show the code for creating the PedningIntent. If you are passing extras to your activity, be aware that two intents that differ only by extras are treated as equivalent. You probably want to pass the PendingIntent.FLAG_CANCEL_CURRENT when you create the PendingIntent to make sure your intent is not reused.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why do I get a missing handler for logger "sentry.errors"? I installed django-sentry in an integrated fashion.
I then ran python manage.py shell and tried to log like this:
>> import logging
>> mylog = logging.getLogger('sentrylogger')
>> mylog.handlers
[<logging.StreamHandler instance at 0x9f6130c>,
<sentry.client.handlers.SentryHandler instance at 0x9ffed4c>]
>> mylog.debug('this is a test 1')
DEBUG 2011-09-28 11:10:33,178 <ipython console> 4607 -1217300800 this is a test 1
No handlers could be found for logger "sentry.errors"
Currently, nothing is written to the sentry. I believe the missing logger 'sentry.errors' is the root cause of my inability to log to sentry. Am I on the right track ?
A: Yes, there's a handler missing. I cannot explain why logging to one log should affect another log instance, but maybe if you try to write this before doing mylog.debug(..) it will work:
sentry_errors_log = logging.getLogger("sentry.errors")
sentry_errors_log.addHandler(logging.StreamHandler())
Furthermore, refer to the documentation about older versions that seem to add sentry.errors log handler manually:
http://readthedocs.org/docs/sentry/en/latest/config/index.html#older-versions
A: if you are running sentry on your own domain with HTTPS, there is a bug in sentry SNI support. check https://github.com/getsentry/raven-python/issues/523 for more details. A quick workaround is to replace DSN scheme by threaded+requests+https:
RAVEN_CONFIG = {
'dsn': 'threaded+requests+https://xxxxxxxxxxxx@sentry.example.com/1',
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.