text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Is it possible to center an inline-block element and if so, how? I have an element of initially unknown width, specifically a MathJax equation supplied by the user. I have the element set as inline-block to ensure that the width of the element fits its contents and so that it has a defined width. However, this prevents traditional methods of centering. That is, the following does not work:
.equationElement
{
display: inline-block;
margin-left: auto;
margin-right: auto;
}
And the solution cannot be:
.equationElement
{
display: block;
width: 100px;
margin-left: auto;
margin-right: auto;
}
Because I have no idea what the width should actually be beforehand and if the user clicks on the equation, I need the entire equation highlighted, so I cannot set the width to 0. Does anyone have a solution to centering this equation?
A: Another way to do this (works for block element also):
.center-horizontal {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Explanation:
left:50% will position the element starting from the center of containing parent, so you want to pull it back by half of its width with transform: translateX(-50%)
Note1:
Be sure to set the the position of containing parent to position: relative; if the parent is absolutely positioned put a 100% width and height, 0 padding and margin div inside it and give it position: relative
Note2: Can also be modified for vertical centering with
top:50%;
transform: translateY(-50%);
A: A little late, but similar to Ivek's answer, you can avoid using the position declaration by using margin-left rather than left, so:
margin-left: 50%;
transform: translateX(-50%);
A: Simply set text-align: center; on the container.
Here's a demo.
A: You can do this by changing it to a block element and using max-content:
.element {
display: block; /* Change from inline-block to block */
margin-inline: auto;
width: max-content;
}
Using width: fit-content will also work.
A: my way, i wrap the inline-block element with other div, e.g. wrapper, and then its magically centered, if not then give margin auto or something to the wrapper class
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "73"
}
|
Q: How to preserve conditional comments in element in a Diazo theme? I have a Diazo theme file which is based on the html5boilerplate. The theme uses conditional comments on the <html> element to identify particular versions of Internet Explorer, e.g.
<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]-->
<!-- Consider adding an manifest.appcache: h5bp.com/d/Offline -->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
However, when the theme is applied Diazo seems to strip away these conditional comments and only the last
<!--<![endif]-->
is left in the final markup producing something like
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" class="no-js" lang="en" xml:lang="en"><!--<![endif]-->
with an unmatched endif. Using conditional comments within the <html> tag (e.g. inside <head> or further down in the document) seems to work fine.
Examples of a theme and rules files which have this issue are available at
https://github.com/hexagonit/hexagonit.themeskel/blob/master/hexagonit/themeskel/templates/less_theme/+namespace_package+/+package+/theme_resources
I'm using plone.app.theming 1.0b8 with the associated KGS versions from good-py.
A: This looks like a bug in Diazo, please add it to the Plone bug tracker with component 'Diazo'.
A: A work around for this could be to use conditional comments on the <body> tag, but Diazo must also add a few classes to the body tag for Plone, which would break it in <=IE8.
<merge attributes="class" css:theme="body" css:content="body" />
So a 3rd rate work around could be to use contional comments on a div block like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<title>Title</title>
</head>
<body>
<!--[if lt IE 7]> <div class="no-js ie6 oldie"> <![endif]-->
<!--[if IE 7]> <div class="no-jsie7 oldie"> <![endif]-->
<!--[if IE 8]> <div class="no-js ie8 oldie"> <![endif]-->
<!--[if gt IE 8]><!--> <div class="no-js"> <!--<![endif]-->
<div id="content"></div>
</div><!-- Browser Detection -->
</body>
</html>
Given the general fuglyness of Plone's generated html, I could live with this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Visual Studio Setup Project Remove install for all users I am creating a setup project and want to remove the option to install for "everyone" or "just me" and have it default to just me.
A:
View->Editor->User Interface. Click on Installation folder. In the properties window there is a key InstallAllUsersVisible. Set it to false –
A: If you don't want to show the option at all in the screen. You can do the above said one "View->Editor->User Interface." in the properties window, Set the InstallAllUsersVisible. Set it to false.
If you wish not to show the details, then: click on the setup project, select "F4" button to open the setup project properties. In the properties list "InstallAllUser" properties to be set to false. This will make the option invisible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How can I use an action filter in ASP.NET MVC to route to a different view but using the same URL? Is it possible to make a filter that, after a controller action has been (mostly) processed, checks for a certain test condition and routes to a different view transparently to the user (i.e., no change in the URL)?
Here would be my best guess at some pseudocode:
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// If some condition is true
// Change the resulting view resolution to XYZ
base.OnResultExecuting(filterContext);
}
A: filterContext.Result = new ViewResult
{
ViewName = "~/Views/SomeController/SomeView.cshtml"
};
This will short-circuit the execution of the action.
A: also you can return view as from your action
public ActionResult Index()
{
return View(@"~/Views/SomeView.aspx");
}
A: I have extended the AuthorizeAttribute of ASP.NET MVC action filter as DCIMAuthorize, in which I perform some security checks and if user is not authenticated or authorized then action filter will take user to access denied page. My implementation is as below:
public class DCIMAuthorize : AuthorizeAttribute
{
public string BusinessComponent { get; set; }
public string Action { get; set; }
public bool ResturnJsonResponse { get; set; }
public bool Authorize { get; set; }
public DCIMAuthorize()
{
ResturnJsonResponse = true;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
try
{
//to check whether user is authenticated
if (!httpContext.User.Identity.IsAuthenticated)
return false;
//to check site level access
if (HttpContext.Current.Session["UserSites"] != null)
{
var allSites = (VList<VSiteList>)HttpContext.Current.Session["UserSites"];
if (allSites.Count <= 0)
return false;
}
else
return false;
// use Authorize for authorization
Authorize = false;
string[] roles = null;
//get roles for currently login user
if (HttpContext.Current.Session["Roles"] != null)
{
roles = (string[])HttpContext.Current.Session["Roles"];
}
if (roles != null)
{
//for multiple roles
string[] keys = new string[roles.Length];
int index = 0;
// for each role, there is separate key
foreach (string role in roles)
{
keys[index] = role + "-" + BusinessComponent + "-" + Action;
index++;
}
//access Authorization Details and compare with keys
if (HttpContext.Current.Application["AuthorizationDetails"] != null)
{
Hashtable authorizationDetails = (Hashtable)HttpContext.Current.Application["AuthorizationDetails"];
bool hasKey = false;
foreach (var item in keys)
{
hasKey = authorizationDetails.ContainsKey(item);
if (hasKey)
{
Authorize = hasKey;
break;
}
}
}
}
return base.AuthorizeCore(httpContext);
}
catch (Exception)
{
throw;
}
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
try
{
filterContext.Controller.ViewData["ResturnJsonResponse"] = ResturnJsonResponse;
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
return;
}
if (!Authorize)
{
//Authorization failed, redirect to Access Denied Page
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "Base" },
{ "action", "AccessDenied" }
//{ "returnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
catch (Exception)
{
throw;
}
}
}
A: This is what I ended up doing, and wrapped up into a reusable attribute and the great thing is it retains the original URL while redirecting (or applying whatever result you wish) based on your requirements:
public class AuthoriseSiteAccessAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// Perform your condition, or straight result assignment here.
// For me I had to test the existance of a cookie.
if (yourConditionHere)
filterContext.Result = new SiteAccessDeniedResult();
}
}
public class SiteAccessDeniedResult : ViewResult
{
public SiteAccessDeniedResult()
{
ViewName = "~/Views/SiteAccess/Login.cshtml";
}
}
Then just add the attribute [SiteAccessAuthorise] to your controllers you wish to apply the authorisation access to (in my case) or add it to a BaseController. Make sure though the action you are redirecting to's underlying controller does not have the attribute though, or you'll be caught in an endless loop!
A: You Can Also Save All Route File Path in a Static And Use it Like This :
public static class ViewPath
{
public const string SomeViewName = "~/Views/SomeViewName.cshtml";
//...
}
And into Your ActionFilter :
context.Result = new ViewResult()
{
ViewName = ViewPath.SomeViewName /*"~/Views/SomeViewName.cshtml"*/
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: .mo and .po files for wordpress theme internationalization Ok, so I feel like a complete idiot asking this, but I've been looking around and I haven't found a decent answer.
I am using qTranslate as i18n plugin to create a multilingual website.
I have a localized framework/theme with a default.po file. I have built both en_CA.po/.mo and fr_FR.po/.mo files.
What do I do with these and how do I activate them?????
I have tried defining WPLANG in wp-config.php, with no result...
English is already the default one so it works fine, but the French one doesn't apply when switching form english to french... I still get the english text for theme strings (content translates fine)
Thanks for your help!
A: I figured out it appeared to be a setting in qTranslate that set both locales to en_US and fr_FR instead of en_CA and fr_CA
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Excel VBA Macro to query Amazon Web Services for Book data I have an .xcl with 500 books, title in one column, author in another.
I want to query amazon web services with a vba macro to pull back amazon's listing with title, author, isbn, and most importantly publisher and year.
Book list - getting book details from amazon using Excel VBA barcode lookups
http://channel9.msdn.com/coding4fun/articles/Using-the-Amazon-Web-Service
These have me on the right path, but one searches by isbn's, and the other i dont understand.
I have very little programming experience, but am a fast learner so what do I need to do to get this to work? Otherwise I have to go line by line and search amazon individually.
Please Help!
A: There is two ways to solve this issue:
http://www.linhadecodigo.com.br/Artigo.aspx?id=448
http://www.linhadecodigo.com.br/artigo/449/Obtendo-dados-atualizados-da-Web-atrav%C3%A9s-do-Excel-XP-Parte-2Consumindo-Web-Services-no-Office.aspx
The articles are in Portuguese, but I believe that you can read it using Google Translate.
I hope it helps
A: Easier way would be to use automation software that offers web data extraction capabilities. Look at Automation Anywhere. You can probably set up the task and schedule it within a few minutes. Hope this helps.
-Tom
A: The ISBNDB API lets you search by keyword, ISBN, author or publisher.
http://isbndb.com/docs/api/
Given your search criteria, it returns title, author, ISBN, and a host of other information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Remove item from dropdown list on page load (no jquery) I have the following dropdown list:
<select name="DD1" id="DD1">
<option value="B">B</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="R">R</option>
</select>
On page load I need to hide/delete option D. I can't go by the index because that list is dynamic so I have to use the value parameter or the actual text that gets rendered.
I've tried finding the answer but all the solutions I came across use JQuery for this and I don't have the option to do this.
Anyone have a way to hide option D just using Javascipt on page load so the user never sees that option?
Thanks
A: I used window.addEventListener it won't work on down-level browsers that don't support it. I suggest creating your own addEvent method that abstracts the inconsistencies - if jQuery (or some other framework) is not allowed.
window.addEventListener("load", function(){
var list = document.getElementById('DD1'), el;
for(var i in list.children){
el = list.children[i];
if(el.hasOwnProperty('value')) {
if(el.value == 'D') {
el.style.display = 'none';
break;
}
}
}
}, false);
http://jsfiddle.net/UV6nm/2/
A: var select=document.getElementById('DD1');
for (i=0;i<select.length; i++) {
if (select.options[i].value=='D') {
select.remove(i);
}
}
A: Try looping over the options, checking the value, and if it matches, set it to null:
function removeByValue(id, value) {
var select = document.getElementById(id);
for (var i=0, length = select.options.length; i< length; i++) {
if (select.options[i] && select.options[i].value === value) {
select.options[i] = null;
}
}
}
removeByValue('DD1', 'D');
A: var selectbox = document.getElementById('DD1');
for(var i = 0; i < selectbox.options.length; i++)
{
if(selectbox.options[i].value == 'D')
selectbox.remove(i);
}
A: Since everyone else has proposed basically the same solution, here's a simpler solution if you have the benefit of only targeting modern browsers:
var el = document.querySelector('select[name=DD1] option[value=D]');
el.parentNode.removeChild(el);
Or, for every browser:
var el;
if(typeof document.querySelector == 'function') {
el = document.querySelector('select[name=DD1] option[value=D]');
} else {
for(var child in document.getElementById('DD1').childNodes) {
if(child.textContent == 'D') {
el = child;
break;
}
}
}
el && el.parentNode.removeChild(el);
A: There's probably a little cleaner way to do this but I am rusty with javascript.
var options = documentgetElementsByTagName("option");
for(i=0; i<options.length; i++)
{
if(options[i].value == "D")
{
this.class += "displayNone";
}
}
.displayNone{ display: none; }
this is not tested so I don't know if it would work.
A: you don't need this. just a two line code is enough.
var Node1 = document.getElementById("DD1");
Node1.removeChild(Node1.childNodes[1]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Script to read in line, select from value, and print to file So I have a php script, I want to read in a file line by line, each line only contains one id. I want to select using sql for each id in the file, then print the result for each selection in the same file.
so far i have:
while (!feof($file))
{
// Get the current line that the file is reading
$currentLine = fgets($file) ;
//explodes integers by amount of sequential spaces
//$currentLine = preg_split('/[\s,]+/', $currentLine);
echo $currentLine; //this echo statement prints each line correctly
selectQuery($currentLine) ;
}
fclose($file) ;
as a test so far i only have
function selectQuery($currentLine){
echo $currentLine; //this is undefined?
}
A: The result of fgets is never undefined. However, your approach is way too low-level. Use file and array_filter:
$results = array_filter(file('input.filename'), function(line) {
return strpos($line, '4') !== false; // Add filter here
});
var_export($results); // Do something with the results here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: glutIdleFunc not calling idle function I'm creating a maze program, that randomly generates a path. I'm using an idle function to calculate the next direction and shape of the path, but for some reason the idle function is not being called by glutIdleFunc. I checked this with visual studio's debugger and having it step through each line of code. When the debugger gets to the "glutIdleFunc(idle)", it just skips over it rather than going into the function.
A previous build had idle getting called, but the logic in it was not right, so I had to completely rewrite the idle function. I did get rid of some global variables that I no longer needed with my new logic, but I don't think they should have affected whether or not idle gets called.
This is the main that calls glutIdleFunc.
//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char **argv){
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set the display mode
glutInitWindowSize(640,480); // set the window size
glutInitWindowPosition(100, 150); // set the window position on the screen
glutCreateWindow("Maze"); // open the screen window(with its exciting title)
glutDisplayFunc(myDisplay); // register the redraw function
myInit();
glutIdleFunc(idle); // IDLE FUNCTION IS CALLED HERE
glutMainLoop(); // go into a perpetual loop
}
Here is the idle function
void idle(){
int c; // holds column value for square
int r; // holds row value for square
if((done == false) && just_visited.empty()){
// initialize random seed
srand ( time(NULL) );
// randomly select first maze square indices
c = rand() % num_col + 1;
r = rand() % num_row + 1;
}
else if(done == false){
// set c and r to index values for last
// accessed block
c = just_visited.top().col;
r = just_visited.top().row;
vector<square> possible_paths;
bool open_path = false; // will set to true if there is an untouched adjacent square to move to
// will not exit loop until an open path is found or the maze has been completed
while(open_path != true || done != true){
// if statements check each adjacent square to see if they are possible_paths
// if they are then they get put into possible paths vector for access later
if(map[r][c].north == true && map[r+1][c].east == true && map[r+1][c].north == true && map[r+1][c-1].east == true){
possible_paths.push_back(map[r+1][c]);
open_path = true;
}
if(map[r][c].east == true && map[r][c+1].east == true && map[r][c+1].north == true && map[r-1][c+1].north == true){
possible_paths.push_back(map[r][c+1]);
open_path = true;
}
if(map[r-1][c].north == true && map[r-1][c].east == true && map[r-2][c].north == true && map[r-1][c-1].east == true){
possible_paths.push_back(map[r-1][c]);
open_path = true;
}
if(map[r][c-1].north == true && map[r][c-1].east == true && map[r][c-2].east == true && map[r-1][c].north == true){
possible_paths.push_back(map[r][c-1]);
open_path = true;
}
if(!open_path){ // if no direction around current square is open, backtrack in maze
just_visited.pop(); // pop last off the stack
if(just_visited.empty()){ // if stack is empty then the maze is done
done = true;
}
// set and c and r to new square values
c = just_visited.top().col;
r = just_visited.top().row;
}
} // end of while loop
if(!done && open_path){
//choose a direction to go
int dir = rand() % possible_paths.size();
if(possible_paths[dir].col > c){
map[c][r].east = false;
just_visited.push(map[c+1][r]);
}
else if(possible_paths[dir].col < c){
map[c-1][r].east = false;
just_visited.push(map[c-1][r]);
}
else if(possible_paths[dir].row > r){
map[c][r].north = false;
just_visited.push(map[c][r+1]);
}
else if(possible_paths[dir].row < r){
map[c][r-1].north = false;
just_visited.push(map[c][r-1]);
}
} // end of if statement
glutPostRedisplay();
} //end of if statement
} // end of idle
Can anyone help me out? What am I missing doing wrong that idle isn't getting called?
(Also I'm having trouble pasting code into here from visual studios, the formatting gets super messed up. I'm using chrome for my browser)
Here is a link to my full visual studios project folder
http://dl.dropbox.com/u/15786901/Maze.rar
A: Your misconception lies here:
glutIdleFunc(idle); // IDLE FUNCTION IS CALLED HERE
glutIdleFunction does not call idle. It merely registers idle as being a callback, called whenever GLUT did process all pending events; glutPostRedisplay posts a redisplay event, so if you called glutPostRedisplay somewhere – like at the end of the display function – then the idle handler will not be called. Thus in a program registering a idle callback, glutPostRedisplay should only be called from GLUT event handlers, except the display handler.
A: glutIdleFunc does not call the Idle function, it only assigns a function to be called in glutMainLoop() whenever your process has nothing else to do.
A:
When the debugger gets to the "glutIdleFunc(idle)", it just skips over it rather than going into the function.
glutIdleFunc() just registers the function pointer with GLUT. Logic inside of glutMainLoop() takes care of actually calling it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flex 3: is it possible to add an event listender to a boolean variable? I have a boolean variable, projectsLoaded that is set to false when my application loads. As i'm sure you can imagine, when the final project module loads, I set the variable to be true. Is there a way I can trigger a series of functions to run once that variable is set to true?
A: You can use setters and getters to execute code when value changes. Just be sure to use the setter instead of setting the private variable value.
EDIT : I just saw you tagged your question with addeventlistener. I edited the code to use that instead.
private _projectsLoaded:Boolean = false;
//this could be done elsewhere, that's just an example
private function init():void
{
addEventListener("projectsLoaded", onProjectsLoaded);
}
public function get projectsLoader():Boolean
{
return _projectsLoaded;
}
public function set projectsLoaded(value:Boolean):void
{
if(_projectsLoaded!=value)
{
_projectsLoaded = value;
if(value)
dispatchEvent(new Event("projectsLoaded"));
}
}
protected function onProjectsLoaded(event:Event):void
{
//your logic here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: protobuf-net v2 and Monotouch : How does it mix? I have been trying to use protobuf-net with MonoTouch but I have no idea how, and despite having heard that it is possible, I haven't been able to find any tutorial or any example that actually work.
It was confirmed by Marc Gravell on his blog that it does work on MonoTouch. I have also looked through the blogs of the two people he states in this article, but I haven't found anything related to protobuf.
Having no lead on the subject, i decided to download protobuf-net and try it out anyway. So I created the following object for testing purposes :
[ProtoContract]
public class ProtoObject
{
public ProtoObject()
{
}
[ProtoMember(1)]
public byte[] Bytes { get; set; }
}
and I tried to send it through WCF from a service running on windows using a [ServiceContract] interface with
[OperationContract]
ProtoObject GetObject();
but the instance of ProtoObject recieved on the device is always null. This is not really unexpected since i have read that to make protobuf-net work with WCF you need to modify the app.config/web.config.
It's a little hard to accomplish since a MonoTouch project has no app.config, but I did not yet give up. To replace the app.config, I tried to add the ProtoEndpointBehavior to the client's endpoint's behaviors programmatically, and there I hit a wall. ProtoBuf.ServiceModel.ProtoEndpointBehavior, available on .NET 3.0 implementation of protobuf-net is not available on the iOS release.
How would I go about using protobuf-net to deserialize objects received from a windows-based WCF endpoint using protobuf-net serialization.
A: It is actually pretty much the same as described in this blog entry by Friction Point Studios. Since meta-programming on the device is not really an option, the trick is to pre-generate a serialization dll. This can be done by creating a small console exe (this is just a tool - it isn't designed to be pretty) that configures a RuntimeTypeModel (by adding the types you are interested in), and then call .Compile(...):
var model = TypeModel.Create();
model.Add(typeof (ProtoObject), true);
model.Compile("MySerializer", "MySerializer.dll");
This generates a serializer dll; simply reference this dll (along with the iOS version protobuf-net), and use the serializer type in the dll to interact with your model:
var ser = new MySerializer();
ser.Serialize(dest, obj); // etc
A: Just to bring this up to date there are a few issues with using WCF + Protobuf on MonoTouch. As you have observed the current releases of System.ServiceModel and protobuf light for ios don't include all the necessary bits.
However if you go and get the full System.ServiceModel from the Mono repository on GitHub and build it against the full Protobuf source then you can get it to work; I have done so.
You need to generate a serialisation assembly using the precompile tool then edit the ProtoOperationBehavior attribute to give it some way to reference your serialisation assembly. All the changes are too extensive to document here but it can be done and it is a lot faster than DatacontractSerializer which is pretty awful on iOS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Javascript order execution of prompt and document.writeln statements I am trying to write a program that iteratively solves a problem with user input. It is something like trying to guess a user's number between 0 and 100 using binary search.
So the program spits something out (in the form of
document.writeln statements); then asks the user for a new input (using prompt()); does some more crunching and spitting out until eventually it terminates. Here is my problem:
The program does not execute the document.writeln statements until it has executed all of the
prompt statements. The rest of the statements execute in proper order.
I'd really appreciate some help on understanding why this this happening. I know that Javascript has a peculiar notion of execution order and perhaps it is doing this because it likes to do the prompt()'s first because they are alerts, but I still don't get it.
thanks
A: You might want to try appending some text onto the contents of a <div>. document.writeln has some legacy problems that you're likely to run into if you continue down this path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to edit html (tags), before being executed by CppWebBrowser I can't solve my problem, and I hope somebody knows how...
I have a component on my form TCppWebBrowser, and when I navigate to a URL, after the document was downloaded, in method OnDocumentComplete() , I'm trying to check and change html source of loaded document... before it being executed by browser.
I need that, because some websites have background sounds, and I want to parse html and remove tags or just remove text which contains sound files like *.wav , *.mid , *.swf, *.mp3 ... ect.
For example if html source have this line:
<NOEMBED><BGSOUND src="/images/ImagineCut.wav"></NOEMBED>
then, i change it to:
<NOEMBED><BGSOUND src="/images/ImagineCut."></NOEMBED>
or I can delete whole tag.
Using this way I want to mute webbrowser or even to stop playing sounds. Please take into consideration this method, because it will help me to avoid all kind of sounds after I edited html.. (before browser execute it)
That's what I tried to do:
void __fastcall TForm1::CppWebBrowser1DocumentComplete(TObject *Sender,
LPDISPATCH pDisp, Variant *URL)
{
IHTMLDocument2 *pHTMLDoc;
CppWebBrowser1->Document->QueryInterface(IID_IHTMLDocument2,(LPVOID*)&pHTMLDoc);
IHTMLElement *pElem;
pHTMLDoc->get_body(&pElem);
BSTR text;
pElem->get_innerHTML(&text);
text = Cleaning(text); //checking and changing html without souds
pElem->put_innerHTML(text);
pElem->Release();
pHTMLDoc->Release();
}
A: To do what you are asking, you would have to download the HTML file yourself from outside of the TCppWebBrowser component completely, alter the HTML as needed, and then push the new HTML into TCppWebBrowser using one of its IPersist... interfaces. Examples of doing that have been posted in the Borland/CodeGear/Embarcadero forums many times before.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can we use .xml file to truncate a table when server(JBOSS) started? How can I truncate table when jboss server started ?
Can we use mysql-ds.xml ?
HOw can we use xml to truncate a table ?
HINT :- I saw jboss creates timer table automatically when server started using .xml file.
But I want to truncate a table using xml file.Is it possible?
A: This has been closed.We have to modify server file in server/default/deploy/jms/hsqldb-jdbc-state-service.xml by appendig truncate coomand
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android ImageView: How to prevent scaling with ScaleType.CENTER? According to the docs, using the CENTER attribute will not perform any scaling on the image. Yet, when loading a PNG via XML like shown below, it appears significantly larger than it should be.
What's going on?
I figure the image is being scaled when it's loaded, but why? Is there some manifest tag missing, or should I be using a different folder?
<ImageView
android:src="@drawable/auth_logo"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scaleType="center"></ImageView>
Any help would be appreciated.
A: Scaling of image is caused by difference between your image's DPI and screen DPI.
Android manages scaling so that DPI matches.
Image's DPI is determined by res source folder where image is stored (drawable / drawable-hdpi / etc), and actual screen density, which is given physically and is fixed for given device.
To avoid scaling, put your image into res/drawable-nodpi folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Session variable not taking effect in asp.net I have a session variable in my asp.net application. The session variable holds a value from the database, that reflects a customized HTML color value.
In my application, I have an asp button with server side code
btnContinue.BackColor = System.Drawing.Color.FromName(Session("ContinueColor"))
Issue: However, when I run the application, the color value is not being reflected in the button.
I did double check, and the session variable does hold the correct value.
There are other objects, that use session variables to display colors, and they are working fine.
How can I resolve this issue?
Update: When I force a color "btnContinue.BackColor = Drawing.Color.Blue", that works perfectly fine.
A: If it's a hex code, you might want to use ColorTranslator instead:
btnContinue.BackColor = System.Drawing.ColorTranslator.FromHtml(Session("ContinueColor").ToString());
Looking at the color information you posted in your comment, I think you just need to cast the session object as type Color:
btnContinue.BackColor = DirectCast(Session("ContinueColor"), System.Drawing.Color)
EDIT
I found the solution:
btnContinue.BackColor = System.Drawing.Color.FromName("{Name=48E8DD, ARGB=(0, 0, 0, 0)}")
In your case, it would be:
btnContinue.BackColor = System.Drawing.Color.FromName(Session("ContinueColor").ToString())
A: Which part of the page life cycle are you setting the color? Maybe the session data has not been read yet? Session should be ready after PageLoad.
I recommend setting a break point immediately after this line of code to make sure nothing else is overriding it - theme.
btnContinue.BackColor = System.Drawing.Color.FromName(Session("ContinueColor"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to retrieve textbox value and subtract from it Ive a textbox with id fnlprce I want to retrieve its value on an event, subtract 50 from it and update it to the latest value, ive this piece of code to work over:
function updateDiscount() {
var iniprce = parseInt($("#fnlprce").text());
var fnlprce = iniprce-50;
$("#dscntdprce").html("Price: " + fnlprce + ");
$("fnlprce").html(fnlprce);
}
But something getting wrong as it is showing, ‘NaN’ in the output, guidance please :)
A: Change
var iniprce = parseInt($("#fnlprce").text());
to
var iniprce = parseInt($("#fnlprce").val());
because val() is current value of that textbox.
Besides that, change
$("#dscntdprce").html("Price: " + fnlprce + ");
to
$("#dscntdprce").html("Price: " + fnlprce);
because yours one have syntax error
A: Use .val() instead of .text() as an input's value is found in its value= attribute, and not as a text node inside of it.
function updateDiscount() {
var iniprce = parseInt($("#fnlprce").val(), 10);
var fnlprce = iniprce - 50;
$("#dscntdprce").html("Price: " + fnlprce);
$("#fnlprce").html(fnlprce);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does one safely static_cast between unsigned int and int? I have an 8-character string representing a hexadecimal number and I need to convert it to an int. This conversion has to preserve the bit pattern for strings "80000000" and higher, i.e., those numbers should come out negative. Unfortunately, the naive solution:
int hex_str_to_int(const string hexStr)
{
stringstream strm;
strm << hex << hexStr;
unsigned int val = 0;
strm >> val;
return static_cast<int>(val);
}
doesn't work for my compiler if val > MAX_INT (the returned value is 0). Changing the type of val to int also results in a 0 for the larger numbers. I've tried several different solutions from various answers here on SO and haven't been successful yet.
Here's what I do know:
*
*I'm using HP's C++ compiler on OpenVMS (using, I believe, an Itanium processor).
*sizeof(int) will be at least 4 on every architecture my code will run on.
*Casting from a number > INT_MAX to int is implementation-defined. On my machine, it usually results in a 0 but interestingly casting from long to int results in INT_MAX when the value is too big.
This is surprisingly difficult to do correctly, or at least it has been for me. Does anyone know of a portable solution to this?
Update:
Changing static_cast to reinterpret_cast results in a compiler error. A comment prompted me to try a C-style cast: return (int)val in the code above, and it worked. On this machine. Will that still be safe on other architectures?
A: You can negate an unsigned twos-complement number by taking the complement and adding one. So let's do that for negatives:
if (val < 0x80000000) // positive values need no conversion
return val;
if (val == 0x80000000) // Complement-and-addition will overflow, so special case this
return -0x80000000; // aka INT_MIN
else
return -(int)(~val + 1);
This assumes that your ints are represented with 32-bit twos-complement representation (or have similar range). It does not rely on any undefined behavior related to signed integer overflow (note that the behavior of unsigned integer overflow is well-defined - although that should not happen here either!).
Note that if your ints are not 32-bit, things get more complex. You may need to use something like ~(~0U >> 1) instead of 0x80000000. Further, if your ints are no twos-complement, you may have overflow issues on certain values (for example, on a ones-complement machine, -0x80000000 cannot be represented in a 32-bit signed integer). However, non-twos-complement machines are very rare today, so this is unlikely to be a problem.
A: Here's another solution that worked for me:
if (val <= INT_MAX) {
return static_cast<int>(val);
}
else {
int ret = static_cast<int>(val & ~INT_MIN);
return ret | INT_MIN;
}
If I mask off the high bit, I avoid overflow when casting. I can then OR it back safely.
A: C++20 will have std::bit_cast that copies bits verbatim:
#include <bit>
#include <cassert>
#include <iostream>
int main()
{
int i = -42;
auto u = std::bit_cast<unsigned>(i);
// Prints 4294967254 on two's compliment platforms where int is 32 bits
std::cout << u << "\n";
auto roundtripped = std::bit_cast<int>(u);
assert(roundtripped == i);
std::cout << roundtripped << "\n"; // Prints -42
return 0;
}
cppreference shows an example of how one can implement their own bit_cast in terms of memcpy (under Notes).
While OpenVMS is not likely to gain C++20 support anytime soon, I hope this answer helps someone arriving at the same question via internet search.
A: Quoting the C++03 standard, §4.7/3 (Integral Conversions):
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
Because the result is implementation-defined, by definition it is impossible for there to be a truly portable solution.
A: While there are ways to do this using casts and conversions, most rely on undefined behavior that happen to have well-defined behaviors on some machines / with some compilers. Instead of relying on undefined behavior, copy the data:
int signed_val;
std::memcpy (&signed_val, &val, sizeof(int));
return signed_val;
A: unsigned int u = ~0U;
int s = *reinterpret_cast<int*>(&u); // -1
Сontrariwise:
int s = -1;
unsigned int u = *reinterpret_cast<unsigned int*>(&s); // all ones
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Wonky Start-Process errors after the script has been running a while I have a PowerShell 2.0 script that works on large file shares from the top down, correcting permissions and such by launching another executable via Start-Process and waiting for the results and exit codes, with code like this:
Start-Process -FilePath $exe -ArgumentList $allargs -Wait -Passthru -NoNewWindow -RedirectStandardOutput $tempoutputfile -RedirectStandardError $temperrorfile;
The script will work great for a few hours, processing thousands of entries, and then eventually it will start giving odd errors like the following:
*
*"Start-Process : Cannot process request because the process (PID) has exited." -- So the process closed so fast that no status was returned?
*"Start-Process : This command cannot be executed due to the error: Not enough storage is available to process this command." -- There is more than 20GB free on the file share I'm working on, as well as on the system drive on the 2 different systems I've tested from (not to mention copious free RAM & virtual memory).
Note that I am using the builtin Start-Process cmdlet, not the PSCX one--but incidentally it behaves the same way (since they're both based on .NET's Process class anyway).
Note also that it doesn't look at all like a memory management problem--the PowerShell process peaks at less than 100MB working set early in the process, and never grows beyond that over hours of running.
Anyone have ideas how to stop these errors? Or, how to debug them, for that matter?
-----Solution-----
Thanks to @JPBlanc for pointing towards the following solutions:
1.) To solve the "Not enough storage is available to process this command" errors, I ran the PowerShell script on the local server which hosts the file share (rather than over the CIFS share, which is affected by some memory limitations).
2.) To solve the "Cannot process request because the process (PID) has exited" errors, I had to add additional testing of the HasExited property of the System.Diagnostics.Process object, as follows:
$ps = Start-Process -FilePath $exe -ArgumentList $allargs -Wait -Passthru -NoNewWindow -RedirectStandardOutput $tempoutputfile -RedirectStandardError $temperrorfile;
do {} until ($ps.HasExited); # wait...
$ps.ExitCode; # <-- this is what I really needed from the output
The script is now running error-free!
A: As you are running your script on a share, this can be caused by the server service running out of process memory, by a process on your system consuming memory handles and not releasing them properly, there are some test advices on this post. By the past I used to have a similar error on an application that was opening a lot of file on a share, and modifying IRPStackSize registry key seems to help.
----Edited------
As far as I understand "Cannot process request because the process (PID) has exited" is due to the fact that under Start-Process there is a [Diagnostics.Process] used and the -Wait parameter is played whithout testing if the hasexited propertie is true or false. To corect this error, I would instrument my code to discover exactly on which file this appends. For me this error is due to a particular error of your $exe called with $allargs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to measure how long the function works I am trying to compare the performance of several different algorithms. So created several functions each of them implementing different approach of solving the same task.
What was thinking to do is to create 2 Date objects before and after the function runs, and to compare them afterwords...
The issue here is that I need to modify the code for it, so maybe there another approach? Who can suggest?
A: Easy way:
Use getTimer() when you start and then check and compare when the function is done.
Example: http://wonderfl.net/c/d5WS
package
{
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.text.TextField;
public class FlashTest extends Sprite
{
private var _debugText : TextField;
public function FlashTest()
{
var timeStarted : int = getTimer();
var timeCompleted : int;
runReallyWackyFunction();
timeCompleted = getTimer();
setupDebugText("total time: " + (timeCompleted - timeStarted) + "ms");
}
private function setupDebugText(message : String) : void
{
_debugText = new TextField();
_debugText.x = 20;
_debugText.y = 20;
_debugText.textColor = 0xFFCC00;
_debugText.backgroundColor = 0x000000;
_debugText.background = true;
_debugText.autoSize = "left";
_debugText.text = message;
addChild(_debugText);
}
private function runReallyWackyFunction() : void
{
// put wacky stuff here
var testUpdates : int = 300000;
while(testUpdates--)
{
with(graphics)
{
beginFill(Math.random()*0x000000, 0.25);
drawCircle(Math.random() * stage.width, Math.random() * stage.height, 10);
endFill();
}
}
}
}
}
A: There are several ways to do this from scratch, but I would suggest trying Grant Skinner's Performance Test.
In addition to being able to test individual methods, it will allow you to set up a "Test Suite" which allows you to run tests on multiple methods multiple times, and average the results to find optimal performance.
Above, I've linked to the article explaining the newest version (2.0) instead of the download, hopefully you find this helpful. Also, he has several other entries about optimization, which are a fascinating read at worst, and invaluably helpful more often.
My favorite is his talk:
Quick as a Flash
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Do I Attach a SQL Server Express Database to a Visual Studio 2010 project? How do I do this?
*
*Attach an SQL Server Express Database to a Visual Studio project so that...
*
*my source control contains the most resent schema for the database including stored procedures (can'
t use SQL Compact Ed. because need to be able write stored procedures against the database),
*can be version controlled using TFS without using tools like Red Gate Source Control,
*can be automatically set up/updated when a developer gets the latest version of a project (using MS Build or similar build script api),
*(would be nice) can be published after entire project passes unit tests.
Is any of this possible and if so how do I do it?
A: Sounds like you want a migration framework, more than you want to store the actual database. Look into migration libraries for .Net like FluentMigrator.
A: This sounds like continuous Database Integration:
http://www.codeproject.com/KB/architecture/Database_CI.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Weak reference related exception I started getting the exception below after starting to use a class from an open source MVVM framework that uses weak references to prevent memory leaks.
This class is called PropertyObserver and is "A standardized way to handle the INotifyPropertyChanged.PropertyChanged event of other objects. This class uses weak references and the weak-event pattern to prevent memory leaks."
The trigger for the exception was quitting a WPF app, in which a ShellVm has a reference to a MasterVm which has references to multiple DetailVms, each of which holds the aforementioned PropertyObserver. The MasterVm is ultimately the consumer of the static Inflector class used to pluralize and capitalize this and that, which is where the WeakReference related exception gets thrown.
I can't say I fully understand the exception, so I guess that is the starting point. How would I start to resolve this?
System.InvalidOperationException was unhandled by user code
Message=Handle is not initialized.
Source=mscorlib
StackTrace:
at System.WeakReference.set_Target(Object value)
at System.Text.RegularExpressions.Regex.Replace(String input, String replacement, Int32 count, Int32 startat)
at System.Text.RegularExpressions.Regex.Replace(String input, String replacement)
at Inflector.Inflector.Rule.Apply(String word)
at Inflector.Inflector.ApplyRules(List`1 rules, String word)
at Inflector.Inflector.Pluralize(String word)
at Smack.Core.Lib.TextUtil.StringEx.Pluralize(String s)
at Smack.Core.Lib.TextUtil.StringEx.PluralizeWithCount[T](String s, IEnumerable`1 collection)
at Smack.Core.Presentation.Wpf.ViewModels.MasterDetailVms.GenericMasterViewModel`2.get_Status()
InnerException:
A: Will try to give a suggession, as something like this I met many years ago. To be honest I didn't find a real solution for it. First a rough one, after just change an architecture.
I'm afraid there is no other solution, then just try to call GC.Collect() on destroying object (rough solution), or just change MVVM framework.
After googling some:
Handle not initialized1
Handle not initialized2
In short this is something related to WeakReferences bug present in different versions of .NET Framework.
Good luck.
A: As noted in a comment:
The exception is actually triggered by Regex, it also uses weak refs.
The stack trace is very incomplete. Quacks like a bug in the library
code. Look for destructors being use inappropriately.
Hans Passant, Sep 29, 2011 at 19:24
And this was confirmed by the OP:
That was it, some logging line in a destructor where a value was null
Berryl, Sep 29, 2011 at 20:54
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using a
A: Using Font Extensions should solve this problem.
Once you use font extensions, then you can set the font in the text element or in the style. You will not specify pdfFontName, pdfEncoding, or isPdfEmbedded in the report. That gets specified in the font extension.
Note: In a strict interpretation, this doesn't actually answer the question. I have no idea why styles work differently from directly setting the fonts. It seems like a bug, but maybe it's unexpected yet intentional for some reason we aren't thinking of. Therefore, I started to enter this as a comment rather than an answer. But it got too long.
Regardless, this should allow you to use styles as you want to. So I expect that it will solve the heart of the problem.
Font extensions are documented in the JasperReports (and iReport) samples and documentation, so it should be pretty easy to use them once you know that you ought to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# - Add XML Namespace (xmlns) tag to document I'm creating an XML document using System.XML in C#.
I'm almost done, but I need to add some similar to the following to the top of my document:
<ABC xmlns="http://www.acme.com/ABC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" fileName="acmeth.xml" date="2011-09-16T10:43:54.91+01:00" origin="TEST" ref="XX_88888">
I need to add this just below where I have:
<?xml version="1.0" encoding="UTF-8"?>
I create this using the following code:
XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
After this I go on to create my XML document, which is finished now but I need to add this in-between.
Thanks
John
A: You can add namespace declarations to the root element of an XmlDocument like this:
document.DocumentElement.SetAttribute("xmlns", "http://default-namespace");
document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");
A: I think this is what you're after:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
XNamespace ns = "http://www.acme.com/ABC";
DateTimeOffset date = new DateTimeOffset(2011, 9, 16, 10, 43, 54, 91,
TimeSpan.FromHours(1));
XDocument doc = new XDocument(
new XElement(ns + "ABC",
new XAttribute("xmlns", ns.NamespaceName),
new XAttribute(XNamespace.Xmlns + "xsi",
"http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute("fileName", "acmeth.xml"),
new XAttribute("date", date),
new XAttribute("origin", "TEST"),
new XAttribute("ref", "XX_88888")));
Console.WriteLine(doc);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can I dynamically load the jQuery Colorbox plugin? When I try to load it runtime I keep getting the error:
Erro: uncaught exception: [Exception... "Index or size is negative or
greater than the allowed amount" code: "1" nsresult: "0x80530001
(NS_ERROR_DOM_INDEX_SIZE_ERR)" Erro: b.data(this, r) is undefined
jquery.colorbox-min.js
This is how I need to load it:
<a class="cboxElement" href="urlimg1.jpg" rel="example11111" title="title 1.">img1</a>
<a class="cboxElement" href="urlimg1.jpg" rel="example11111" title="title 1.">img1</a>
<a class="cboxElement" href="urlimg1.jpg" rel="example11111" title="title 1.">img1</a>
<input type="button" onclick="loadColorBox()" value="load it!"/>
<script>
function loadColorBox(){
$("a[rel='example11111']").colorbox();
}
</script>
Can anybody help?
Yours,
Diogo
edit----
Ok, that is the only way that works for me:
<div class="galeria_imgs">
<a class="cboxElemento" title="Me and my grandfather on the Ohoopee." href="url1" rel="galeria_img_1">link1</a>
<a class="cboxElemento" title="On the Ohoopee as a child" href="url2" rel="galeria_img_1">link2</a>
<a class="cboxElemento" title="On the Ohoopee as an adult" href="url3" rel="galeria_img_1">link3</a>
</div>
<script type="text/javascript">// <![CDATA[
$(".cboxElemento").live("click", function(){
$("<a href="+$(this).attr("href")+" rel="+$(this).attr("rel")+" />").colorbox({
open:true,
rel:'galeria_img_1',
title:$(this).attr('title')
});
return false;
});
// ]]></script>
At least it loads properly the image from href link but for some reason it’s not recognizing that it’s a gallery, I tried to force rel:'galeria_img_1' but still not working... any idea?
A: I wasn't able to reproduce your error message. As far as I could see your code looks good, you just need to add the open:true option to your colorbox settings. This option tells colorbox to open right now (when the function is called), rather than open when those links are clicked. So your function should look like this:
function loadColorBox(){
$("a[rel='example11111']").colorbox({
open: true
});
}
A: Using OnClick to load ColorBox isn't strictly necessary. The plugin has click event handling built-in and when you use it in the 'vanilla' cuse case - which you are - it assumes you what the plugin to do the even trapping.
If your use case is this: Trigger ColorBox open from an arbitrary element (button in your case) and display content from an arbitrary collection (rel="example11111" in your case) could it approach this way:
var $gallery = $('a[rel=example11111]').colorbox(); // Set the target gallery
$('button').click(function(e){ // Invoke Colorbox @ content element #1 on click of button
e.preventDefault(); // stop default action by browser
$gallery.eq(0).click(); // do a click event on the gallery to open Cbox
});
This separates the assignment of the gallery content from the event that invokes ColorBox. You could also assign an ID or class to the button element for more granular selection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CAlayer transform on sublayers flickers with gestures (ipad) I have a CALayer that contains few other subLayers (CATextLayer actually)
I want to apply some transformation on that layer when user do usual gesture on the ipad but it doesn't seem to be working properly. The goal of using the CALayer was to apply the transformation only to that Layer so that all of my sub-textLayer would be affected at the same time with the same transformation.
What's happening is that the transformation seem to flicker between previous and current position. I don't really get what could be the problem... When I do a 2 fingers panning gesture for example, CaTextLayer positions flickers all the time during my gesture and at the end they are all correctly placed at their new translated position.
So everything seems to work fine except that flickering thing that is bothering me a lot.
Do I need to set some property I don't know about ? I'm thinking it might have something to do with bounds and frame too....
Here's how I create my CATextLayer (This is done only once at creation and it works properly):
_textString = [[NSString alloc] initWithString: text];
_position = position;
attributedTextLayer_ = [[CATextLayer alloc] init];
attributedTextLayer_.bounds = frameSize;
//.. Set the font
attributedTextLayer_.string = attrString;
attributedTextLayer_.wrapped = YES;
CFRange fitRange;
CGRect textDisplayRect = CGRectInset(attributedTextLayer_.bounds, 10.f, 10.f);
CGSize recommendedSize = [self suggestSizeAndFitRange:&fitRange
forAttributedString:attrString
usingSize:textDisplayRect.size];
[attributedTextLayer_ setValue:[NSValue valueWithCGSize:recommendedSize] forKeyPath:@"bounds.size"];
attributedTextLayer_.position = _position;
This is how I add them to my Super CALayer
[_layerMgr addSublayer:t.attributedTextLayer_];
[[_drawDelegate UI_GetViewController].view.layer addSublayer:_layerMgr];
And here's how I apply my transformation :
_layerMgr.transform = CATransform3DMakeAffineTransform(_transform);
A: After lots of reading and testing...I've found my own solution.
It looks like the CoreAnimation uses default animation when you do transformation or operation on any layers. It's very recommended that when you do such CALayer operation that you go through what they call "Transactions".
I've found all about that in the CoreAnimation Programming guide, under the section : transactions.
My solution was then to implement such a transaction, and preventing any animation while doing CALayer operation.
This is what I do when applying my transformation (which prevents flickering) :
-(void)applyTransform
{
if (! CGAffineTransformIsIdentity(_transform))
{
[CATransaction begin];
//This is what prevents all animation during the transaction
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
_layerMgr.transform = CATransform3DMakeAffineTransform(_transform);
[CATransaction commit];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Out-of-band OAuth authentication with Facebook TL;DR version:
Can you authenticate with Facebook without having a callback URL for a web application since the web application isn't actually running on a server.
Full explanation:
I'm working on building a connectedTV platform application where the "app" itself is a bunch of HTML/JS/CSS running locally (like File -> Open on your desktop browser) and I'd like to integrate Facebook into this.
The problem is that all of Facebook's OAuth calls for the web require you to have a callback URL to redirect the user to in order to complete authentication. Here's the gotcha -- there is no URL for this application -- it's a locally running webpage on the device.
I know this is what out-of-band authentication was designed for, but I can't seem to find any documentation on how to use this (or how to do a non-callback OAuth flow) with the Facebook OAuth system.
A: You're describing desktop authentication or any situation where you are authenticating to FB without a server. The redirect URL you pass to the OAuth dialog is https://www.facebook.com/connect/login_success.html When the browser redirects you can get the access token. You can read all about it in the FB documentation, way at the bottom in the Desktop Apps section (https://developers.facebook.com/docs/authentication/)
Just reread your question and since the application runs inside a browser you will need to open another window to authenticate and get the access token from that.
A: If you're doing HTML/Javascript, use their Javascript SDK. You can log the guy in simply by using FB.login and getting the access token from the callback from that.
A: I really don't think this is directly possible. Unless there is something totally undocumented, Facebook has no mechanism to send authentication data except by loading a url. I'm sure it's meant at least partly as a security measure, functioning as sort of a "whitelist" of where auth data will be sent.
The only way I can think of for you to work around it might be to set up a url on a server somewhere that could answer the redirect and store the auth data, and have your client-side code poll that server to get it. Kind of a proxy authentication service, in effect. You would probably have to open a second browser window with the Facebook auth screen in it, but in theory it could work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: table sorter with combined two rows jQuery table sorter with combined rows
Every second row contains detail data for the first row. By default, it is hidden with CSS, but I can slide it open with jQuery.
What I would like to achieve: Table sorting similar to this jQuery plugin: http://tablesorter.com/docs/
The problem: The plugin should "glue together" all pair rows, and move them together. The sorting should be done only with the data of the first row (.row-vm), while ignoring the content of the second row (.row-details).
Is there a jQuery plugin that supports this?
<tr class="row-vm">
<td>...</td>
<td>...</td>
...
</tr>
<tr class="row-details">
<td colspan="6">
Description data
</td>
</tr>
<tr class="row-vm">
<td>...</td>
<td>...</td>
...
</tr>
<tr class="row-details">
<td colspan="6">
Description data
</td>
</tr>
A: So i'm not sure how well documented this was but i found what i think you are looking for in the table object.
Check out this fiddle
It looks like you can add a class of expand-child. Or you can pass in your own class name
$("table").tablesorter({
cssChildRow: "row-details"
});
A: We have the same issue and found a workaround. I pass the class name that I have set on the 2nd row. Just add one of the code below :
$(document).ready(function()
{
$("tableName/ID/classname").tablesorter({
cssChildRow: "tableName/ID/classname"
});
}
);
or
$("tableName/ID/classname").tablesorter({
cssChildRow: "tableName/ID/classname"
});
A: i'm using datatables, take a look and see if helps you
examples: http://datatables.net/examples/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Get value of nth item in an un-ordered list For this code,
<ul id="date-list" hidden="hidden">
<% foreach (string item in (List<string>)Model.OpenCloseTime)
{%>
<li value="<%= item %>"><%= item %></li>
<% }%>
</ul>
How could i get the value of nth item in the list. It is an MVC project and we are using jquery.
Basically I am trying to use the string value as a min max time for an input of type="time".
Thanks!
A: var found = $('#date-list').find('li').eq(n).text()
A: Here you go:
$( '#date-list' ).children().eq( n ).text()
A: $('#date-list').children().eq(n).attr('value');
However, if you want a custom data attribute, html5 states you should precede it with data-
<li data-value="<%= item %>"><%= item %></li>
$('#date-list').children().eq(n).data('value');
A: $('#date-list>li:nth-child('+n+')'.attr('value');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Looping through annotate query Initially I asked this question, and I wanted to give credit to Daniel. Here is the new issue I have however.
I have this which works great, but I'm having a minor issue.
total_list = plan.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution').annotate(Sum('maturity_amount'))
I'm having trouble displaying the financial institution name. When I loop through total list and put loop_variable.financial_institution it shows me the ID but not the name.
Any ideas on how to fix this?
A: Assuming that the "financial_institution" model has a name field, I think you could just add it to the list of values you're asking for:
total_list = plan.investment_set.filter(
maturity_date__gte= '%s-1-1' % current_year
).values(
'financial_institution',
'financial_institution__name'
).annotate(Sum('maturity_amount'))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: python: difference of two timedate strings I have two date strings (taken from user input and can vary greatly)
s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'
I wish to find the difference between the two as minutes.
How should I proceed to tackle this ?
A: import datetime
d1 = datetime.datetime.strptime('2011:10:01:10:30:00', '%Y:%m:%d:%H:%M:%S')
d2 = datetime.datetime.strptime('2011:10:01:11:15:00', '%Y:%m:%d:%H:%M:%S')
diff = (d2 - d1).total_seconds() / 60
If you need to handle arbitrary datetime formats, I don't believe the built in datetime library will do that for you. Perhaps check out something like:
http://www.egenix.com/products/python/mxBase/mxDateTime/
A: Using the datetime module, parse into a datetime object using strptime, then subtract. You'll get a timedelta. Then use timedelta.total_seconds() and divide by 60.
A: Use datetime to parse the string and convert into a base epoch time. Do the math. Convert back:
>>> from datetime import datetime
>>> s1 = '2011:10:01:10:30:00'
>>> s2 = '2011:10:01:11:15:00'
>>> d1=datetime.strptime(s1,'%Y:%m:%d:%I:%M:%S')
>>> d2=datetime.strptime(s2,'%Y:%m:%d:%I:%M:%S')
>>> d2-d1
datetime.timedelta(0, 2700)
>>> (d2-d1).total_seconds()/60
45.0
If you are looking for arbitrary date string parsing, check out DateUtil and the parse function.
A: The time module can be helpful for this.
import time
s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'
s1Time = time.strptime(s1, "%Y:%m:%d:%H:%M:%S")
s2Time = time.strptime(s2, "%Y:%m:%d:%H:%M:%S")
deltaInMinutes = (time.mktime(s2Time) - time.mktime(s1Time)) / 60.0
print deltaInMinutes, "minutes"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Style BasedOn a user-defined style I have a DefaultStyle and then another Style defined like this
<Style TargetType="{x:Type my:CustomButton}" BasedOn="{StaticResource DefaultStyle}" x:Key="DefaultCustomButton"> ...
Then, having defined this style, I have
<Style TargetType="{x:Type my:CustomButton}" BasedOn="{StaticResource DefaultCustomButton}" />
No problem, so far.
Now, I wanted to reuse a good part of that second style, so I defined the following:
<Style TargetType="{x:Type my:CustomToggleButton}" BasedOn="{StaticResource DefaultCustomButton}" x:Key="DefaultToggleButton"> ...
and then
<Style TargetType="{x:Type my:CustomToggleButton}" BasedOn="{StaticResource DefaultToggleButton}" />
Finally, I used the new button in a window:
<my:CustomToggleButton x:Name="measurableButton">Text Goes Here</my:CustomToggleButton>
At that point, I get this error:
"Cannot convert the value in attribute 'BasedOn' to object of type
'System.Windows.Style'. Can only base on a Style with target type
that is base type 'CustomToggleButton'.
Anything obvious? Does CustomToggleButton have to derive from CustomButton?
A: See the note (in yellow down the page a bit) here: http://msdn.microsoft.com/en-us/library/system.windows.style.basedon.aspx
So your CustomToggleButton must derive from CustomButton. I'm assuming (now) based on the error that it does not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Threading a shell script I have a small shell script that executes ~30 Java commands consecutively. Each one pulls data from a MySQL db then jams it into a BI tool. Is there any way to execute >1 of these commands from within said shell script? Unfortunately, I only have access to the script itself, I cannot change the frequency or method of execution.
THANKS
A: Generally, a construct like this:
command_1 &
command_2 &
command_3 &
# ...
wait
will run all of the commands with & at the end in parallel, and then wait for all of them to finish before continuing. Without knowing more about what these commands look like, I can't be more specific.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Validating an XML NCName in Java I'm getting some values from Java annotations in an annotation processor to generate metadata. Some of these values are supposed to indicate XML element or attribute names. I'd like to validate the input to find out if the provided values are actually legal NCNames according to the XML specification. Only the local name is important in this case, the namespace URI doesn't play a part here.
Is there some simple way of finding out if a string is a legal XML element or attribute name? Preferably I'd use some XML API that is readily available in Java SE. One of the reasons I'm doing this stuff in the first place is to cut back on dependencies. I'm using JDK 7 so I have access to the most up-to-date classes/methods.
So far, browsing through content handler classes and SAX/DOM stuff hasn't yielded any result.
A: If you're prepared to have Saxon on your class path you can do
new Name10Checker().isValidNCName(s);
I can't see anything simpler in the public JDK interface.
A: didn't find anything straightforward in any of the jdk 6 APIs (don't know about jdk 7). a quick but possibly "hackish" way to check would be to convert it to an xml doc and see if it parses:
String name = ...;
if(name.contains(">")) {
return false;
}
String xmlDoc = "<" + name + "/>";
DocumentBuilder db = ...;
db.parse(new InputSource(new StringReader(xmlDoc)));
A: I ran into the same problem and found lots of implementations in foss libraries, and even an old implementation in a Java class library, which has been removed ages ago... So here's a few options to choose from:
*
*Java Class Library: XMLUtils.isValidNCName(String ncName) (note: removed in 2004)
*Apache Axis: NCName.isValid(String stValue)
*Saxonica: NameChecker.isValidNCName(CharSequence ncName)
*OWL API: XMLUtils.isNCName(java.lang.CharSequence s)
*Validator.nu HTML Parser: NCName.isNCName(java.lang.String str)
So, if you're using one of these libraries anyway, you're fine.
As I am not, I'll go with a copy of the XMLUtils from the OWL API, which has no external dependencies, is available under non-restrictive licenses (LGPL and Apache 2.0) and consists of nice and clean code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: ASP.NET MVC Exclude Namespaces from New View Model Dropdown Menu When you add a new view to an ASP.NET MVC project you can strongly type the view by selecting which model class it should work with in the dialog box. The problem is in that drop down menu it includes all the classes and interfaces from all referenced projects and dlls. So, I see all the Ninject classes, all the interfaces for my services, etc in that menu. Is there any way to specify which namespaces to include or a list of namespaces to exclude from that drop down menu?
I realize that this is not a big deal and you can just start typing the name of the class in the box and it will pull up the right one. I just thought that if there was a place for this it would be nice. If there isn't, no big deal but I thought I would ask. :)
A: If you really really want this and you are cool with some hacking, try this :)
c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Microsoft.VisualStudio.Web.Mvc.3.01.dll
decompile it - you will find MvcAddViewDialog class, and the GetTypes method in it. Put some filtering in it, recompile, replace, enjoy... but personally, I probably wouldnt :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: TSAlertView not responding to delegate? TSAlertView is TomSwift's https://github.com/TomSwift/TSAlertView/ solution to present modal views that look like UIAlertView but fully customizable. Good work!
However I fail to respond to button press in the modal dialog. I set up my viewcontroller as delegate, but there is simply no reaction.
In my own ViewController I write
@interface MyViewController : UIViewController <TSAlertViewDelegate> {
and then I implement
-(void) alertView: (TSAlertView *) alertView didDismissWithButtonIndex: (NSInteger) buttonIndex {
NSLog(@"inside");
}
but it never gets called. It seems like
[self.delegate alertView: self didDismissWithButtonIndex: buttonIndex ];
in TSAlertView.m has no effect.
Also there is no code about this in the Demo. Anybody ever looked at TSAlertView? Figured out how to be delegate for the buttons? Thanks!
A: TSAlertView works pretty much the same way as a normal UIAlertView. Are you sure you're setting the delegate?
Here's a sample code on how I was using it, with all the delegate methods getting called as expected:
TSAlertView *aView = [[TSAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
// <customize alertview>
[aView show];
[aView release];
You can add a breakpoint in - (void) dismissWithClickedButtonIndex: (NSInteger)buttonIndex animated: (BOOL) animated (in TSAlertView.m) and see what goes wrong and check if the delegate was set correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does ASP.NET load the wrong version of my web application assembly? I have a web application in Visual Studio 2008 with a web service and a couple web forms. When I try to debug, none of my breakpoints are available; if I mouse over them, I see:
"The breakpoint will not be hit. The source code is different than the original version."
The list of loaded debug modules includes the old version 1.0.* of my assembly. I have since changed it to 1.1.0.0 but that version never gets loaded. I tried stopping IIS and deleting the files out of Temporary ASP.NET Files, but when I restart it the 1.0.* version comes right back! The build output is definitely 1.1.0.0 and not 1.0.*, so where can it possibly be coming from? The same thing happens when I use the VS Development Server instead of IIS.
Thanks
A: I've seen this happen when the DLL is cached in the Temporary ASP.NET Files folder. Try doing a "Rebuild All", and if it's still happening remove the DLL from the temp folder, or clear the folder contents altogether.
A: I had a very similar problem:
*
*Web application referencing assembly containing resources.
*When using non-default culture (one with resources build into satellite *.resources.dll assembly), some of the resources were used ok but some falling back to default languagage.
*Deleting Temp ASP.NET files or Clear\Build didnt help
Problem is that most of the tools you can use for diag assembly loading problems (Process Explorer for list of loaded assemblies and paths, fuslogvw for assembly binding log) don't show satellite assemblies at all.
But finally i found that there is old version of the satellite assembly right in my web app bin folder (still dont know how it get there) and it was getting priority during assembly probing\loading...
A: It looks like this is triggered when a files LastWriteTime does not update. I can reliably reproduce this by taking two completely separate builds of a dll, with the exact same LastWriteTime, and deploying them into IIS one after another. If I then use GNU touch to update the files LastWriteTime, IIS picks up the current correct version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Where is the proper location to embed IV information for file encryption using Rijndael algorithm? I'm creating a Rijndael file encryption application. I will using a unique IV for each file encryption.
My question: Where is the proper place to embed the IV info?
My initial thought is to append it at the end of the file's content. Is that a good choice? Any other better option for me?
A: At the beginning of the file makes more sense (the reader will need it before reading the rest).
But yes, you can safey add it to the output. The IV (and maybe a Salt) is not a secret.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Adding stuff to the navigation bar I want to add some stuff to the navigation bar (like Heading and some buttons like back or home, a shopping cart and a Youtube ENDO channel) at the top of the view. But navigation bar is not visible in the nib file. That can be done through some coding stuff. So, how can I add them to navigation bar??
Please help
regards
Prateek
A: You need to add your view controller to a UINavigationController first. There are two scenarios:
Either, from your root controller. Just look at the template "Navigation based Application" in Xcode / New Project for how to do this. Most things just happen automatically. When you push a view controller, it should already have a navigation bar. Also, you will find it in your xib file.
Or, from another view controller that is not part of a navigation controller. Before pushing it, "wrap" it into a navigation controller like this:
MyViewController *controller = [[MyViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc]
initWithRootViewController:controller];
[self presentModalViewController:nav animated:YES];
[controller release];
[nav release];
Now you can add to self.navigationController.navigationBar to your heart's content.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Lightbox as Part of a Distributed Code Snippet I have been tasked with creating a code snippet that will be distributed to multiple websites for inclusion in their HTML. This code snippet will render a button, that when pressed will launch a lightbox that contains an iframe with content from a central website.
My thought is to use jQuery with a Lightbox Plugin (colorbox for example) however the websites including this code snippet may have an older (or newer) version of jQuery or a different framework already included which will most likely cause problems.
My questions is; how would one include jQuery in a website in a way that would not interfere with other versions of jQuery or other frameworks?
Also, is this even the best way to approach this? Is there a Javascript Lightbox out there that doesn't use a framework?
Any help would be greatly appreciated!
A: Well, generally speaking, adding more than one js library to a page hurts performance. That goes for adding more than one version of a library, too. On each and every page load JQuery (and other libraries) must run quite a few test just to know which part of its own code to run (and for each version). Most of the time you don't notice it, but after adding a second library it may become an issue.
That said, running multiple versions of jQuery is easy. Set the newer version of jQuery to noconflict mode while giving it a different name (jquery let's you rename it's $ to whatever you want), such as $j2 or whatever (just make sure it's something compatible). Also, it I believe it has to be included before the older version so as not to conflict before it goes into noconflict mode. Then you put this line in a script tag immediately after you've included the newer jquery code:
<script type='text/javascript'>
var $j2 = jQuery.noConflict();
</script>
You would load the second version of jQuery normally. Any subsequent calls to your newer jQuery would look something like:
$j2("myDiv")
Personally, I am a big fan of colorbox. I feel that it is the best out there right now. It's fast, versatile, and rebrandable. So with the ability to change both the jQuery name and the colorbox name, you could make calls to colorbox look like this:
$ourBiz.fantasyBox({settings:etc});
Of course, if your customers don't look at the code they won't notice it, but it looks cool, eh? I would try that first, you may find that the performance hit of a second library is not even noticable.
If you do notice a performance hit, you might want to try one of these:
*
*Lightbox JS - one of the original lightboxes. Note that there is a Lightbox 2 from the same author, but this uses Prototype & Scriptaculous
*HighSlide
*Floatbox
*TinyBox - this one is not quite as versatile as most but it's fast, so for popups with single images or inline content, its a good choice
A: Just include jQuery and use the noConflict() method. Example
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="http://leandrovieira.com/projects/jquery/lightbox/js/jquery.lightbox-0.5.pack.js"></script>
<link rel="stylesheet" href="http://leandrovieira.com/projects/jquery/lightbox/css/jquery.lightbox-0.5.css">
<script>
jQuery.noConflict()(function($){
$('a').lightBox();
});
</script>
If the client asks for optimizations well that is a another story.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Search and Replace Strings in a Text File Using Wildcards Trying to do a search/replace in python using wildcards on the contents of a text file:
If the contents of the text file looks like:
"all_bcar_v0038.ma";
"all_bcar_v0002.ma";
"all_bcar_v0011.ma";
"all_bcar_v0011.ma";
Looking to replace all the version numbers with v1000 to get this:
"all_bcar_v1000.ma";
"all_bcar_v1000.ma";
"all_bcar_v1000.ma";
"all_bcar_v1000.ma";
And have the file written out.
I've tried the below but what happens is the script only catches the first version number, leaving the others untouched:
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
rigs = ['all_bcar']
rigs_latest = ['all_bcar_v1000']
old_pattern = []
old_compiled = []
old = []
old_version = []
for rig in range(len(rigs)):
old_pattern.append("/" + rigs[rig] + "_(.*).ma")
fin = open(txt_file, "r")
old_compiled.append(re.compile(old_pattern[rig]))
old.append(old_compiled[rig].search(fin.read()))
old_version.append(old[rig].group(1).strip())
old_rig = (rigs[rig] + "_" + old_version[rig])
replaceAll(txt_file,old_rig,rigs_latest[rig])
fin.close()
Not sure how to keep the search looping to find other versions and to avoid the versions that have already been replaced, to skip any versions that equal "v1000".
A: Your life would be vastly improved with the use of regexes. You should be able to do this in 2 lines (assuming I understand the problem correctly):
import re
for line in fileinput.input(file, inplace=1):
re.sub(r"_v\d{4}", "_v1000", line)
A: Try -
import re
re.sub("_v\d{4}", "_v1000.", string)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do chained assignments work? A quote from something:
>>> x = y = somefunction()
is the same as
>>> y = somefunction()
>>> x = y
Question: Is
x = y = somefunction()
the same as
x = somefunction()
y = somefunction()
?
Based on my understanding, they should be same because somefunction can only return exactly one value.
A: It would result in the same only if the function has no side-effects and returns a singleton in a deterministic manner (given its inputs).
E.g.:
def is_computer_on():
return True
x = y = is_computer_on()
or
def get_that_constant():
return some_immutable_global_constant
Note that the result would be the same, but the process to achieve the result would not:
def slow_is_computer_on():
sleep(10)
return True
The content of x and y variables would be the same, but the instruction x = y = slow_is_computer_on() would last 10 seconds, and its counterpart x = slow_is_computer_on() ; y = slow_is_computer_on() would last 20 seconds.
It would be almost the same if the function has no side-effects and returns an immutable in a deterministic manner (given its inputs).
E.g.:
def count_three(i):
return (i+1, i+2, i+3)
x = y = count_three(42)
Note that the same catches explained in previous section applies.
Why I say almost? Because of this:
x = y = count_three(42)
x is y # <- is True
x = count_three(42)
y = count_three(42)
x is y # <- is False
Ok, using is is something strange, but this illustrates that the return is not the same. This is important for the mutable case:
It is dangerous and may lead to bugs if the function returns a mutable
This has also been answered in this question. For the sake of completeness, I replay the argument:
def mutable_count_three(i):
return [i+1, i+2, i+3]
x = y = mutable_count_three(i)
Because in that scenario x and y are the same object, doing an operation like x.append(42) whould mean that both x and y hold a reference to a list which now has 4 elements.
It would not be the same if the function has side-effects
Considering a print a side-effect (which I find valid, but other examples may be used instead):
def is_computer_on_with_side_effect():
print "Hello world, I have been called!"
return True
x = y = is_computer_on_with_side_effect() # One print
# The following are *two* prints:
x = is_computer_on_with_side_effect()
y = is_computer_on_with_side_effect()
Instead of a print, it may be a more complex or more subtle side-effect, but the fact remains: the method is called once or twice and that may lead to different behaviour.
It would not be the same if the function is non-deterministic given its inputs
Maybe a simple random method:
def throw_dice():
# This is a 2d6 throw:
return random.randint(1,6) + random.randint(1,6)
x = y = throw_dice() # x and y will have the same value
# The following may lead to different values:
x = throw_dice()
y = throw_dice()
But, things related to clock, global counters, system stuff, etc. is sensible to being non-deterministic given the input, and in those cases the value of x and y may diverge.
A: Left first
x = y = some_function()
is equivalent to
temp = some_function()
x = temp
y = temp
Note the order. The leftmost target is assigned first. (A similar expression in C may assign in the opposite order.) From the docs on Python assignment:
...assigns the single resulting object to each of the target lists, from left to right.
Disassembly shows this:
>>> def chained_assignment():
... x = y = some_function()
...
>>> import dis
>>> dis.dis(chained_assignment)
2 0 LOAD_GLOBAL 0 (some_function)
3 CALL_FUNCTION 0
6 DUP_TOP
7 STORE_FAST 0 (x)
10 STORE_FAST 1 (y)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
CAUTION: the same object is always assigned to each target. So as @Wilduck and @andronikus point out, you probably never want this:
x = y = [] # Wrong.
In the above case x and y refer to the same list. Because lists are mutable, appending to x would seem to affect y.
x = [] # Right.
y = []
Now you have two names referring to two distinct empty lists.
A: As already stated by Bob Stein the order of assignment is important; look at the very interesting following case:
L = L[1] = [42, None]
Now, what does contain L? You must understand that a single object being initially [42, None] which is assigned to L; finally, something like L[1] = L is performed. You thus have some cyclic infinite "list" created (the word "list" being here more similar to some CONS in Lisp with a scalar 42 being the CAR and the list itself being the CDR).
Just type:
>>> L
[42, [...]]
then have some fun by typing L[1], then L[1][1], then L[1][1][1] until you reach the end...
Conclusion
This example is more complicated to understand than other ones in other answers, but on the other hand, you can see much quicker that
L = L[1] = [42, None]
is not the same as
L[1] = L = [42, None]
because the second one will raise an exception if L is not previously defined while the first one will always work.
A: They will not necessarily work the same if somefunction returns a mutable value. Consider:
>>> def somefunction():
... return []
...
>>> x = y = somefunction()
>>> x.append(4)
>>> x
[4]
>>> y
[4]
>>> x = somefunction(); y = somefunction()
>>> x.append(3)
>>> x
[3]
>>> y
[]
A: In
x = somefunction()
y = somefunction()
somefunction will be called twice instead of once.
Even if it returns the same result each time, this will be a noticeable if it takes a minute to return a result!
Or if it has a side effect e.g. asking the user for his password.
A: What if somefunction() returns different values each time it is called?
import random
x = random.random()
y = random.random()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
}
|
Q: What is causing the bottleneck in this scenario? I'm looking for some help with a production issue we have encountered.
We have an NServiceBus Handler that when it processes a message sends a request to an asmx (.net 2.0) webservice running on IIS 6.0, the web service then sends a second http request to a 3rd Party web service, on average the 3rd party service takes 500ms to respond but we have been told will only start queing requests when 11 simultaneous requests are in progress.
To meet our processing SLA's we need to be able to process 79,000 messages an hour or ~ 1300 messages a minute. With 11 requests being processed in parallel and taking an average of 500 ms this should be achievable if we can get eleven concurrent requests firing, every second we should be able to process about 20 messages.
The problem we have is that we cannot get anywhere near these figures. Our deployed solution is as follows. We have a service that polls a database every
5 seconds to retrieve a batch of 100 new messages, it sends them to a distributor which load balances accross four worker windows services running on two servers. I'll call them NsbServerA & NSbServerB. Each worker service is configured with 2 threads so we have 8 threads in total. We have two servers runing the asmx web services I'll call the asmx1 & asmx2, ServerA sends requests to asmx1 and ServerB sends requests to asmx2.
The current throughput is 30,000 messages per hour, ~500 per min, ~8 per second so somewhere we have a bottle neck the question is where?
I have seen this article http://support.microsoft.com/default.aspx?scid=kb;en-us;821268 which seems to indicate that you have to tune the IIS 6.0 process model if you want to make more than a few of concurrent calls to the same webservice.
Quote from the article:
"If you are making one Web service call to a single IP address from each ASPX page, Microsoft recommends that you use the following configuration settings:
Set the values of the maxWorkerThreads parameter and the maxIoThreads parameter to 100.
Set the value of the maxconnection parameter to 12*N (where N is the number of CPUs that you have).
Set the values of the minFreeThreads parameter to 88*N and the minLocalRequestFreeThreads parameter to76*N.
Set the value of minWorkerThreads to 50. Remember, minWorkerThreads is not in the configuration file by default. You must add it."
If anyone can shed some light on what is happening or what the solution is I would be really grateful.
Thanks,
Charlie
A: One likely possibility:
The ServicePointManager, through which all your .NET Web requests are routed, has a default of two concurrent connections per object. See ServicePointManager.DefaultConnectionLimit.
So if your 3rd party Web service takes an average of 500 ms to respond, a single server can only do four requests to that service every second. (i.e. two concurrent requests every 500 ms).
Multiply that by two servers and you get your ~8 messages per second.
Try setting ServicePointManager.DefaultConnectionLimit = 4; when you start your program, and see if that increases your throughput.
A: Sounds like it could be many things.
*
*Are you using the commercially available Standard Edition of NServiceBus? Without that your handler will work single threaded.
*Is your mid-tier web service asynchronous? If the second service round trip is made synchronously then a thread will be tied up and unable to process incoming requests.
*Have you configured sufficient worker threads to process incoming requests? UPDATE: See this page http://msdn.microsoft.com/en-us/library/ff647787.aspx#scalenetchapt06_topic9 ("Table 6.1: Recommended Threading Settings for Reducing Contention") for high throughput recommendations. The settings you should look at are minFreeThreads, maxconnection, maxWorkerThreads, minWorkerThreads.
I would be nervous committing to a throughput SLA of 20 messages per second if you cannot reliably achieve this without massive optimization.
Also probably a stupid question but why can't you call the remote service from your message handler directly?
A: I would suggest testing each layer of the system in isolation.
Specifically, first discount the database tier as an issue. I'd put together some simple integration-style unit tests that exercise the peak throughput of the database, ideally by using something like Parallel.ForEach to run a few hundred threads concurrently.
Then move up a layer and use something like a stub to "mock out" the database calls and verify that the service tier is behaving as it should.
Then at least you'll be able to narrow down the inefficiencies and deal with them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Implement chat functionality like words with friends on ios I want to add chat functionality to an iOS app similar to what Words With Friends has. Are there any libraries that I can piggy back on or do I need to write it from scratch?
I got a couple of ideas, but all seem expensive:
- Build simple chat client server from scratch
- Host XMPP server and build XMPP functionality into client
- Piggyback on Google Talk or Facebook Chat
-- Facebook Chat XMPP protocol doesn't support group chat which I need
-- Not enough people use google
A: Unfortunately, you will have to write it from scratch. I've written an group chat in the app store and I suggest XMPP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to add 'show/hide content' option in a webpage in html? though there are many codes available, but i want the simplest and shortest code for an option for show/hide content.( it would be good if the text 'show/hide' can be replaced by an image for the same or by a button)
A: If you have an element with id="myElem", you can do:
elem=document.getElementById("myElem");
elem.style.display = "none";
and to show it:
elem.style.display = "";
A: If you don't mind a library dependency - jquery can achieved this with
$("#myelm").toggle();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why can't the maven-deploy-plugin resolve my custom system property? I'm using the gmaven-plugin to set a custom system property in my POM. This seems to work, as I'm able to successfully echo the property using the maven-antrun-plugin; however, the maven-deploy-plugin seems completely unaware of the property and is unable to resolve it.
Relevant portion of the POM:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
System.setProperty("nodotsversion", "${env.PATCH_VERSION}".replace('.', ''))
</source>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.6</version><!-- 1.2 in central -->
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<configuration>
<target>
<echo message="${nodotsversion}" />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.6</version>
<goals>
<goal>deploy-file</goal>
</goals>
<configuration>
<repositoryId>artifactory</repositoryId>
<packaging>sql</packaging>
<generatePom>true</generatePom>
<url>${project.distributionManagement.snapshotRepository.url}</url>
<groupId>com.company.product</groupId>
<artifactId>patch${nodotsversion}</artifactId>
<version>1.0.0-SNAPSHOT</version>
<file>${WORKSPACE}/myfile.sql</file>
</configuration>
</plugin>
</plugins>
</build>
When I run this with mvn clean install deploy:deploy-file, I get the following error:
Caused by: org.apache.maven.plugin.MojoExecutionException: The artifact information is incomplete or not valid:
[0] 'artifactId' with value 'patch${nodotsversion}' does not match a valid id pattern.
Why is the maven-antrun-plugin able to resolve my custom system property, while the maven-deploy-plugin is not?
A: I'm not sure, but I believe that the ${...} placeholder syntax can only resolve project properties. I believe the system properties are added to the project properties at a point in the build, which is why system properties are available in this way, but a system property added later in the build won't be available. You should add the property to the project properties instead.
A: I'm not sure how this is related, but I recently figured out a problem I was having using the ${...} syntax and the gmaven-plugin. In my plugin I was generating a finalName for the build. This part of the pom looks like:
<build>
<finalName>${my.final.name}</finalName>
Then, in the maven <source> section I had something like:
def myvar = "prefix${someothervar}suffix"
project.properties['my.final.name'] = myvar
The pom was for a war. When I ran maven, the output was always:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project myservice: The parameters 'warName' for goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war are missing or invalid -> [Help 1]
After much head scratching I finally figured out how to solve the problem. myvar needed to be declared as a String!
String myvar = "prefix${someothervar}suffix"
project.properties['my.final.name'] = myvar
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it any methods in GWT to get screenshot of page region? I am using GWT. I have a set of dragable widgets that can be placed on page as user wants. I need to get page region screenshot as a handler of some event and save it. Is any way to do this?
Is it possible to get Widget view as an image in GWT?
A: You will have to create applet to get screenshots. You can embed the applet in your GWT application/
A: No. Sorry. You cannot get a screenshot of any page region in any browser, for security reasons.
There is one exception, drawWindow which is not part of GWT but part of HTML5 Canvas and only works in firefox, and only locally (not allowed to run on normal webpages).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: swfobject.embedSWF doesn't do anything. What am i missing? I am experimenting with with swfObject to embed a flash video player on my site. here is some snippets of my code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
if (typeof ARI == 'undefined')
{
ARI = {};
}
ARI.InsertFlash = function()
{
var flashvars = {};
var parameters = {};
parameters.quality = 'high';
parameters.play = 'true';
parameters.LOOP = 'false';
parameters.wmode = 'transparent';
parameters.allowScriptAccess='true';
var attributes = {};
attributes.id='ARIVID';
swfobject.embedSWF("AS3MediaPlayer.swf","inlieu","720","405","9.0.0","",flashvars,parameters);
}
</script>
...
<body>
<div class='inlieu'>
<p> this will be replaced</p>
</div>
<button type='button' onclick='ARI.insertFlash();'>Insert</button>
This does nothing. my button does hit the correct function (please excuse any html errors that might be on the page). I've tested that with a div. The function itself does fire, but my div doesn't get replaced. What am I missing here? I want to embed a flash object that uses external interface, so any answers to my question that keeps that in context would be helpful. Also i want this to fire when a user pushes the button, not on page load, like most of the examples on the internet show.
thanks
Ari
A: SWFObject requires an ID on the target element, You're using a class. Change class='inlieu' to id='inlieu'
Also, since you're specifying an ID in the attributes, your new object will have the ID ARIVID and will NOT inherit the ID inlieu
This
<body>
<div id='inlieu'>
<p> this will be replaced</p>
</div>
<button type='button' onclick='ARI.insertFlash();'>Insert</button>
will become this
<body>
<object id="ARIVID" ... ></object>
<button type='button' onclick='ARI.insertFlash();'>Insert</button>
A: um you are loading swfobject from http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js
Put the file in the same domain as your swf/html and your issue should go away.
Aside from trying to steal bandwidth you have no reason to loading from google and this can cause you version issues, if they decide to update that code base with something new.
Also you should be calling that function onLoad or from a button click as you stated. The code you posted is running before the page is finished loading and that javascript file from google may not be loaded yet.
You can test this by putting this code right before the embed statement.
alert( swfobject );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: F# Create list of multiples of x? I want to create a list that is the multiples of a number. For example [2; 4; 6; 8; 10] would be the multiples of 2 between 0 and 10.
How would I dynamically create such a list of the multiples of x? Is it possible to do it without setting an upper bound?
One way to do it would be to create a list between 0 and some crazy large number and then filter it using the mod function. Trying to test this, creating a list of 0 to some crazy large number caused an out of memory exception (after a 30 second or so wait).
I feel like F# has some super simple and awesome way to build such a list but I'm too much of a newb to know what it is, yet. Help?
A: Sequences (IEnumerables) give the laziness you want here:
let multiplesOfN n =
seq {
for i in 1 .. 1000000 do
yield i * n
}
let first6multsof3 =
multiplesOfN 3 |> Seq.take 6
printfn "%A" (first6multsof3 |> Seq.toList)
or with your filter-mod strategy:
seq { 1 .. 1000000} |> Seq.filter (fun x -> x%3=0) |> Seq.take 6 |> Seq.toList
A: This produces an infinite sequence of multiples:
let multiples n = Seq.unfold (fun i -> Some(i, i + n)) n
multiples 3 |> Seq.take 3 //seq [3; 6; 9]
This is a bit more code, but faster:
let multiples n =
let rec loop i =
seq {
yield i
yield! loop (i + n)
}
loop n
It's basically equivalent to the following C#:
static IEnumerable<int> Multiples(int n) {
int i = n;
while (true) {
yield return i;
i += n;
}
}
A: [ firstValue..Step..endValue]
[ 2..2..10] => [2; 4; 6; 8; 10]
other way
Seq.initInfinite id |> Seq.map (((+) 1) >> ((*) 2))
A: List.init 10 ((*) 3)
val it : int list = [0; 3; 6; 9; 12; 15; 18; 21; 24; 27]
You can play with the arguments and Seq.skip to get whatever you need.
For example, for [2; 4; 6; 8; 10]:
List.init 6 ((*) 2)
|> List.tail
Or:
List.init 6 ((*) 2)
|> Seq.skip 1
|> List.ofSeq
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android Eclipse library project and the library project's type resolution for project specific config files I've got several android projects that share one of my library projects. I want to have the library code depend on certain configuration classes that are defined differently in the project(s) that are depending on it. In order to get the non-lib projects to report no errors in Eclipse project explorer, this means providing class definitions in each project with the same fully-qualified path.
So the structure looks like this
Tablet_Project:
defines com.mycompany.config.ClientPrefs.java
Phone_Project:
defines com.mycompany.config.ClientPrefs.java
Lib_Project:
depends on but does not define com.mycompany.config.ClientPrefs.java
Once this done, the projects show no errors in Eclipse project explorer, but the lib has a red "X" indicating that it can resolve the ClientPrefs reference - which I would expect, Since you can't compile a lib anyway it doesn't seem like a big deal.
Problem: The phone project compiles and runs fine, but the tablet project reports that an error needs to be fixed before launching even though there are no "X" indicators anywhere in its workspace explorer.
Question: Is this approach to configuration actually permissible in these projects or is the fact that the phone project works just an accident?
Edit
Here is the most basic example I can come up with:
ProjectA and ProjectB depend on ProjectLib as an Android Library project. As displayed here, ProjectLib's Util.java can't resolve the missing ref to Config.java but this doesn't seem to matter for A and B since they seem to resolve this for ProjectLib and thus both build and run. Anyone else taken this approach to config?
The reason I ask is because I have a much larger set of projects, and one of them won't build anymore (in Eclipse) presumably since it's lib project has errors. Building with Ant from the command line always works and that makes me think that a library project gets pulled into the dependent project without regard to it's Eclipse boundary.
A: Before it was possible to make the same Config class in the ProjectA and ProjectB, and exclude the Config class from lib project.
But now the library project is included as jar, and it is not possible to exclude class from jar in eclipse.
My temporary solution to have config util class, which returns the correct Config, I need to change it each time when build different project.
public class Config {
private static MyConfig config;
public static MyConfig getConfig() {
if (config == null) {
config = new MyConfig();
}
return config;
}
// ...
// CONSTANTS
// ...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: reading innerHTML of HTML form with VALUE attribute (& its value) of INPUT tags I have a html form with some input fields.
Instead of reading and sending the values of input fields by document.ipForm.userName.value , I need to send the whole html content to html parser and extract the <name ,value> pair of each input field by some other program( and other information too).
But when i did this in JavaScript(i want pure JavaScript- not other library)
var contents=document.getElementById("formArea").innerHTML;
alert(contents);
It doesnot shows the value="enteredValue" of <input/> fields even if i entered some values.
My HTML File:
<html>
<head>
<script type="text/javascript">
function showInnerHtml(){
var contents=document.getElementById("formArea").innerHTML;
alert(contents);
}
</script>
</head>
<body>
<div id="formArea">
<form name="ipForm" >
UserName : <input type="text" name="userName">
</form>
</div>
<div> other contents..... </div>
<div onclick="showInnerHtml()">Show InnerHTML</div>
</body>
</html>
Am i missing something here or this is not possible.
Don't call me MAD. but i am struggling with this strange condition.
A: You can also write an input which will change itself his attribute, like this :
(...)
UserName : <input type="text" name="userName" onChange="this.setAttribute('value', this.value);">
And for checkboxes :
onClick="if (this.checked) { this.setAttribute('checked', null); } else { this.removeAttribute('checked'); }"
Enjoy :)
A: That's because value is a property when the textbox is filled in, not an attribute. This means that .value works fine, but it's not part of the actual DOM as an attribute (like <input value="...">).
You'd need to set it explicitly:
document.getElementById("html").onclick = function() {
var elems = document.getElementsByName("ipForm")[0]
.getElementsByTagName("input");
for (var i = 0; i < elems.length; i++) {
// set attribute to property value
elems[i].setAttribute("value", elems[i].value);
}
alert(document.getElementsByName("ipForm")[0].innerHTML);
};
<form name="ipForm">
UserName : <input type="text" name="userName">
</form>
<button id="html">get innerHTML</button>
View on jsFiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Can VirtualBox be executed under Amazon EC2 instance? We have a test system where a VirtualBox VM snapshot is started before each major test. The snapshot contains a state of the tested system specific to the test.
This is a memory-intensive testing.
There is an idea to move the daily test run into Amazon EC2 Large instance (7.5G of RAM).
My understanding though is that EC2 is a supervisor itself. Will it allow another VM software (VirtualBox) to get started under it?
A: I tried to do something, although it won't make much sense at least for , it's like VM inside VM, if it helps somebody
*
*Used Amazon EC2 account and installed free tier Windows Server 2012
*Took remote access to this so called VM, and install virtual box into it.
*Install a smallest possible Linux Headless (Slitaz) in this virtual box.
Here is how it looks,
A: I haven't yet found an exceedingly "authoritative" source (e.g. explicit EC2 or VirtualBox documentation) but the answer definitely seems to be: No.
The best explanation I've found so far is in Running Hyper-V, VMware or Xen on an AWS EC2 Instance?: virtualization feels like emulation, as if Amazon is running a "CPU simulator app". But a hypervisor is more like a kernel: it claims certain privileges on the actual physical CPU, exclusively for itself. Just like a kernel prevents apps from using physical CPU features that would interfere with other apps, a hypervisor is something of a "superkernel" that prevents kernels from using physical CPU features that might interfere with other kernels.
Basically: Amazon's virtualization software is already using the privileged instruction sets that VirtualBox would need. You will have to either use an emulator as David suggests, or somehow convert your VirtualBox image into a format supported by Amazon's VM Import tool — essentially convert your VM to run directly as its own EC2 instance.
A: I tried working with Virtual Box in Amazon EC2 today. Here is what I found
64 Bit VM's doesn't work at all. So you have to use only x86 VM in Virtual Box. You also have to limit CPU count per VM to 1. It doesn't work with 1+ CPU. You can modify it in vm_name.vbox file directly. Look for <CPU count="1" hotplug="false">
Note: Host OS on Virtual Box was "Ubuntu 14.04 x64" and guest OS was "Ubuntu 14.04 x64/x86" while testing
A: There were some new developments recently. Now AWS has bare
metal boxes, which are not VMs, but actual physical boxes.
Unfortunately, because AWS hardware is super dense the smallest box you can get is m5d.metal, which is 96 core, 768GB monster which comes quite pricey. Also, it looks like there is no spot market for those either.
I just tried to spin up Ubuntu instance on m5d.metal box, installed Vagrant and VirtualBox and tried to run one of my Windows boxes. It worked as expected without any problems.
A: I tried this today and definitive answer is: No.
You can install the GUI but kernel module will not install:
sudo /sbin/vboxconfig
vboxdrv.sh: Stopping VirtualBox services.
vboxdrv.sh: Building VirtualBox kernel modules.
vboxdrv.sh: Starting VirtualBox services.
vboxdrv.sh: failed: Running VirtualBox in a Xen environment is not supported.
A: Well, Amazon now allows to import VirtualBox and VMWare VMs. Not all operation systems are supported yet, but they work on it:
http://aws.amazon.com/ec2/vmimport/
So there is no need to run VirtualBox under Amazon, one can just import and clone the VM as an instance.
A: No, I don't believe it will.
I'm not 100% clear on exactly why, but my understanding is that the VirtualBox host needs access to ring 0, but since your host will be running in a virtualized system it won't be able to get this access.
If you really want to run virtual machines inside other virtual machines, you can use QEMU. Because it is an a processor emulator it doesn't depend on any of the underlying hardware, so it will work “anywhere”. The downside, though, is that it's much slower.
A: I have run VirtualBox under a Windows AMI. I'm trying to run it under Linux but there are all sorts of dependencies and hassles.
It is painfully slow.
So the answer is "yes" but you probably don't want to do it unless you're really desperate.
A: All AWS instances including the bare-metal ones already run in a virtualized environment.
Running VirtualBox in an EC2 instance means you want to run another virtual environment inside an already existing virtual environment called nested virtualization.
AWS has provided special instance types named bare-metal(.metal) instances to support nested virtualization.
So, for VirtualBox, Hyper-V, or any other virtual environment in an EC2 instance, use any of the available bare-metal instances. They are very costly though.
A: For those who are interested in seeing how "nested virtualiztion" works on bare metal EC2 instances:
# curl -w "\n" 169.254.169.254/latest/meta-data/instance-type
c5n.metal
# cat /etc/issue
Ubuntu 20.04.3 LTS \n \l
# dpkg -l virtualbox
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name Version Architecture Description
+++-==============-=============================-============-===========================================
ii virtualbox 6.1.26-dfsg-3~ubuntu1.20.04.2 amd64 x86 virtualization solution - base binaries
# VBoxManage list vms
"vagrant-project1_vm1_CentOS_1643693775729_39367" {d5043860-dcb6-4d05-a5be-a528b28cddf9}
"vagrant-project1_vm2_Ubuntu_1643693811420_34650" {3534a74d-a52b-4c2f-84bf-404ce524018d}
# vagrant status
Current machine states:
vm1_CentOS running (virtualbox)
vm2_Ubuntu running (virtualbox)
# vagrant ssh vm2_Ubuntu --command "sudo virt-what"
virtualbox
The last command above shows the virtulization type of the nested VM is "virtualbox".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
}
|
Q: Can I run an update query against my SQL db while in READ UNCOMMITTED isolation level? Currently I have with (nolock) specified after each table in all of the select statements within my stored procedure.
If I add the following code to the top of my stored procedure, can I still run an update/insert/delete query in my stored procedure?
set transaction isolation level READ UNCOMMITTED
A: Yes, but the update/insert/delete won't and can't be "dirty"
READUNCOMMITTED and NOLOCK cannot be specified for tables modified by insert, update, or delete operations. The SQL Server query optimizer ignores the READUNCOMMITTED and NOLOCK hints in the FROM clause that apply to the target table of an UPDATE or DELETE statement.
It goes on to say that this "feature" is deprecated anyway
With NOLOCK on the SELECTs, this means locks are neither issued nor observed. From same link
No shared locks are issued to prevent other transactions from modifying data read by the current transaction, and exclusive locks set by other transactions do not block the current transaction from reading the locked data.
So:
*
*your own SELECTs do not issue shared locks
*you ignore other locks (eg dirty reads)
As to issuing NOLOCK everywhere, do you know why you do it? I or any other high rep user here would recommend against it...
*
*Is the NOLOCK (Sql Server hint) bad practice?
*Using NOLOCK Hint in EF4?
*Is there a way to get different results for the same SQL query if the data stays the same?
*Is NOLOCK the default for SELECT statements in SQL Server 2005? (note the "authority" site is wrong)
You should consider snapshot isolation (or fixing the indexes/queries) if you have too many proven blocking reads
A: Yes, you can. Isolation levels do not mean you can't update/insert/delete.
Isolation levels are more about ACID - about what gets locked and what is visible to other sessions.
From wikipedia, Isolation (database systems):
In database systems, isolation is a property that defines how/when the changes made by one operation become visible to other concurrent operations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Switching tabs breaks background images when using the CSS styling perspective Any ideas why?
What steps will reproduce the problem?
*
*Load the following fiddle: http://jsfiddle.net/bhellman1/4fTeA/1/
*In the result box, scroll down a half way
*Switch to another tab
*Then go back to the fiddle, notice the background image broke, it's gone, and all you now see it the background color
The background-image should persist when tabbing through chrome. Instead, switching to another Chrome tab breaks the background-image
A: Getting rid of all of this code fixes it for me:
#number .flipper {
perspective: 1000;
-o-perspective: 1000;
-ms-perspective: 1000;
-moz-perspective: 1000;
-webkit-perspective: 1000;
}
Not even sure what that does exactly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails3 app failed to push to Heroku. "Unrecognized error" Things seem to go great, and then it chokes at the end. Observe:
$ git push heroku master
Counting objects: 12, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 109.76 KiB, done.
Total 7 (delta 4), reused 0 (delta 0)
-----> Heroku receiving push
-----> Ruby/Rails app detected
-----> Detected Rails is not set to serve static_assets
Installing rails3_serve_static_assets... done
-----> Configure Rails 3 to disable x-sendfile
Installing rails3_disable_x_sendfile... done
-----> Configure Rails to log to stdout
Installing rails_log_stdout... done
-----> Gemfile detected, running Bundler version 1.0.7
Unresolved dependencies detected; Installing...
Using --without development:test
Installing rake (0.9.2)
Installing multi_json (1.0.3)
Installing activesupport (3.1.1.rc1)
Installing builder (3.0.0)
Installing i18n (0.6.0)
Installing activemodel (3.1.1.rc1)
Installing erubis (2.7.0)
Installing rack (1.3.3)
Installing rack-cache (1.0.3)
Installing rack-mount (0.8.3)
Installing rack-test (0.6.1)
Installing hike (1.2.1)
Installing tilt (1.3.3)
Installing sprockets (2.0.0)
Installing actionpack (3.1.1.rc1)
Installing mime-types (1.16)
Installing polyglot (0.3.2)
Installing treetop (1.4.10)
Installing mail (2.3.0)
Installing actionmailer (3.1.1.rc1)
Installing arel (2.2.1)
Installing tzinfo (0.3.29)
Installing activerecord (3.1.1.rc1)
Installing activeresource (3.1.1.rc1)
Installing coffee-script-source (1.1.2)
Installing execjs (1.2.6)
Installing coffee-script (2.2.0)
Installing rack-ssl (1.3.2)
Installing rdoc (3.9.4)
Installing thor (0.14.6)
Installing railties (3.1.1.rc1)
Installing coffee-rails (3.1.1)
Installing jquery-rails (1.0.14)
Installing pg (0.11.0) with native extensions
Using bundler (1.0.7)
Installing rails (3.1.1.rc1)
Installing sass (3.1.7)
Installing sass-rails (3.1.2)
Installing sqlite3 (1.3.4) with native extensions
Installing uglifier (1.0.3)
Updating .gem files in vendor/cache
Removing outdated .gem files from vendor/cache
* spork-0.9.0.rc9.gem
Your bundle is complete! It was installed into ./.bundle/gems/
-----> Compiled slug size is 14.4MB
-----> Launching...
! Heroku push rejected due to an unrecognized error.
! We've been notified, see http://support.heroku.com if the problem persists.
To git@heroku.com:myproject.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:myproject.git'
Before this, I was able to push to Heroku, but the app was failing to launch because I was missing the pg gem. So now the pg is in there correctly and the push fails. Any ideas on how I can fix this?
A: You should submit a ticket to support. Seems like they've had a similar issue in the past:
http://status.heroku.com/incident/52
At first glance, that spork gem looks suspicious. Are you segregating your development gems in a group in your Gemfile?
group :development, :test do
gem 'spork'
end
A: you should check https://status.heroku.com/ first.
There's an open issue (https://status.heroku.com/incident/212) which was opened 54 minutes ago which relates to deployment issues - although it appears to be only Cedar apps affected now - but that's not to say it wasn't the full stack when the issue was created.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: assign func(const void *) to func(void *) in C I have a function that takes a function pointer and apply it over a list. It's prototype is as follows:
void applyList(List *, void applyFunc(void *));
Now I want to supply a function that prints the element in the list. Since I'm not modifying the list element, the print function looks like this:
void printNode(const void *nodeData){
Data *dPtr=(Data*)nodeData;
printf("%s", dPtr->str );
}
//Usage
applyList(list, printNode);
However I got an compiler error saying
expected ‘void (*)(void *)’ but argument is of type ‘void (*)(const void *)’
I don't want to add const to apply's prototype, because I might supply some function that modifies the data. Any suggestion on how to deal with this situation?
A: Unfortunately, in C function pointers are not polymorphic. At all. Attempting to force a cast leads to undefined behavior.
Your only standard-conforming way out is to write a wrapper function:
static void wrap_printNode(void *nodeData) {
printNode(nodeData);
}
Note, however, that your const is kind of useless here:
Data *dPtr=(Data*)nodeData;
You just casted away the const declaration. Try to keep it on there:
const Data *dPtr=(const Data*)nodeData;
A:
I don't want to add const to apply's prototype, because I might supply some function that modifies the data.
Then there is no sane solution. The data isn't yours to modify, which is why it's marked const.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cannot resolve type runtime error after registering the Enterprise Library into the GAC I worked on registering the Enterprise Library assemblies into the Global Assembly Cache (GAC). I am using version 5.0 of the Enterprise Library that I signed with my own key, and I am using the assemblies in a number of .NET 4.0 applications.
After successfully registering the Enterprise Library assemblies into the GAC, the application started with this message:
The type 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling' cannot be resolved. Please verify the spelling is correct or that the full type name is provided.
When I unregister the Enterprise Library assemblies from the GAC, the application returns to normal operating conditions.
What is causing the application to fail when the Enterprise Library assemblies are registered into the GAC?
A: This required quite a bit of hunting to figure out what happened. As it turns out, the Enterprise Library internally uses partial names to load type dynamically. In this case, the Enterprise Library is trying to load Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter dynamically because it appears in the configuration file.
To get around partial name references at runtime, simply enter a qualifyAssembly element in the configuration file (see <qualifyAssembly> Element in the MSDN documentation).
In my case, all I needed to enter was this entry:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<qualifyAssembly partialName="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
fullName="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblyBinding>
</runtime>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: httpapi: Why is HttpSendHttpResponse returning invalid parameter? I've tried to port http.h to Delphi, but my calls to HttpSendHttpResponse return 'invalid patameter', and I'm not sure why.
I'm sticking to HTTPAPI_V1 for now, and am testing on WinXP. I have posted source-code I use to test with here:
http://nldelphi.com/Forum/showthread.php?t=37904
A: I had some problems with it and the obvious problem was the aligning rules for the data types. Add the following to the unit to validate your data structures:
initialization
{$if sizeof( HTTP_REQUEST ) <> 464}{$message error 'HTTP_REQUEST sizeof error.'}{$ifend}
{$if sizeof( HTTP_RESPONSE ) <> 280}{$message error 'HTTP_RESPONSE sizeof error.'}{$ifend}
{$if sizeof( HTTP_COOKED_URL ) <> 24}{$message error 'HTTP_COOKED_URL sizeof error.'}{$ifend}
{$if sizeof( HTTP_DATA_CHUNK ) <> 32}{$message error 'HTTP_DATA_CHUNK sizeof error.'}{$ifend}
{$if sizeof( HTTP_REQUEST_HEADERS ) <> 344}{$message error 'HTTP_REQUEST_HEADERS sizeof error.'}{$ifend}
{$if sizeof( HTTP_RESPONSE_HEADERS ) <> 256}{$message error 'HTTP_RESPONSE_HEADERS sizeof error.'}{$ifend}
{$if sizeof( HTTP_SSL_INFO ) <> 28}{$message error 'HTTP_SSL_INFO sizeof error.'}{$ifend}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual Studio-> Find all references-> Looking for symbol in XAML files Is there a way to prevent "Find all references" from searching in XAML files? Searching the XAML files is painfully slow.
A: Not to re-open an older post, but you could do a "find in files" and specify only the file types you want to search through (e.g. .xml; .txt; .cs; .cpp etc).
Granted i might be stating the obvious but....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Is there a way of logging the browser a user submits a form from in MySQL database I have a PHP page which handles the submission of a form and adds the data to a MySQL table. I am wondering if there is a way of writing the browser and version that a user is submitting the form from into a column in the MySQL table?
Thanks,
Nick
A: This information is available in:
$_SERVER['HTTP_USER_AGENT']
The function get_browser() is capable of parsing it out to some degree:
$browserinfo = get_browser($_SERVER['HTTP_USER_AGENT']);
print_r($browserinfo);
echo $browserinfo['browser']; // firefox
echo $browserinfo['platform']; // linux
Note: It's not actually necessary to pass the user agent variable into get_browser() as I've done above - it reads that header by default.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Moving a Object pointer in a vector to a different vector Right now I have two vectors of Object pointers
std::vector<Object*> vec1;
std::vector<Object*> vec2;
Lets say vec1 has two objects and vec2 has none. How would I move one of the objects in vec1 to vec2 without destroying the actual object? So, in the end both vectors are of size 1 and each have an object pointer.
A: You won't destroy the data pointed to (assuming there even is any) until delete is called. You can do something as simple as...
vec2.push_back(vec1[1]);
vec1.pop_back();
A: You don't destroy the object. Take it out of vec1 and push_back to vec2. Even if you take it out of both, you don't destroy the object.
A: Suppose you want to move the last Object* from vec1 to vec2:
vec2.push_back(vec1[1]);
vec1.pop_back(); // not destroying Object*
Suppose you want to move any arbitrary Object* to other vector then get its vector::iterator and copy it to the destination. Then you can use vector::erase() on it.
A: As already pointed out, I think you may benefit from more understanding of pointers in general before attempting to do anything with them. You're not moving or doing anything with the object itself, you're moving around / creating new pointers to that object.
A: If the vectors contained objects instead of pointers to objects and you wanted to move and not copy I believe you could use std::move which returns rvalue reference which is movable but not copyable.
There is SO question about move here: What is std::move(), and when should it be used?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the best way to enable several users to update the same database? I am currently on a mission and I'm facing a problem that I have never had to deal with before:
A classic Access 2003 database contains several tables that have to be updated by people located at different places in the company. What is the best way to enable different people to enter data in the tables ? Here are the few I have though of:
*
*the worse: each personn will modify the ONLY database file that will be sent to each people that want to update it
*the database is located on a server and people will connect to it, using forms to enter the data
*each time a person will have to enter data in the database, we will extract the table to Excel and then the person will modify it before it will be reimported to Excel
I guess (and hope) that the best solution is not among the three above, I need your advices, thank you !
A: If the users are in remote offices, use Terminal Services that include the app file Remou suggested and link to the data file on a server the terminal service users have available. I don't know about Office licenses of having on user computer and the server.
A: The usual solution is to split the database into front and back-ends. The front end is placed on each user's desktop and contains forms and reports. The tables are linked frrom the back-end, which is on a shared directory on your server.
More info: http://msdn.microsoft.com/en-us/library/aa167840(v=office.11).aspx
A: If multiple people need to edit the database concurrently, you should really be using a real Database server, such as SQL Server.
You can use Access as a front-end to SQL Server, so you won't need an additional interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: hex not evaluating correctly i tried hard to solve this one on my own but ive spent way to much time on something as simple as this so im hoping someone can give me the answer.
see image below but basically im just trying to get a range built but my marker and my list never meet even though there are items that match the criteria.
in the example below im looking for 2c and the array has it in position 11 but just goes right past it.
i have tried a few different ways, and the comparison above it works just fine so i dont get where my problem is.
i have tried just saying
== 0x2c (never evaluates)
or using this like i had above
`intValue`
but this make it get a match on 2D which from my testing is because it truncates the digits down to just plain 2.
ACTUAL CODE:
int lastIndexInPayload = ([payload count]-1);
int beginningOfData = ([payload count]-1);
NSString * endOfLine = [NSString stringWithFormat:@"%02X", 0x0D];
NSString * startOfLine = [NSString stringWithFormat:@"%02X", 0x2C];
if ([[payload objectAtIndex:lastIndexInPayload]intValue] == [endOfLine intValue]) {
while ([payload objectAtIndex:beginningOfData]!= startOfLine) {
beginningOfData--;
DDLogVerbose(@"beginningOfData %d",beginningOfData);
}
}
the payload is an array of bytes
taken from nsdata from a socket return
A: I imagine it's because you're using == to compare objects. Since it appears both your array and your startOfLine object are just hex strings representing a single byte, you should probably just use -isEqualToString:, as in
while (![[payload objectAtIndex:beginningOfData] isEqualToString:startOfLine]) {
That said, I find it rather odd that your payload is an array of hex bytes represented as strings. Why not just shove the whole thing into an NSData and have access to "real" bytes instead?
A: You are comparing strings according to their address and not their contents, you should use while (![[payload objectAtIndex:beginningOfData] isEqualToString:startOfLine]). Also why are you trying to use strings for hex values and not just compare against 0xD directly? Your call to intValue will result in 0 for endOfLine because it does not know that it is hex and will stop trying to parse a number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Center Text align for labels I have a label exactly in center of a form with text "It is my Visual Studio application". Now, I have a button click event that changes the text to "My application". But the problem is the alignment gets disturbed as the length of changed text is different from previous one. I tried TextAlign option of label to MiddleCenter. but no luck. Can any one help?
A: You can even do better: set the label Autosize OFF, and manually stretch the label in the designer to
fill the area that's needed to show the largest text value.
Now if you set the TextAlign to MiddleCenter, you get the effect you want (even in the designer, so you can check it by setting a value in the Text property).
A: You will also need to set the width of the label to the length of your longest text, or just to the width of the form.
A: You need to set the label autosize to true, put that label inside a frame (or a table cell), and make the anchor properties to none. That way it will be centered always.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: android SQLiteConstraintException: error code 19: constraint failed I got android SQLiteConstraintException: error code 19: constraint failed exception. I saw there are tons of question in this topic, I've read a bunch of them, but still cant figure out what I did wrong. Mere is my table schema.
private static final String DATABASE_CREATE = "CREATE TABLE calls (call_ID
INTEGER AUTO INCREMENT PRIMARY KEY NOT NULL, caller_id TEXT NOT NULL, "+
caller_name TEXT NOT NULL, called_id TEXT NOT NULL, called_name TEXT NOT NULL," +
"start_time TEXT NOT NULL, end_time TEXT NOT NULL);";
I add one single row, and it throws the exception.
public long addCall(String caller_id, String caller_name, String called_id,
String called_name, String start, String end) {
ContentValues initialValues = createContentValues(caller_id, caller_name,called_id,called_name, start,end);
return database.insert(DATABASE_TABLE, null, initialValues);
}
I overrided the SQLHelpers onOpen method, to clear the table on every open, but it didnt help.
public void onOpen (SQLiteDatabase database){
database.execSQL("DROP TABLE IF EXISTS calls");
onCreate(database);
Log.w(DBHelper.class.getName(),"DB onOpen");
}
UPDATE: The problem is not that, I try to pass null, cause I only add these strings, and I got the error.
dbAdapter.addCall("test", "test","test", "test", "test", "test");
UPDATE 2: This is my createContentvalue method:
public static final String CALLER_ID = "caller_id";
public static final String CALLER_NAME = "caller_name";
public static final String CALLED_ID = "called_id";
public static final String CALLED_NAME = "called_name";
public static final String START = "start_time";
public static final String END = "end_time";
public static final String DATABASE_TABLE = "calls";
private ContentValues createContentValues(String caller_id, String caller_name, String called_id, String called_name, String start, String end) {
ContentValues values = new ContentValues();
values.put(CALLER_ID, caller_id);
values.put(CALLER_NAME, caller_name);
values.put(CALLED_ID, called_id);
values.put(CALLED_NAME, called_name);
values.put(START, start);
values.put(END, end);
return values;
}
A: Checked for null values in your method arguments? ;-)
Edit based on update
Haa, I knew it: A null value. ;-)
You use CALLER_NAME twice... (btw CALLER_ID too)
Edit based on comments
Besides the null value, he was trying to set the primary key (accidentally). That could have been the main reason (besides the actual null value).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I validate the ? Is there a way to validate the tag? And I have two elements with OnMouseOver attribute, and the validator, too don't validate them. The only errors are these. So if you know a way, please share...
A: There is no way to validate the <marquee> tag since it is not a standard html element. You will have to use JavaScript. Here is another SO question that might lead you in the right direction. Javascript Marquee to replace tags
A: <marquee>? Are you travelling in time and came from late 90's?
OK, jokes aside. <marquee> is not a standard HTML attribute, it was introduced by Microsoft and was never really adopted. Hence the HTML validator will obviously scream.
Technically you can use tricks like generating this tag dynamically via JavaScript. There is also much better, portable and widely accepted workaround - don't use it. It looks terrible.
A: <marquee> is not a valid HTML tag. It won't validate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I "re-group" a pig relation? Assume I have an input file input.dat that looks like this:
apples 10
oranges 30
apples 6
pears 5
Now, when I load, group, and project the data:
sources = LOAD 'input.dat' as { a:chararray, b:int };
grouped = GROUP sources BY a;
projection = foreach sources generate flatten(group), SUM(sources.b);
dump projection;
I get the following:
apples 16
oranges 30
pears 5
Now, I want to "re-group" the data where the SUM(sources.b) is below some threshold into a single line. As an example, if the threshold was 20, I would get:
other 21
oranges 30
because the sum for both "apples" and "pears" was below the threshold of 20.
It seems to me that I can follow a couple of different approaches:
*
*Use the SPLIT operator on grouped to create two relations: above_threshold and below_threshold. Then project below_threshold to replace the value of a with "other" and regroup. Finally UNION that result together with above_threshold and then run the final projection again.
*Or, follow the original script exactly, but when creating projection, generate a conditionally (based on SUM(sources.b)), then re-group projection (to group all of the "other" rows together), and then project again (to flatten the re-grouped data).
Is one of the above approaches clearly better than the other? Or is there another approach that will be more efficient or easier to maintain?
A: Option 1 is better. This is because option 1 only has to pass around below_threshold data into a M/R record count; while in option 2, you are regrouping everything, it seems like.
Also, there are a few good things about approach 1, most notably:
*
*The below_threshold count is going to be pretty fast because you only need 1 reducer and the combiner is going to do wonders with only one key.
*Depending on your application, you don't need to UNION. You can just output to two locations, and then "union" by treating them as the same output externally from pig. For example, you can still do hadoop fs -getmerge my_out/*/part-r-* output to grab both outputs.
So, I see your Pig script looking like:
sources = LOAD 'input.dat' as { a:chararray, b:int };
grouped = GROUP sources BY a;
projection = foreach sources generate flatten(group) as n, SUM(sources.b) as s;
SPLIT projection into above_threshold if s >= 20, below_threshold if s < 20;
dump above_threshold;
below_grouped = GROUP below_threshold BY 'other' PARALLEL 1;
below_projection = FOREACH below_grouped GENERATE group, SUM(below_threshold.s);
dump below_projection;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cocoa Bindings: Enable a button if multiple textfields have values I have 5 buttons and 5 text fields. I'd like to set up bindings so that button 1 is enabled only if textfields 2-5 have values..... button 2 is enabled only if textfield 1 & 3-5 have values, etc.
I'm just starting to learn about cocoa bindings. I was hoping I could use them to manage the enabling/disabling of the buttons. When I tried to set up an Enable binding on one of the buttons, it won't let me reference the textfields.
Is this possible (and right) to do with bindings?
A: You won't be able to reference the textfields directly in the bindings for the bitton.
A way to work around this is to create a NSObject subclass - call it ButtonController - and have instance vars for the 5 textfields:
@inteface ButtonController : NSObject
{
NSString *text1;
NSString *text2;
NSString *text3;
...
}
@property(nonatomic, retain) NSString *text1;
@property(nonatomic, retain) NSString *text2;
...
In the xib file, instantiate an object for the ButtonController. Now u can bind things to the button controller instance.
Next, bind all the textfields to the corresponding NSString properties.
Then u can bind the enabled property of the button to ButtonController's properties. When u bind the enabled property of button1, bind it to text2 and check the box for valuetransformer and select "NSIsNotNil". Once u do that, a second enabled2 binding becomes available and u can bind it to text3 etc.
I think this will work but havent tried it yet.
A: Bindings are not conditional, or at least rather opaque in this respect. You will have to do this in code. Check your text fields text change callbacks and enable the buttons accordingly. Should be just a few lines of code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Set a (different) property based on a value in a variable?
Possible Duplicate:
Objective C Equivalent of PHP’s “Variable Variables”
I have a UIButton action, that grabs the button sender
This line gives me the sender tag which I'm using in a switch statement
int senderTag = [sender tag];
I then have to do...
switch (senderTag) {
case 1:
brain.selectedPaintColor1 = myColor;
break;
case 2:
brain.selectedPaintColor2 = myColor;
break;
case 3:
brain.selectedPaintColor3 = myColor;
...
What I'd really like to be able to do is use the tag to set a variable property name like this
[brain.selectedPaintColor%i,senderTag] = myColor;
Can anyone assist with the syntax to be able to do that?
Thanks!
A: Direct translation of what you want
NSString *key = [NSString stringWithFormat:@"selectedPaintColor%i", senderTag];
[brain setValue:myColor forKey:key];
A: Or, since the assignment methods above are really being translated into calls to setter methods, one could build an array of selectors and call a method from the indexed array. (Not going to slog through the syntax just now though -- selectors always make my head hurt.)
(And, in fact, there's a way to dynamically look up a selector, so you could build the selector name string and look it up, vs pre-constructing an array.)
A: Combine your properties selectedPaintColor1 , selectedPaintColor2 etc. into an NSMutableArray and use that as a property. Now the syntax is:
[brain.paintColors replaceObjectAtIndex:sender.tag withObject:myColor];
Be aware that if your sender is of type id you will have to cast it into a (UIView) first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC 3 with Forms Authentication, need userid in data project, best practices? I just started an MVC 3 project using Forms Authentication. I have a web project (mvc project), and a data project. The data project handles all database interactions.
I need to store the current user id in my database on every insert and update.
Here's what I am doing right now. I feel like this has to be a common scenario. Can anyone shed some light on a better way to do this?
*
*On LogIn or Register, I grab my current user record (by username) from the database and store the user id in session.
*When saving a record within my data project, I refer to the httpcontext (if it exists) and use the user id that is stored in session.
This works for all but one scenario. It fails when a user has a valid cookie saved, and so they are allowed to bypass the login/register action. When this happens, obviuosly, my session variable for userId is null. My next step would be to create a base controller and imlement OnAuthorizeStarting to check if my Session variable is null or not. This feels kludgy, and I'm hoping there is a better way.
I do not want to have to pass the user Id to the data project as a parameter on every Save call.
Anyone have some brilliance? thanks.
A: The UserID is available via membership. So, something like this:
Membership.GetUser(HttpContext.User.Current.UserName).ProviderUserKey
The IPrincipal (HttpContext.user.Current) is created when the user is authenticated against the forms authentication cookie. You just pull up the user id from the Membership whenever you need it.
If you don't like accessing Membership every time then you can always create a static helper class that wraps your UserID session call. If it's null, it goes out to the membership provider, gets it, then stores it in the session.. on later accesses it just retrieves the session variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET MVC3 Entity with ViewModel CRUD pages I'm using EF with ViewModel and AutoMapper design strategies for an MVC3 application.
I'm wondering if there is a more efficient way of creating the CRUD pages then what I'm currently doing.
My Current Process Involves:
*
*Create the Entity
*Create the ViewModel via copy paste then deleted non-required fields
*Add the Entity to the Context list
*Create a controller via the Visual Studio 2010 create controller wizard page.
*I select a Template of Controller with read write actions and views, using Entity Framework.
*I choose my model to be my ViewModel instead of my entity.
*I select the appropriate context.
*Now the part I part I think can be improved, I have to re-write all the CRUD methods to use AutoMapper and the Entity/ViewModel design pattern changing:
return View(db.BlockedUserViewModels.ToList());
into:
IList<BlockedUser> blockedUsers = db.BlockedUsers.ToList();
IList<BlockedUserViewModel> blockedUserVMs = AutoMapper.Mapper.Map<IList<BlockedUser>, IList<BlockedUserViewModel>>(blockedUsers);
return View(blockedUserVMs);
*
*I have to add the same [Authorize] and roles permissions to each controller CRUD option.
This seems way overkill in workload! I'm hoping there a better solution. (I'm coming from Python/Django where it requires a single line of code to create beautiful strong CRUD pages)
A: It sounds like you can add a service and inject it into your controller. Then you only have to call
var model = _service.GetBlockedUsers();
each time instead of:
IList<BlockedUser> blockedUsers = db.BlockedUsers.ToList();
IList<BlockedUserViewModel> blockedUserVMs = AutoMapper.Mapper.Map<IList<BlockedUser>, IList<BlockedUserViewModel>>(blockedUsers);
This will keep your controllers light and act as a place to keep your crud logic so you don't have to repeat it everywhere.
Also, you can add the [Authorize] attribute to the controller if it applies to every action in the controller.
A: It really depends on how painful this is for you, but you can always use the MVC scaffolding stuff found in Nuget and written by Steven Sanderson. Investing some time could help you in the long run, but you have to figure out if it's right for you.
http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating tables with different sized cells I want to make my form to look neat and I want my cells to be different sizes depending on the information in the cell. How do I make a cell width different then the one above it?
OK now i also want to know how to make 1 cell tall and have a lot of small cells to the right of it.
Example:
<html>
<table border="1"><td width="50">some info</td><td width="50">some more info</td>
<tr>
<td width="250">Lots more text and information in this box then the first cell</td><td> other information</td>
I don't want the first cell in the first row to automatically resize to the length of the first cell in the second row.
Example:
|some info|some more info|
|Lots more text and information in this box then the first cell|other information|
or is there at least another way to lay this out that would look clean?
A: All column in table always have similar width (you can't change it), you can only add one more cell and span some amount of cells in second row.
<html>
<table border="1">
<tr>
<td width="50">some info</td>
<td width="50">some more info</td>
<td></td>
<td></td>
</tr>
<tr>
<td width="250" colspan="3">Lots more text and information in this box then the first cell</td>
<td> other information</td>
A: Try this -- use DIVs to simulate table rows and columns, and the CSS min-width property to create "cells" that can stretch as needed.
http://jsfiddle.net/HN4YS/1/
html:
<div class="row"><div class="col1">some info</div><div class="col2">some more info</div></div>
<div class="row"><div class="col1">Lots more text and information in this box then the first cell</div><div class="col2">other information</div></div>
css:
.col1, .col2 {
display: inline-block;
min-width: 150px;
border: 1px solid;
padding: 4px;
}
.row {
white-space: nowrap;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SystemExit and NameError issues with exiting def main():
try:
print "hardfart"
return 0
except:
return 1
if __name__ == '__main__':
exit(main())
Can one kind programmer tell me why this spits out the following error on exit?
Traceback (most recent call last):
File "C:/Apps/exp_exit.py", line 9, in ,module.
exit(main())
File "C:\Apps\python2.7.2\lib\site.py", line 372 in __call__
raise SystemExit(code)
SystemExit: 0
This is causing an error on exit in a project that's set up similarly. For that project, after using gui2exe to compile an exe, when closing the program I get this related error:
Traceback (most recent call last):
File "checkHDBox.py", line 303, in <module>
NameError: name 'exit' is not defined
So if exit is generating this error, how do I exit then? And if I create an exception handler for exit, doesn't that replace the default action that python takes with the exit function?
Thanks.
Edit:
I think this answers my own question.
The traceback here is from IDLE, I think it's a default behavior from other sources I've read.
Traceback (most recent call last):
File "C:/Apps/exp_exit.py", line 9, in ,module.
exit(main())
File "C:\Apps\python2.7.2\lib\site.py", line 372 in __call__
raise SystemExit(code)
SystemExit: 0
The traceback here was fixed by using sys.exit() instead of exit(0)
Traceback (most recent call last):
File "checkHDBox.py", line 303, in <module>
NameError: name 'exit' is not defined
A: You exit a program by raising SystemExit. This is what exit() does. Someone has incorrectly written an exception handler that catches all exceptions. This is why you only catch the exceptions you can handle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Msbuild Custom Task - For loop I would like to implement a Msbuild Custome task to loop a list of items and do something about each item. Basically I would liketo build a foreach or for loop in msbuild.
I have searched around but didn't find much useful information about output a list of items and loop though each of them
What I got
How to implement Custom Tasks
http://blogs.msdn.com/b/msbuild/archive/2006/01/21/515834.aspx
Return output from a custom msbuild task
Return output from an MsBuild task?
Is it possible to implement my though with msbuild custom task?
Update:
I would like something
<Foreach item='String' in="PropertyGroups" Property='MyPropertyName'>
//do what ever to use $(MypropertyName) for other tasks
</Foreach>
A: Standard MSBuild tasks operate on collections (ItemGroup in MSBuild-ese, ITaskItem[] in the ITask interface) and custom tasks can do the same. You don't need a foreach.
Your task, if you need a custom task, would look like this:
<MyTask TaskItems="@(blah)"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Regular expression for number search I need a regular expression that will find a number(s) that is not inside parenthesis.
Example abcd 1 (35) (df)
It would only see the 1.
Is this very complex? I've tried and had no luck.
Thanks for any help
A: An easy solution is to first remove the unwanted values:
my $string = "abcd 12 (35) (df) 2311,22";
$string =~ s/\(\d+\)//g; # remove numbers within parens
my @numbers = $string =~ /\d+/g; # extract the numbers
A: The regular expression would be:
^[a-z]+ ([0-9]+) \([0-9]+\) \([a-z]+\)$
The result is the first (and only) matching group of the regex.
Maybe you want to remove the ^ and $ if the regex should not match only if it’s the content of a whole single line. You can also use [a-zA-Z] or [[:alpha:]]. This depends on the regular expression engine you use and, of course, the content you want to match.
Example perl code:
if (m/^[a-z]+ ([0-9]+) \([0-9]+\) \([a-z]+\)$/) {
print("$1\n");
}
Please note that your question contains not enough information to make a good answer possible (you did not say anything about the general format of your expression, for example if you want to match integers or floating points)
A: This is quite hard but something like this will probably do:
^(?:\()(\d+)(?:[^)])|(?:[^(0-9]|^)(\d+)(?:[^)0-9]|^)|(?:[^(])(\d+)(?:\))$
The problem is to match (123, 123) and also to not match the string 123 as the number 2 between the non-parentheses characters 1 and 3. Also there are probably some edge cases for start of and end of string.
My suggestion is to not use a regex for this. Maybe a regex that matches numbers and then use the capture info to check if the surrounding characters are not parentheses.
A: How about
/(?:^|[^\d(])(\d+)(?:[^\d)]|$)/
? This matches a string of digits (\d+) that are
*
*preceded by the beginning of the string, or a character that is not a digit or an open parenthesis ((?:^|[^\d(]))
*succeeded by the end of the string, or by a character that is not a digit or a close parenthesis ((?:[^\d)]|$))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Leaks in UIPasteboard objects I see a lot of leaks in several UIPasteboard objects. Until today, I never heard of this class and (obviously) didn't use one myself in the program. Here's a screenshot:
What can I do to get rid of these leaks? Am I even looking at this problem correctly?
A: Without a stack trace, you can't do a whole lot.
UIPasteboard is used for implementing copy&paste. On the desktop it's also used for drag&drop. Besides these two tasks, I'm not really sure what else people commonly use it for, but it is a way to send snippets of data between apps (assuming both apps know to look at the pasteboard).
A: make sure to check if the problem is a UIPasteBoard instance in any 3rd party code used.
A: If this is not an application pasteboard that you have set than it is a system pasteboard so you will need to access the generalPasteBoard than get all its items and all the types for those items and set their string and data values to nil.
generalpasteboard UIPasteBoard *pb = [UIPasteboard pasteBoardWithName:UIPasteboardNameGeneral];
for (UIPasteBoardItem *pbItem in [pb items]) {
for (NSString pbType in [pbItem pasteboardTypes]) {
[pbItem setData:nil forPasteboardType:pbType];
[pbItem setValue:nil forPasteboardType:pbType];
}
}
try putting this at the beginning of your application.... Still its strange that the general pasteboard is leaking... By the way, it may also be the find pasteboard UIPasteboardNameFind (also a system pasteboard)
Note that this is for finding out if it is the general pasteboard not using in the final distributed app. Also make sure to check if the problem is a UIPastBoard instance in any 3rd party code used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Will XMPP work in a NAT environment? An XMMP server sends push notifications to a client behind a NAT using a public endpoint( IP + Port) supplied by NAT to client. But how long this endpoint is assigned to this specific client by NAT, what will happen if NAT assigns same endpoint to another client ? How this problem can be solved?
A: XMPP uses a standard TCP connection. NATs will keep the association for as long as the connection is alive (unless they are horribly broken).
Update: The last part of my statement could have been expanded a bit. Horribly broken NAT implementations do exist. Generally these are a small percentage, but many (most?) popular XMPP clients do ensure they send some kind of keepalive over idle connections.
There are three kinds of keepalive you can use I'll list them here in order of bandwidth/processing requirements:
TCP keepalives are a good lightweight option, especially as once they are enabled, they are automatically handled by the OS. How to enable them will depend on your language and framework, but at the lowest level, you need to enable the SO_KEEPALIVE option on the socket.
There are two problems with TCP keepalives. One is that you can't control them from your application (unless you write platform-specific code). The second problem is that some NAT implementations are so broken that they will ignore TCP keepalives too! But you're hopefully down to a very small percentage now.
So another option is whitespace keepalives. Since these involve data going across the stream, you should be safe from even the broken NATs that ignore keepalives.
Whitespace keepalives simply involve sending the space character (' ') across the XMPP stream at any time it is idle. XML and XMPP allow unlimited whitespace between elements, and it is simply ignored by the recipient.
Finally, you can use fully-fledged XMPP pings (XEP-0199). These involve ending an actual <iq/> 'get' stanza to the server, which then must reply. This ensures data flows in both directions, and should make even the most broken NAT implementations keep your connection alive.
Ok, I should mention that there is an even worse class of NAT. I have seen NATs that will simply 'forget' about your mapping for a range of reasons, including their mapping table being full, or just after a timer. There is nothing you can do to work around these, they don't work with any long-lived TCP connections. The best you could probably do at that point is use BOSH (essentially XMPP over HTTP).
Conclusion: If you are concerned that your application may run behind some of these devices, I suggest something like the following algorithm (exact times may be tweaked, but I recommend these as minimum values):
*
*If you have not sent any data for 60s, send a single space character.
*If you have not received any data for 120s, send an XMPP ping to your server.
*If the server doesn't reply to the ping within a reasonable amount of time, reconnect.
Because the behaviour of broken NAT devices is beyond any standard protocol specification, it is naturally impossible to devise a perfect solution that will work with all of them, all of the time. You just have to accept that these are a small minority, and none of this matters for working NAT devices (though there are other kinds of network breakages that may make regular keepalives/pings a good idea, depending on the needs of your application).
A: The Solution is sending keep alive messages to maintain the NAT entry. XMPP whitespace is typically used. Send it eg every Ten minutes to preserve reachability of the nated client.
You have to keep in mind that NAT is no standardized technique. Thus there are different implementations. The provided RFCs in the comment above is from the BEHAVE working group.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: EVO 3d ( PG86100 ) - No logs in Logcat via sendlog? Trying to get some logs from a EVO 3D, but each time the logs are sent, they appear to contain no 3rd party app logs. Makes it quite difficult to try and debug an issue which appears only on this one device.
Any thoughts/suggestions?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Do the && and || operators convert their operands to booleans? Flanagan's O'Reilly JavaScript book states:
Unlike the && and || operators, the ! operator converts its operand to
a boolean value [...] before inverting the converted value.
If those logical operators don't convert the operands to booleans, how can the expression be evaluated?
A: Per specification, section 11.11: Binary Logical Operators:
The production [of evaluating &&] ... is evaluated as follows:
*
*Let lref be the result of evaluating LogicalANDExpression.
*Let lval be GetValue(lref).
*If ToBoolean(lval) is false, return lval.
*Let rref be the result of evaluating BitwiseORExpression.
*Return GetValue(rref).
The production [of evaluating ||] ... is evaluated as follows:
*
*Let lref be the result of evaluating LogicalORExpression.
*Let lval be GetValue(lref).
*If ToBoolean(lval) is true, return lval.
*Let rref be the result of evaluating LogicalANDExpression.
*Return GetValue(rref).
So internally the value is "converted to a boolean". However, since this is never exposed -- and the entire semantic explanation is an abstraction which can be/is "optimized out" -- the behavior of && and || can be simply explained through using truthy-and-falsy values (for which ToBoolean covers: a truthy-value is one for which ToBoolean returns true, all other values are falsy).
The logical table for && is:
a b result
truthy any b
falsy any a
The logic table for || is:
a b result
truthy any a
falsy any b
Note that either the evaluation of a or b is returned.
Happy coding.
For completeness, from section 9.2:
The abstract operation ToBoolean converts its argument to a value of type boolean as ...
*
*Undefined - false
*Null - false
*boolean (not Boolean object!) - The result equals the input argument (no conversion).
*number (not Number object!) - The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
*string (not String object!) - The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
*Object - true
A: They do convert the values to boolean, but only to determine how to proceed in evaluating the expression. The result of the expression is not necessarily boolean (in fact, if neither of your operands are boolean, it will not give you a boolean):
var x = false || 'Hello' // gives you 'Hello'
var y = 0 && 1 // gives you 0, because 0 is "falsy" and short circuits
var z = 1 || 2 // gives you 1, because 1 is "truthy" and short circuits
A: The operands are interpreted as booleans for evaluating the expression, but the return value of && or || is always one of the operands.
For example:
true && 0 === 0, not false
1 || false === 1, not true
A: Because JavaScript has an idea of truthiness that covers more than booleans.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Picassa Data Feed API I know it's old hat (relatively) but I can't seem to get the API to return rows passed 1,000, though the results from a query of show open search total results well exceeding that number.
https://picasaweb.google.com/data/feed/api/all?q=elephants&start-index=1&max-results=11&v=2&prettyprint=true&alt=json&strict=true&kind=photo
Am I mis-interpreting the return of:
"openSearch$totalResults": {"$t": 195717},
Combinations of start-index and max-result that exceed 1,001 return an error of "Too many results requested".
A: The API doesn't support returning more than 1000 results for a query. If you need more results, you will have to refine your search query.
A: It returns same error if your start-index is past total number of results available.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the best way to test a RedirectToAction? I have the following condition
if (_ldapAuthentication.IsAuthenticated (Domain, login.username, login.PassWord))
{
_ldapAuthentication.LogOn (indexViewModel.UserName, false);
_authenticationService.LimpaTentativas (login.username);
return RedirectToAction ("Index", "Main");
}
being true, it redirects to another page .. what would be best to do a test?
A: In a unit test, you'd just assert on the ActionResult returned by your controller.
//Arrange
var controller = new ControllerUnderTest(
mockLdap,
mockAuthentication
);
// Mock/stub your ldap behaviour here, setting up
// the correct return value for 'IsAuthenticated'.
//Act
RedirectResult redirectResult =
(RedirectResult) controller.ActionYouAreTesting();
//Assert
Assert.That( redirectResult.Url, Is.EqualTo("/Main/Index"));
A: To avoid possible InvalidCastExceptions in your unit test, this is what i always do:
//Arrange
var controller = new ControllerUnderTest(
mockLdap,
mockAuthentication
);
// Mock your ldap behaviour here, setting up
// the correct return value for 'IsAuthenticated'.
//Act
var result = controller.ActionYouAreTesting() as RedirectToRouteResult;
// Assert
Assert.NotNull(result, "Not a redirect result");
Assert.IsFalse(result.Permanent); // Or IsTrue if you use RedirectToActionPermanent
Assert.AreEqual("Index", result.RouteValues["Action"]);
Assert.AreEqual("Main", result.RouteValues["Controller"]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Possibilities of SQL Injection with EFCTP and .net mvc Just want to know from experts that is there any inbuilt security for SQL Injection in Entity Framework or .net MVC?
Thanks
A: It is only built in if you use it. Entity Framework provides strongly typed entity classes - if you only use Linq to Entities you will be protected against SQL injection attacks, the same is true though if you use parametrized SQL with SQL server directly.
Having said that, you can still shoot yourself in the foot if you use EF store queries - this can be plain old SQL - so make sure you use SqlParameter here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Higher-order functions in C++, using std::wcout fails with error C2248 I'm playing around with implementing functional-style stuff in C++. At the moment, I'm looking at a continuation-passing style for enumerating files.
I've got some code that looks like this:
namespace directory
{
void find_files(
std::wstring &path,
std::function<void (std::wstring)> process)
{
boost::filesystem::directory_iterator begin(path);
boost::filesystem::directory_iterator end;
std::for_each(begin, end, process);
}
}
Then I'm calling it like this:
directory::find_files(source_root, display_file_details(std::wcout));
...where display_file_details is defined like this:
std::function<void (std::wstring)>
display_file_details(std::wostream out)
{
return [&out] (std::wstring path) { out << path << std::endl; };
}
The plan is to pass a continuation to find_files, but to be able to pass composed functions into it.
But I get the error:
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' :
cannot access private member declared in
class 'std::basic_ios<_Elem,_Traits>'
What am I doing wrong? Am I insane for trying this?
Note: my functional terminology (higher-order, continuations, etc.) is probably wrong. Feel free to correct me.
A: In display_file_details, you need to take your wostream by reference. iostream copy constructors are private.
A: Upon looking more deeply into the compiler output, I found this:
This diagnostic occurred in the compiler generated function
'std::basic_ostream<_Elem,_Traits>::
basic_ostream(const std::basic_ostream<_Elem,_Traits> &)'
It turns out that basic_ostream doesn't have an available copy constructor.
Changing std::wostream out to std::wostream & out fixes it. At least to the point that I get a bunch of other errors. These were easily fixed by:
std::for_each(begin, end,
[&process] (boost::filesystem::directory_entry d)
{ process(d.path().wstring()); });
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does a base class with the metadata [Bindable] keyword automatically extends EventDispatcher? I'm encountering something a bit bizarre, but maybe someone else came across this before.
I've got a base class, that doesn't extend anything. Let's call it...
public class FooBar {
//...
}
But I want to bind EVERY single one of its exposed properties:
[Bindable] public class FooBar {
public var propertyOne:String;
public var propertyTwo:String;
}
While Debugging / Profiling the class, I'm noticing that each time a property is changed - the instance of FooBar is calling ".dispatchEvent()" on it. But my class doesn't extend EventDispatcher.
What gives?
Does this mean, at compile time, my class automatically extends EventDispatcher or some other class with the ability to dispatch events? How could I listen to the PropertyChangeEvent if my class doesn't have the "addEventListener" method declared in it?
A: When you use the [Bindable] metadata the Flex compiler generates a lot of code for you. If you want to know what happens exactly take a look at the answers to What does the Flex [Bindable] tag do? and the links that are posted there.
To answer your question: No, your class doesn't extend EventDispatcher. However, the compiler changes your class so that it will implement the IEventDispatcher interface. The generated implemenation of that interface uses an instance of EventDispatcher.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Relationship between form and formset on same webpage I'm trying to relate all the objects created in a formset to an object created on the same webpage as the formset. So, an example of the code is this:
def create_b(request):
SpeciesFormSet = modelformset_factory(Species, fields=('common', 'scientific'))
if request.method == 'POST':
formset = SpeciesFormSet(request.POST)
form1 = BForm(request.POST)
if form1.is_valid():
objcreate = BModel.objects.create(
name = form1.cleaned_data['name'],
...
)
objcreate.save()
for forms in formset.forms:
if forms.is_valid():
formset1 = Species.objects.create (
common = forms.cleaned_data['common'],
scientific = forms.cleaned_data['scientific'],
BName = form1.cleaned_data['name']
)
formset1.save()
else:
formset = SpeciesFormSet()
form1 = BForm()
c = {'SpeciesFormSet' : SpeciesFormSet, 'form1' : form1}
c.update(csrf(request))
return render_to_response('Forms/create_b.html', c)
return HttpResponseRedirect('/accounts/profile')
else:
formset = SpeciesFormSet()
form1 = BForm()
c = {'SpeciesFormSet' : SpeciesFormSet, 'form1' : form1}
c.update(csrf(request))
return render_to_response('Forms/create_b.html', c)
The problem I'm having is that when trying to relate the formset object to the form one, it tells me that the form object doesn't actually exist. It creates the object in the database however, just none of the formset objects. I get the error "Cannot assign "u''": "Species.BName" must be a "BModel" instance." if that helps. Also, the relationship is a ForeignKey. Is there anyway to solve this? Thanks for your time.
A: This exact pattern is what inline model formsets are for.
A: From the error, it looks like you are assigning a BName where the property is supposed to be a BModel. Either, you want to change the BName with a BModel, or you need to fix your models so they match with a BName for the Species.
formset1 = Species.objects.create (
common = forms.cleaned_data['common'],
scientific = forms.cleaned_data['scientific'],
BName = form1.cleaned_data['name']
)
formset1.save()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Trying to understand CakePHP cookies & authentication I'm trying to figure out CakePHP cookies and meet my slightly unusual authentication requirements.
I have a CakePHP-based data collection system that is now being integrated with a reporting system built with COTS software. The reporting system needs to be access controlled and unless I want to duplicate all user accounts in both systems I need the reporting system to be able to find out if the user is authenticated in my CakePHP system.
The reporting system permits me to load a Java class and execute a function when the client's report request first arrives. So my idea was to
*
*Inspect the incoming report request and extract the cookie used by my CakePHP site for authentication / session identification
*Send a request from the Java function to a 'reportauth' action within the CakePHP site with this cookie attached
*The reportauth action within CakePHP then checks if the user is logged in to the CakePHP site and returns an encrypted response to the Java function identifying the user's role
I can get the cookie, send it in a request, and separately I can share encrypted information between PHP and Java.
However, when I use a 'fresh' cookie (the cookie that my browser repeatedly sends with requests to the CakePHP site after a new login) in my Java request the response says the user is not logged-in. If I then reload the site in my browser I have been logged-out. I suspect that there may be some extra information in the cookie about user-agent (?) that causes the Java-sourced request to be thrown out and that session destroyed for safety, but I don't know the system well enough. I think I might be seeing CakePHP protecting against session hijacking (which, ordinarily, would make me happy).
Can anyone tell me if there is a way around this issue? Preferably one that doesn't involve custom auth components in CakePHP as the data collection site is already live and my reporting deadline is not far away.
Any help much appreciated.
A: One workaround:
Get CakePHP to store a random token in a separate cookie, and as a field in the user table.
Then get the Java application to grab the token, and send it to the cakephp application to get the user's details.
Alternatively, have it authenticate with the CakePHP app itself, and pass in the session id to have cake use the right session. Note, setting with that function needs to be done before session_start() is called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to sort/order data? I've already experiences with MongoDB, CouchDB, Redis, Tokyo Cabinet, and other NoSQL Databases. Recently I stumbled upon Riak and it looks very interesting to me. To getting started with it, I decided to write a small Twitter clone, the "hello world" in the NoSQL World. To get a fully working clone, it's necessary to order the tweets chronologically. After reading the Riak docs I discovered that Map-Reduce is the right tool for this job. In my development-environment it works quite well, but how's the performance in production, with hundreds of parallel queries? Are there other, maybe faster, methods for sorting data, or is it possible to store data in an ordered form (like Cassandra)?
I think I've found another solution to this problem - a simple linked list. So one possible implementation could be, that every user gets his/her own "timeline bucket", where links to the tweets-data itself gets stored (tweets gets stored separately in the "tweets" bucket). As you would know, this timeline-bucket must contain a key named "first", which links to the latest timeline-object and is the starting point of the list. To insert a new tweet in the timeline, just insert a new item in the timeline bucket, set the "next"-link of this new item to the "first"-item, after that, make the new item to "first".
In short: Insert an item as you would do in a linked list...
As with Twitter, the personal timeline just holds 20 tweets shown to the user. To receive the last 20 tweets, there are only 2 queries necessary. To speed things up, the first query uses the link-walking ability of Riak to get the latest 20 objects, tagged by "next". Finally, the second, and last query uses the keys computed by the first query to receive the tweets itself (using map/reduce).
To remove the tweets of users you've just unfollowed, I would use the secondary index ability of Riak 1.0 to receive the related timeline-objects/tweets.
A: It is not possible to store data in an ordered form in Riak without resorting to re-writing portions of the Riak core. Data is stored, roughly, in bucket + key order. The actual order depends on the backend storage mechanism that you're using for Riak.
Riak 1.0 has some features that might help you, too. There's support for secondary indexes as well as improvements to Map Reduce operations - in particular, they perform much better in highly concurrent scenarios.
Alexander Siculars wrote an article about Pagination with Riak. It outlines the problem pretty well. Yammer also make extensive use of Riak and two of their engineers put together a presentation about Riak at Yammer. It doesn't go into a lot of implementation details, but you can learn a lot about how they have designed their solution.
Combining secondary index queries and Map Reduce makes it possible to solve your problem very easily.
A: As Jeremiah says it's not possible to store the data in sorted order, but you can still make it return sorted results by using secondary indexes and map/reduce. The problem, as described, is that you can't efficiently limit the query in a sorted way.
Here is an example using range query to list all keys and then sorting them using the built in functions in *riak_kv_mapreduce*::
{ok, Pid} = riakc_pb_socket:start_link("127.0.0.1", 8087),
riakc_pb_socket:mapred(Pid
, {index, colonel_riak:bucket(context), <<"$key">>, <<0>>, <<255>>}
, [{reduce, {modfun, riak_kv_mapreduce, reduce_sort}, none, true}])
You can use functions in the lists module in erlang or use the native javascript sort function. Order by can be achieved by lists:reverse/1 in erlang.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Open Graph custom action that links to other user I have question about the beta Open Graph stuffs.
The documentation I am looking at is this https://developers.facebook.com/docs/beta/opengraph/
I successfully define custom objects and actions. However, I cannot figure out how to link current user with other users.
For example, say I define a custom action 'kick'. I want the current user to be able to 'kick' one of his/her friends.
The closest object I can think of is 'profile', but when I pass user_id, 'http://www.facebook.com/profile.php?id=', or http://graph.facebook.com/, it does not work.
This is the requests I tried
POST https://graph.facebook.com/me/myapp:kick?access_token=abc&profile=http%3A%2F%2Fwww.facebook.com%2F123
POST https://graph.facebook.com/me/myapp:kick?access_token=&profile=123
POST https://graph.facebook.com/me/myapp:kick?access_token=abc&profile=http%3A%2F%2Fwww.facebook.com%2Fprofile.php%3Fid%3D123
POST https://graph.facebook.com/me/myapp:kick?access_token=abc&profile=http%3A%2F%2Fgraph.facebook.com%2F123
This is the response I get
{"error":{"message":"An unexpected error has occurred. Please retry your request later.","type":"OAuthException"}}
A: The profile given is for an external website. They call it external profile. Pretty misleading terms.
As you can see I used the following
curl -F 'access_token=TOKEN' \
-F 'profile=http://graph.facebook.com/zuck' \
'https://graph.facebook.com/me/MYAPP:kick'
And it gave the above.
I guess you can fill the external profile with meta info from the Facebook users and it will show alright (for example I can send the profile URL facebook.com/zuck instead), but it seems backwards, inefficient and not the intended usage.
For example feeding it my link.
curl -F 'access_token=TOKEN' \
-F 'profile=http://facebook.com/username' \
'https://graph.facebook.com/me/MYAPP:kick'
But the thing is ... I am not a musician.
It does though seem to look alright in aggregation view.
Which is interesting/weird since one of objects shown in this picture is a Facebook profile, so you would think they would give an example with Facebook profiles as objects.
Though they did say
We are now extending the Open Graph to include arbitrary actions and objects created by 3rd party apps and enabling these apps to integrate deeply into the Facebook experience
Which most likely means they want you to create arbitrary objects outside of Facebook.
Can you still link to other users?
Yes, but through tagging using tags=FacebookID1,FacebookID2 but it will be in the form of
phwd kicked a musician with Friend1 and Friend2 on [APP NAME]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7601998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Confused over function call in pre-ANSI C syntax I'm dealing with some pre-ANSI C syntax. See I have the following function call in one conditional
BPNN *net;
// Some more code
double val;
// Some more code, and then,
if (evaluate_performance(net, &val, 0)) {
But then the function evaluate_performance was defined as follows (below the function which has the above-mentioned conditional):
evaluate_performance(net, err)
BPNN *net;
double *err;
{
How come evaluate_performance was defined with two parameters but called with three arguments? What does the '0' mean?
And, by the way, I'm pretty sure that it isn't calling some other evaluate_performance defined elsewhere; I've greped through all the files involved and I'm pretty sure the we are supposed to be talking about the same evaluate_performance here.
Thanks!
A: If you call a function that doesn't have a declared prototype (as is the case here), then the compiler assumes that it takes an arbitrary number and types of arguments and returns an int. Furthermore, char and short arguments are promoted to ints, and floats are promoted to doubles (these are called the default argument promotions).
This is considered bad practice in new C code, for obvious reasons -- if the function doesn't return int, badness could ensure, you prevent the compiler from checking that you're passing the correct number and types of parameters, and arguments might get promoted incorrectly.
C99, the latest edition of the C standard, removes this feature from the language, but in practice many compilers still allow them even when operating in C99 mode, for legacy compatibility.
As for the extra parameters, they are technically undefined behavior according to the C89 standard. But in practice, they will typically just be ignored by the runtime.
A: The code is incorrect, but in a way that a compiler is not required to diagnose. (A C99 compiler would complain about it.)
Old-style function definitions don't specify the number of arguments a function expects. A call to a function without a visible prototype is assumed to return int and to have the number and type(s) of arguments implied by the calls (with narrow integer types being promoted to int or unsigned int, and float being promoted to double). (C99 removed this; your code is invalid under the C99 standard.)
This applies even if the definition precedes the call (an old-style definition doesn't provide a prototype).
If such a function is called incorrectly, the behavior is undefined. In other words, it's entirely the programmer's responsibility to get the arguments right; the compiler won't diagnose errors.
This obviously isn't an ideal situation; it can lead to lots of undetected errors.
Which is exactly why ANSI added prototypes to the language.
Why are you still dealing with old-style function definitions? Can you update the code to use prototypes?
A: Even standard C compilers are somewhat permissive when it comes to this. Try running the following:
int foo()
{
printf("here");
}
int main()
{
foo(3,4);
return 0;
}
It will, to some's surprise, output "here". The extra arguments are just ignored. Of course, it depends on the compiler.
A: Overloading doesn't exist in C so having 2 declarations would not work in the same text.
That must be a quite old compiler to not err on this one or it did not find the declaration of the function yet!
Some compilers would not warn/err when calling an undefined function. That's probably what you're running into. I would suggest you look at the command line flags of the compiler to see whether there is a flag you can use to get these warnings because you may actually find quite a few similar mistakes (too many parameters is likely to work just fine, but too few will make use of "undefined" values...)
Note that it is possible to do such (add extra parameters) when using the ellipsis as in printf():
printf(const char *format, ...);
I would imagine that the function had 3 parameters at some point and the last was removed because it was unused and some parts of the code was not corrected as it ought to be. I would remove that 3rd parameter, just in case the stack goes in the wrong order and thus fails to send the correct parameters to the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: keeping dialog open on validation failure Trying to achieve this without Ajax..
javascript
jQuery(function () {
// Modal Login.
jQuery(".ModalBoxLogin").dialog({
autoOpen: false,
bgiframe: true,
height: 155,
resizable: false,
draggable: false,
width: 353,
modal: true,
open: function (type, data) {
// Hide Close
jQuery(".ui-dialog-titlebar-close").hide();
// include modal into form
jQuery(this).parent().appendTo(jQuery("form:first"));
//clear all text.
jQuery(this).find(':text').val('');
jQuery(this).find(':password').val('');
},
close: function () {
//clear all text.
jQuery(this).find(':text').val('');
jQuery(this).find(':password').val('');
}
});
});
HTML
<%--Login Dialog--%>
<asp:Panel ID="pnlLogin" runat="server" CssClass="ModalBoxLogin" title="LOGIN">
<div class="ModalBox_conteudo">
<div class="ModalBox_esq">
<asp:Label ID="lblEmail" Text="E-MAIL:" runat="server" />
<asp:Label ID="lblSenha" Text="SENHA:" runat="server" />
</div>
<div class="ModalBox_dir">
<asp:TextBox ID="txtEmail" runat="server" placeholder="Digite o seu e-mail" />
<br />
<asp:TextBox ID="txtSenha" TextMode="Password" runat="server" placeholder="Digite a sua senha"/>
<br />
<asp:LinkButton ID="btnLogar" runat="server" CssClass="btnOk" OnClick="btnLogar_Click" />
<br/>
<asp:Label ID="lblMensagemLogin" runat="server"></asp:Label>
<asp:Literal ID="litScriptLogin" runat="server"></asp:Literal>
</div>
<div class="ModalBox_links">
<asp:HyperLink ID="hlCadastroLogin1" NavigateUrl="" Text="Ainda não tem cadastro?" runat="server" />
<span> | </span>
<asp:HyperLink ID="hlCadastroLogin2" NavigateUrl="" Text="Esqueceu a senha?" runat="server" />
</div>
</div>
</asp:Panel>
CS
protected void btnLogar_Click(object sender, EventArgs e)
{
ControllerCliente controllerCliente = new ControllerCliente();
controllerCliente.Cliente.Email = txtEmail.Text;
controllerCliente.Cliente.Senha = Util.Criptografar(txtSenha.Text);
controllerCliente.Carregar();
if (controllerCliente.Cliente.ClienteCodigo > 0)
{
hlLogin.Visible = false;
hlCadastro.Visible = false;
lblP.Text = "Olá " + controllerCliente.Cliente.Nome;
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "dialog", "alert('oi');", true);
//litScriptLogin.Text = "<script>alert('teste');</script>";
//litScriptLogin.Text = "<script>getElementById('" + pnlLogin.ClientID + "').style.display='none';</script>";
//pnlLogin.Style["display"] = "none";
}
else
lblMensagemLogin.Text = "Email ou senha inválido.";
}
If i use updatePanel in this section:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="btnLogar" runat="server" CssClass="btnOk" OnClick="btnLogar_Click" />
<br/>
<asp:Label ID="lblMensagemLogin" runat="server"></asp:Label>
<asp:Literal ID="litScriptLogin" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
the dialog does not close when i succeed.
Any way that i am missing ?
Regards
EDIT: Just adding some stuff...
javascript Call:
/* Modal */
jQuery(".ModalBoxOpenLogin").live("click", function myfunction() {
jQuery(".ModalBoxLogin").dialog("open");
});
jQuery(".ModalBoxOpenCadastro").live("click", function myfunction() {
jQuery(".ModalBoxCadastro").dialog("open");
});
HTML Call:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:HyperLink ID="hlLogin" runat="server" Text="Log in" CssClass="menu_log_menu ModalBoxOpenLogin"></asp:HyperLink>
<asp:Label ID="lblP" runat="server" Text="|" style="margin-left:5px; cursor:default;color:#CCCCCC;" ></asp:Label>
<asp:HyperLink ID="hlCadastro" runat="server" Text="Cadastre-se" CssClass="menu_log_menu ModalBoxOpenCadastro"></asp:HyperLink>
</ContentTemplate>
</asp:UpdatePanel>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I configure emacs to switch to a particular buffer when I click the mouse in it? I'm using iTerm2 on my mac to ssh into a Linux box and run emacs in the terminal. On a big monitor, I like to split the window to see multiple buffers side-by-side. I'd like to be able to switch to a particular buffer by clicking the mouse in it (rather than doing C-x o).
What seems to be happening is that if I click the mouse anywhere outside the currently active buffer e.g. in the next buffer, on the mode line etc., the click is being interpreted as which is bound to (tmm-menubar-mouse EVENT).
I have disabled the menubar by doing the following in my .emacs_d/init.el:
(menu-bar-mode -1)
This seems to disable the visible display of the menu bar at the top of the window, but the mouse click behavior I described is still happening.
I think what I need is to have the click interpreted as something other than and then bind that to some function that detects which buffer the click happened in and switch to it. But, I don't know how to do that and the searching I've done hasn't yielded any clear answer. Can anyone help?
Alternatively, I looked into using windmove to enable switching between buffers with SHIFT and the arrow keys. I did (windmove-default-keybindings) but emacs then seems to respond to SHIFT left-arrow by inserting "2C" into the buffer and SHIFT-right-arrow by inserting "2D". If anyone has any tips on making this work too, I'd love to hear them.
Thanks
A: I ran into this problem a while ago, where clicking on column > 95 was interpreted as <menu-bar> <mouse-1>, which invokes tmm-menubar-mouse. It turned out to be a bug:
http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6594
There hasn't been a formal release since this bug was fixed, but you can get the patch here:
http://bzr.savannah.gnu.org/lh/emacs/emacs-23/revision/100618
If I recall correctly, you should be able to just drop the modified file into your existing emacs installation and byte-compile it (assuming you're running the 23.3.1, the latest release).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to resize barcode generated by barbecue api? I have generated the barcode using barbecue and now I want to resize the barcode as per my need. I tried with BufferedImage and then I got barcode with different size but then I get an additional black line under the barcode.
public class GenerateBarcode {
public static void main(String[] args) throws Exception {
String initialString = JOptionPane.showInputDialog("Enter the text here");
Barcode barcode = BarcodeFactory.createCode128(initialString);
BufferedImage bi = BarcodeImageHandler.getImage(barcode);
}
}
Here I want to resize "bi".
A: To resize any BufferedImage, you can create a new one and draw your old one on top of it with a scaling applied. For example:
double scale = 2;
BufferedImage scaledBi = new BufferedImage((int)(bi.getWidth()*scale), (int) (bi.getHeight()*scale), bi.getType());
Graphics2D g2 = scaledBi.createGraphics();
g2.drawImage(bi, 0, 0, scaledBi.getWidth(), scaledBi.getHeight(), 0, 0, bi.getWidth(), bi.getHeight(), null);
scaledBi now contains your scaled image. Note that this is not vector based, so I am not sure of the quality. To increase scaling quality, you can play with the rendering hints.
A: Try this code:
Barcode b = BarcodeFactory.create2of7(jTextField1.getText());
b.setBarHeight(5);
b.setBarWidth(1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: interacting with web services and android I want to make a request to a web services http://www.w3schools.com/webservices/tempconvert.asmx and I cannot get a OK respond and got 400 bad request instead.
Here is my AsyncTask doInBackground
protected String doInBackground(Void... params) {
String s=null;
try {
restclient client1 = new restclient("http://www.w3schools.com/webservices/tempconvert.asmx");
client1.AddParam("Celsius", "12");
client1.AddHeader("Content-Type", "text/xml; charset=utf-8" );
client1.AddHeader("SOAPAction", "http://tempuri.org/CelsiusToFahrenheit");
client1.Execute(RequestMethod.POST);
s = client1.getResponse();
return s;
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
I have a class for client1 that I got from a post (cant find the link for that now)
public class restclient {
public enum RequestMethod {
GET, POST
}
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public restclient(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value) {
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception {
switch (method) {
case GET: {
// add parameters
String combinedParams = "";
if (!params.isEmpty()) {
combinedParams += "?";
for (NameValuePair p : params) {
String paramString = p.getName() + "="
+ URLEncoder.encode(p.getValue(), "UTF-8");
if (combinedParams.length() > 1) {
combinedParams += "&" + paramString;
} else {
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
// add headers
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST: {
HttpPost request = new HttpPost(url);
// add headers
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty()) {
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url) {
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I've also included access for Internet
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
.....
</application>
I only get a bad request response when I tried to post. Do I need to use more parameters? I feel that the body is wrong, but I can't find a solution.
A: Are you sure that a POST is correct. When I do a GET for that URL in Chrome I get 200 OK. Maybe you should try changing to the following?
client1.Execute(RequestMethod.GET);
A: EDIT: I just saw your content-type header, have you tried "application/soap+xml"? Also, SOAP required POST I believe, GET will not work, so you're right to do POST.
EDIT2: That client class your using isn't going to work. You need to send a XML in the body of your POST request, wrapped in a SOAP XML wrapper. The XML needs to follow the structure of the WSDL for your endpoint. I would recommend using SOAP UI (link below) to figure out what the XML should look like. If you wanted to get fancy, you should create a class that will serialize to look exactly like the request the SOAP UI creates.
For SOAP services you can almost always access the WSDL by adding ?WSDL to the endpoint url:
http://www.w3schools.com/webservices/tempconvert.asmx?wsdl
If that doesn't work...
How to troubleshoot web services:
*
*Download and install SoapUi and get your SOAP request working by importing your WSDL and filling in required inputs
*Once your request is working install fiddler or some other proxy
*Change the URL of your request in SoapUI to localhost:8888 or whatever the name of your machine is and the port where your proxy is running (fiddler runs on 8888 by default).
*Make the same working request from SoapUI but to the new URL (localhost:8888 or whatever), the request will fail, but fiddler will have captured your request
*Now in your android code, change the URL of the SOAP request to localhost:8888 and make the request, this will also fail but fiddler will have captured your request
*Look at the two requests and compare them. Start by looking at the headers and then the SOAP wrapper/xml.
I've done exactly this a million times, it's a guaranteed method to find the difference between two requests. Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Understanding attachEvents I mean the one in Ext.grid.feature.Feature;
it is used for example in the grid Filters Plug in.
I've been looking in the source code but I can't find where is it called from.
I'd be very grateful if someone could answer me exactly how it works and which class or function calls it.
It would help me and others to understand this and other plugins.
A: See Ext.view.Table#attachEventsForFeatures. (This is Ext 4.0.2a.) Discovery path: the Ext.grid.Panel class uses a view internally to render the actual grid table, which is Ext.grid.View. This class extends Ext.view.Table which provides most of the 'feature' support. Another important class that provides hooks into the table markup generation is Ext.view.TableChunker.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "maven-resources-plugin prior to 2.4 is not supported by m2e" I'm having problems with m2e (Maven plugin into Eclipse IDE).
I see the following error:
maven-resources-plugin prior to 2.4 is not supported by m2e. Use maven-resources-plugin version 2.4 or later.
I have no idea how to resolve this error. I'm pretty sure it is an m2e issue (maybe a setup thing?).
Background:
*
*I'm attempting to build Tika v0.9
http://svn.apache.org/repos/asf/tika/tags/0.9/
*I can build using Maven from command line.
*I can build using Netbeans v7.0.1.
*I am running Maven 3.0.3.
*I am running Eclipse Indigo Service Release 1 (Build id: 20110916-0149)
*I am running m2e v1.0.100.20110804-1717
Thanks for any help.
Albert
A: In the tika.parent project you can find org.apache.apache.6 as parent:
<parent>
<groupId>org.apache</groupId>
<artifactId>apache</artifactId>
<version>6</version>
<relativePath />
</parent>
And in the pom.xml from org.apache apache you can find:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
First simple solution:
add the following into the pom of tika.parent under "build - pluginManagement - plugins" (line 230):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
...
And then ask the tika team to use a newer org.apache apache parent pom.
A: How did you import your project into eclipse? (the mvn eclipse:eclipse goal, or "import maven project" in Eclipse?)
Maybe this answer is of relevance: Error in POM.xml
A: Another solution which worked for me is :
1) Uninstall all the existing Maven plugins from Ecplise.
2) Then install Maven plugin from this location : http://m2eclipse.sonatype.org/sites/m2e
-Rushi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: SQL - match records from one table to another table based on several columns I have two tables:
tblhobby
+-------+-------+-------+-------+
| name |hobby1 |hobby2 |hobby3 |
+-------+-------+-------+-------+
| kris | ball | swim | dance |
| james | eat | sing | sleep |
| amy | swim | eat | watch |
+-------+-------+-------+-------+
tblavailable_hobby
+----------------+
| available_hobby|
+----------------+
| ball |
| dance |
| swim |
| eat |
| watch |
+----------------+
the sql query should take all the columns in tblhobby and match it with tblavailable_hobby. If all the hobbies match to the available_hobby, then the person is selected
the query should produce
+--------+
| name |
+--------+
| kris |
| amy |
+--------+
Please help
Thanks for the answers. I have inherited this database and not able to normalize it at the moment. however, I would like to add another twist to the question. Suppose:
+-------+-------+-------+-------+
| name |hobby1 |hobby2 |hobby3 |
+-------+-------+-------+-------+
| kris | ball | swim | dance |
| james | eat | sing | sleep |
| amy | swim | eat | watch |
| brad | ball | | dance |
+-------+-------+-------+-------+
I would like to get
+--------+
| name |
+--------+
| kris |
| amy |
| brad |
+--------+
how would i go about with it?
A: Poor DB design, but, assuming you have to live with it:
SELECT h.name
FROM tblhobby h
INNER JOIN tblavailable_hobby ah1
ON h.hobby1 = ah1.available_hobby
INNER JOIN tblavailable_hobby ah2
ON h.hobby2 = ah2.available_hobby
INNER JOIN tblavailable_hobby ah3
ON h.hobby3 = ah3.available_hobby
EDIT: Answering the twist proposed in the comments below.
SELECT h.name
FROM tblhobby h
LEFT JOIN tblavailable_hobby ah1
ON h.hobby1 = ah1.available_hobby
LEFT JOIN tblavailable_hobby ah2
ON h.hobby2 = ah2.available_hobby
LEFT JOIN tblavailable_hobby ah3
ON h.hobby3 = ah3.available_hobby
WHERE (h.hobby1 IS NULL OR ah1.available_hobby IS NOT NULL)
AND (h.hobby2 IS NULL OR ah2.available_hobby IS NOT NULL)
AND (h.hobby3 IS NULL OR ah3.available_hobby IS NOT NULL)
A: I know this doesn't answer your question directly, and others have pointed out that your table design is problematic. What it should look like is this:
Table: Person
Id Name
-------------
1 Kris
2 James
3 Amy
table: PersonHobby (Join table)
PersonId HobbyId
----------------
1 1 -- Kris likes to ball
1 2 -- " dance
1 3 -- " swim
2 4 -- James likes to eat
Table: Hobby
Id Name
--------------
1 Ball
2 Dance
3 Swim
4 Eat
etc.
This design uses the concept of a Join or Junction table that allows you make many-to-many relationships between data. In this case people and hobbies.
You then query the data like this:
SELECT *
FROM Person p
JOIN PersonHobby AS ph on p.Id = ph.PersonId
JOIN Hobby AS h on h.Id = ph.HobbyId
WHERE ... -- filter as you need to
The PersonHobbies table in my example takes a table of Persons and a table of Hobbies and enables relationships between Persons and Hobbies. I know this will probably look like more work to you... extra tables, extra columns. But trust us, this design will make your life much simpler in the near future. In fact, you're already feeling the pain of your design by trying to figure out a query which should be much simpler than it is against your current db.
I would like to produce a WHERE filter to match your requirements but I don't quite understand what you're after. Could you explain in some more detail?
A: You can use a query to transform your existing table into a "virtual table", which I think should be easier to work with. Save this SQL statement as qryHobbiesUnion.
SELECT [name] AS person, hobby1 AS hobby
FROM tblhobby
WHERE (((hobby1) Is Not Null))
UNION
SELECT [name], hobby2
FROM tblhobby
WHERE (((hobby2) Is Not Null))
UNION
SELECT [name], hobby3
FROM tblhobby
WHERE (((hobby3) Is Not Null));
I enclosed "name" in square brackets because it's a reserved word. And I aliased [name] as person to avoid problems with square brackets when using qryHobbiesUnion in a subquery later.
I assumed any "empty" values for hobby will be Null. If blanks could also be empty strings (""), change the WHERE clauses to a pattern like this:
WHERE Len(hobby1 & "") > 0
After you determine which version of the WHERE clause returns the correct rows, save the query and use it in another query.
SELECT sub.person
FROM
[SELECT qh.person, qh.hobby, ah.available_hobby
FROM
qryHobbiesUnion AS qh
LEFT JOIN tblavailable_hobby AS ah
ON qh.hobby = ah.available_hobby
]. AS sub
GROUP BY sub.person
HAVING (((Count(sub.hobby))=Count([sub].[available_hobby])));
Using your second set of sample data, that query returns the 3 person names you wanted: amy; brad; and kris.
If tblhobby contained a row for a person with all the hobby fields empty, this query would not include that person's name. That makes sense to me because it seems your intention is to identify the people whose hobby choices are all matched in tblavailable_hobby. So a person with no hobby selections has no matches. If you want different behavior, this will probably get uglier. :-)
A: Really you must learn more about relational databases. Your design isn't good. You should have table with people and a table with hobbies. Then you should have a table the relates the two tables by an ID.
Your tables should look likes this
TABLE: People
COLUMNS: PID (INT, Primary Key), NAME
TABLE: Hobbies
COLUMNS: HID (INT, Primary Key), Hobby
TABLE: PeoplesHobbies
COLUMNS: ID, PID, HID
THEN your query would look something like this
select * from people `p` inner join PeoplesHobbies `ph` on p.PID = ph.PID inner join on Hobbies `h` on ph.HID = h.HID where p.NAME = 'JOHN'
A: SELECT name
FROM tblhobby AS h
WHERE EXISTS
( SELECT *
FROM tblavailable_hobby AS ah1
WHERE h.hobby1 = ah1.available_hobby
)
AND EXISTS
( SELECT *
FROM tblavailable_hobby AS ah2
WHERE h.hobby2 = ah2.available_hobby
)
AND EXISTS
( SELECT *
FROM tblavailable_hobby AS ah3
WHERE h.hobby3 = ah3.available_hobby
)
A: Borrowing from Joe's answer:
SELECT h.name
FROM tblhobby h
LEFT JOIN tblavailable_hobby ah1
ON h.hobby1 = ah1.available_hobby
LEFT JOIN tblavailable_hobby ah2
ON h.hobby2 = ah2.available_hobby
LEFT JOIN tblavailable_hobby ah3
ON h.hobby3 = ah3.available_hobby
WHERE (h.hobby1 IS NULL OR ah1.available_hobby IS NOT NULL)
AND (h.hobby2 IS NULL OR ah2.available_hobby IS NOT NULL)
AND (h.hobby3 IS NULL OR ah3.available_hobby IS NOT NULL)
ypercube's answer can be similarly extended.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change line nr color in folded line in vim line number for folded line has the same color as fold text and it differs from colors in other lines. Is there posibility to change line number color here?
A: No.
Folded line takes presedence because it is "made of" several lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Page-tab: show overlay in iframe depending on Like I wanna add an overlay (already built the HTML 'n jQuery) to a custom iframe tab, that only shows if people haven't liked my client's page yet. Is this possible with the JS SDK? How would I go about this?
A: While this is better done server-side, you code use something like:
FB.api('/me/likes/PAGE_ID',function(response) {
if( response.data ) {
if( !isEmpty(response.data) )
alert('You are a fan!');
else
alert('Not a fan!');
} else {
alert('ERROR!');
}
});
// function to check for an empty object
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
The code is taken from my tutorial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is Plan B for when heroku goes down on your production app? This question is inspired by this recent outage:
https://status.heroku.com/incident/212
There doesn't seem to be much I can do here. I can't push at all, and pushing seemed to be what broke it in the first place. AFAIK, I can't switch over to a new server deployed on aws or elsewhere without fiddling with the DNS records. What should I do?
A: When you use an "all-in-one" service like Heroku you accept and understand than, in case of this kind of issue, you're in their hands and there's nothing you can do.
You can keep a backup system configured elsewhere but, from my point of view, this is a waste of time and resources because:
*
*it requires you to configure and clone all Heroku settings and features
*it's a double work
*in case of issues, the only way to redirect the traffic to your app is to change DNS settings. The change requires DNS changes to propagate
*if you can clone Heroku features, you might not want to use Heroku at all
It's a good idea to have an off-site backup of your application, database and features. But on the other side, these issues are the trade off of using this kind of services.
A: The only real thing you could do would be to not rely on a single service provider for your application. This means that you would need to break out the DNS from the hosting platform so that you can re-point to a different platform (such as AWS).
Depending on your hosting platform, there are different options, but in a nutshell, the key is to reduce single points of failure and have plans in place to switch over when things to fail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I refresh a "form element" when it is changed through a webbrowser control? I am using VB6 (yes, I know it's 10 years old :), but it works). VB.NET answers may work as well, so if you know the answer, please answer too!
I am "manually" setting a dropdown box in a form, yet the 'webbrowser' doesn't seem to update.
Here's an example
If you notice in the form, it has a place where it asks you to fill in a state. (I.e., california, etc). It looks like a javascript/DHTML popup box in MSIE (firefox doesn't do the same, so you need to use MSIE, since that is what the webbrowser control relies on). If I 'click' on the "state" field, a popup box appears. I then can say select "CA" for california, and it updates it. (It now says "CA").
If I progrmatically do it, I would do something like:
WebBrowser1.forms(2).elements(13).value = "CA" ' (sets it to 'california')
WebBrowser1.forms(2).elements(13).item(9).selected = true (makes sure it is 'selected')
However -- within the webbrowser control -- it still appears as if nothing has changed. (In reality it has, i.e., if I submit the form it will submit the correct info), but it just doesn't "update" it.
Do you have any idea how I can do a "forced" refresh (either progrmatically or through some javascript/dhtml refresh), that will correctly then 'update' the field to show that "CA" has been selected?
Thanks very much!
A: The last VB version I used was VB3 so forgive my VB grammar :)
If the change event has a handler that you want to simulate
WebBrowser1.forms(2).elements(13).item(9).fireEvent ("onchange",WebBrowser1.Document.createEventObject())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.