text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to print or echo rows when using COUNT(*) and SUM() I generated the below query for php using PHP-MYADMIN,
My question is how to print the 30 rows it generates? when i use "see quote" it just errors out.
i am trying to echo the rows with search term and count in < div >< /div > tags each in its own.
*
*Facebook 38 searches
*Another Feed 25 searches
*Timeline 18 searches
and so on to row 30.
$result=mysql_query($sql)
$sql = 'SELECT COUNT(*) AS `Rows`, `search`, SUM(searched) FROM `af_timeline_search` GROUP BY `search` ORDER BY SUM(searched) DESC LIMIT 0, 30 ';
/* top searches */
$sqlthis = mysql_query('SELECT COUNT(*) AS `Rows`, `search` FROM `af_timeline_search` GROUP BY `search` ORDER BY `Rows` DESC');
$num=mysql_num_rows($sqlthis);
$arrS = mysql_fetch_array($sqlthis);
$i=0;
while ($i < $num){
echo 'Search '.$arrS[$i].'';
$i++;
}
Screen Shot of Query in PHPmyadmin.
A: I think the best you can do is to take a look at this: mysql-fetch-array
There you'll find the answer on how to loop over that array :)
A: $result = mysql_query("SELECT * FROM YOURDATABASE");
while($row = mysql_fetch_array($result))
{
echo $row['search'] . " " . $row['somenumber'];
echo " searches";
}
mysql_close($con);
A: I have found the solution to this. Thank you all for your guidance. :-) "you all rock"
$sql = "SELECT COUNT(*) AS Rows, search, SUM(searched) FROM anotherfeed.af_timeline_search GROUP BY search ORDER BY SUM(searched) DESC";
$result=mysql_query($sql) or die ('Error! yo.');
$row = mysql_fetch_array($result);
echo '<pre>';
print_r($row);
echo '</pre>';
/* top searches with loop */
$sql = "SELECT COUNT(*) AS Rows, search, SUM(searched) FROM anotherfeed.af_timeline_search GROUP BY search ORDER BY SUM(searched) DESC LIMIT 0, 20";
$result=mysql_query($sql) or die ('Error! yo.');
while($row = mysql_fetch_array($result))
{
echo ' (';
echo urldecode($row['search']) . " " . $row['SUM(searched)'] . "";
echo ') ';
}
I am able to print the array, hopefully i can get the loop down with a while statement. Feel free to add a loop if you have or know one that is better... Thank You.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: The program compiler won't let me use "else" in the last 2 cases and I can't see why I can't find why cases 2,3 wont let me use else for the category selection but it lets me use it in case 1. Where is it falling apart? What code needs editing?
I fixed the elses I think but I got a new error that I've never seen before control cannot fall through from one case label('case3:') to another. What does this mean?
using System;
class Program
{
enum Numbers { standard = 1, express = 2, same = 3 };
const int A = 1, B = 2;
const int Y = 3, N = 4;
static void Main()
{
double cost, LB;
int Number_of_items;
int myNumbers;
char catagory;
char surcharge = 'Y';
Console.WriteLine("please enter the type of shiping you want");
Console.WriteLine("Enter 1:standard shipping.");
Console.WriteLine("Enter 2:express shipping.");
Console.WriteLine("Enter 3:same day shipping.");
myNumbers = int.Parse(Console.ReadLine());
switch ((Numbers)myNumbers)
{
case Numbers.standard:
Console.WriteLine("thankyou for chooseing standerd shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
catagory = char.Parse(Console.ReadLine());
{
if (catagory == 'A')
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 3 * Number_of_items;
Console.Write("is this shipment going to alaska or Hawaii? (Y or N)");
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 2.50;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
}
else
Console.Write("please enter the weight in pounds");
LB = double.Parse(Console.ReadLine());
cost = 1.45 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
} surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 2.50;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
break;
case Numbers.express:
Console.WriteLine("thankyou for chooseing Express Shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
catagory = char.Parse(Console.ReadLine());
if (catagory == 'A')
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 4 * Number_of_items;
{
Console.Write("is this shipment going to alaska or Hawaii? (Y or N)");
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 5.00;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
}
}
else
{
{
Console.Write("please enter the weight in pounds");
LB = double.Parse(Console.ReadLine());
cost = 2.50 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
}
}
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 5.00;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
break;
case Numbers.same:
Console.WriteLine("thankyou for chooseing Same Day Shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
catagory = char.Parse(Console.ReadLine());
if (catagory == 'A')
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 5.50 * Number_of_items;
Console.Write("is this shipment going to alaska or Hawaii? (Y or N)");
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
{
cost = cost + 8.00;
Console.WriteLine("Total cost is {0}.", cost);
}
}
else
{
Console.WriteLine("total cost is {0}.", cost);
}
}
else
{
{
Console.Write("please enter the weight in pounds");
LB = double.Parse(Console.ReadLine());
cost = 3.00 * LB;
surcharge = char.Parse(Console.ReadLine());
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
}
if (surcharge == 'Y')
{
cost = cost + 8.00;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
break;
}
Console.ReadLine();
}//End Main()
}
}
A: I tried to run your code through Lindent to fix the horrible formatting and it reported unmatched else. You have too many else statements in your code.:
indent: foo.c:93: Error:Unmatched 'else'
indent: foo.c:139: Error:Unmatched 'else'
indent: foo.c:164: Error:Unexpected end of file
(Yes, indent(1) is not intended for C#, but it works surprisingly well on most C-like languages, and in this case has pointed out at least two else statements that aren't properly matched. And don't worry about those specific line numbers -- this routine needs to be properly formatting and broken apart into smaller pieces -- trying to just bodge this together with a few correctly-placed {} isn't the right answer.)
Break apart your gigantic main() routine into smaller functions. (Your code duplicates the Alaska / Hawaii question six times -- that should be a separate routine right there. Maybe all yes / no questions should be handled through one routine: pass in the question and it'll do the prompt and return true or false for you.)
I strongly recommend using braces on your else clauses if you used them on your if clause:
This is fine:
if (foo)
/* statement */
else
/* single statement */
But if you ever need to use braces on the first block, then use them on the else block too:
if (foo) {
/* stuff */
/* more stuff */
} else {
/* use those braces! */
/* you will find reading your code far easier if you do */
}
Good luck.
A: You've got two problems here. The first is a couple of braces that shouldn't be there. i.e. these:
catagory = char.Parse(Console.ReadLine());
{ // <------- THIS ONE
if (catagory == 'A')
//
// skipped code
//
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
} /* <------- THIS ONE */ surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
The second problem (the one that is causing your control cannot fall through error) is the fact that the break statement for the Numbers.same case is inside a conditioned block of statements (in the else part of your if (catagory == 'A')). This means that it will be executed only when category is different from 'A', and not for every value of your variable. You just have to move the break after the brace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How can I set the duration of this jQuery animation proportionally? I've created a quick test to show what I'm trying to do:
http://jsfiddle.net/zY3HH/
If you click the "Toggle Width" button once, a square will take one second to grow to full width. Click it again, and it will take one second to shrink down to zero width.
However, click the "Toggle Width" button twice in rapid succession - the second time when the square has grown to only a small fraction of its total width (like 10%) - you'll notice that the animation still takes a full second to return the square to zero width, which looks awkward, IMO.
While that behavior is expected, I'd like the latter animation to happen in an amount of time that's proportional to the width that it's covering. In other words, if you click "Toggle Width" a second time when the square is at 10% of its total width, I'd like it to take about 1/10th of a second to shrink back to zero width.
It should be relatively easy (I think) to make the value of the duration property dynamic, calculated when the jQuery click handler is run, to measure the current width of the square and determine the duration accordingly.
However, am I missing a better way to do this? Does jQuery provide an easy way, or expose some sort of method or property to make this easier?
A: I don't think jQuery has any built-in utility for doing this. The math required to do what you want is fairly straightforward, however, so I'd suggest just going that route. Something like:
var expanded = false;
$('input').click(function() {
$('div').stop();
var duration;
if (expanded) {
duration = ($('div').width() / 100) * 1000;
$('div').animate({ width: '0' }, { queue: false, duration: duration });
expanded = false;
} else {
duration = ((100 - $('div').width()) / 100) * 1000;
$('div').animate({ width: '100px' }, { queue: false, duration: duration });
expanded = true;
}
});
Here's a working example: http://jsfiddle.net/zY3HH/2/
If you've got some free time on your hands, maybe you could make the duration interpolation logic a bit more generic and package it up as a jQuery extension/plugin.
A: This is what you want - http://jsfiddle.net/FloydPink/qe3Yz/
var expanded = false;
$('input').click(function() {
var width = $('div').width(); //gives the current width of the div as a number (without 'px' etc.)
if (expanded) {
$('div').animate({
width: '0'
}, {
queue: false,
duration: (width/100 * 1000)// (current width/total width * 1 sec in ms) });
expanded = false;
} else {
$('div').animate({
width: '100px'
}, {
queue: false,
duration: 1000
});
expanded = true;
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Prevent colorbox instance from closing Is it possible to prevent colorbox from being closed? I am using as a loading screen for a server side processing script and don't want it to be closed until finished.
$(function(){
$("#songPayBtn").click(function() {
$("#ccResultDiv").show();
$.fn.colorbox({width:"50%",
height:"50%",
inline:true,
href:"#ccResultDiv",
onClosed:function(){ <?php echo "window.location = \"http://rt.ja.com/trackdownload.php?trackid=" . $_SESSION['trackid'] . "\"";?> }
});
A: You can prevent your colorbox from closing and hide the close button by adding these options:
$("#myColorbox").colorbox({
escKey: false, //escape key will not close
overlayClose: false, //clicking background will not close
closeButton: false // hide the close button
});
This will also allow you to still use the $.colorbox.close() method when you are ready to close your colorbox.
A: It is indeed. You can redefine the close method before anything is initialized:
$.fn.colorbox.close = function(){};
This has to occur before the $(document).ready() function since it's during this that colorbox will take care of assigning its close method to elements and events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: CXX0030: Error: expression cannot be evaluated The short question:
Why am I see this in the Locals window for my IWICImagingFactory object while in my destructor?
The long explanation:
I am creating a IWICImagingFactory object in my CreateDeviceIndependentResources() function:
if (SUCCEEDED(hr))
{
hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&mpWICFactory)
);
}
I have checked hr after this and it is always S_OK.
Then in my CreateDeviceResources() function I pass a pointer to the IWICImagingFactory object in a call to LoadBitmapFromFile():
if(SUCCEEDED(hr))
{
hr = LoadBitmapFromFile(
mpRenderTarget,
mpWICFactory,
L".\\background.png",
0,
0,
&mpBackgroundBitmap);
}
The function LoadBitmapFromFile is exactly as it appears in the MSDN sample. You can see most of the code here: http://msdn.microsoft.com/en-us/library/dd756686%28v=VS.85%29.aspx
The return code from LoadBitmapFromFile() is S_OK. I now have a ID2D1Bitmap object which works fine.
I don't use the WIC factory for anything else. The problem occurs in my destructor when I try to SafeRelease() the WIC factory:
SafeRelease(&mpWICFactory);
SafeRelease() is defined as:
template<class Interface>
inline void SafeRelease(Interface** ppInterfaceToRelease)
{
if(*ppInterfaceToRelease != NULL)
{
(*ppInterfaceToRelease)->Release();
(*ppInterfaceToRelease) = NULL;
}
}
While in the destructor, if I expand the mpWICFactory object in the Locals window, I see the "CXX0030: Error: expression cannot be evaluated" errors. The screenshot below shows the Locals window right before calling SafeRelease() on the WICFactory object.
http://img21.imageshack.us/img21/9820/localsy.jpg
I then get an error:
Unhandled exception at 0x00d22395 in Program.exe: 0xC0000005: Access violation reading location 0x6df128f0.
What is the cause of this problem?
EDIT: Here is a full simple program demonstrating the problem:
Test.h
#ifndef TEST_H
#define TEST_H
#include <Windows.h>
#include <wincodec.h>
#include <d2d1.h>
class Test
{
public:
IWICImagingFactory *mpWICFactory;
Test();
~Test();
HRESULT Init();
};
template<class Interface>
inline void SafeRelease(Interface** ppInterfaceToRelease)
{
if(*ppInterfaceToRelease != NULL)
{
(*ppInterfaceToRelease)->Release();
(*ppInterfaceToRelease) = NULL;
}
}
#endif
Test.cpp
#include "Test.h"
Test::Test() : mpWICFactory(NULL)
{
}
Test::~Test()
{
SafeRelease(&mpWICFactory);
}
HRESULT Test::Init()
{
HRESULT hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&mpWICFactory)
);
return hr;
}
Main.cpp
#include <Windows.h>
#include "Test.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
PSTR cmdLine, int showCmd)
{
if(SUCCEEDED(CoInitialize(NULL)))
{
Test app;
app.Init();
CoUninitialize();
}
return 0;
}
A: The short answer is that the virtual function pointer 0x6df128e8 is invalid, so the debugger cannot dereference it. That's what it means by "expression cannot be evaluated".
So when the program slightly later tries to call one of the virtual functions, the pointer still doesn't work and you get an access violation.
The long and hard part if finding out exactly where your object is overwritten with an invalid value. Unfortunately it can be pretty much anywhere else in the program...
A: Try calling SafeRelease() right after initialization and see if it works.
Also, try invoking the clean up explicitly (with some sort of uninitialize function) instead of doing this at the destructor. When you leave clean up to destructors, sometimes you don't have full control over exactly what is being cleaned up when.
It could also be that you're destroying some dependent objects in the wrong order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Very new to jquery - why doesn't this work I simply want to shift the .icon to the right. trying to animate .icon by the amount of position().left
My code isn't working and I don't know why. I bet its very simple!!
<script>
$("li.menu-item").hover(function(){
var pos = $(this).position().left;
$(".icon").animate({left : pos+'px'}, 1500 );
});
</script>
</head>
<body>
<div id="menu-wrapper">
<ul id="main-nav">
<li class="menu-item"><a href="">Blog</a></li>
<li class="menu-item"><a href="">Sponsored</a></li>
<li class="menu-item"><a href="">Facebook</a></li>
<li class="menu-item"><a href="">Twitter</a></li>
<li class="menu-item"><a href="">About</a></li>
<li class="menu-item"><a href="">Contact</a></li>
</ul>
<div class="icon">move please</div>
</div><!-- //END menu-wrapper -->
</body>
css
#menu-wrapper { position: fixed; bottom: 50px; margin: 0 auto; text-align:center;}
.icon {
width: 9px;
height: 9px;
background: url(../images/plus-menu.png) no-repeat 0 0;
position: absolute;
left: -5px;
bottom: -4px;
}
#main-nav { line-height: 1.0; float: left; margin-bottom: 1em; }
#main-nav{list-style: none;}
#main-nav li a {
display: block;
position: relative;
text-decoration: none;
margin-right: 20px;
color: #b2b2b2;
line-height: 19px;
padding-bottom: 17px;
}
#main-nav li { float: left; position: relative; }
#main-nav li a:hover, #main-nav li a:active { color: #404040; }
Any help will be great
Thanks
A: Wrap your code in $(document).ready()
<script>
$(document).ready(function()
{
$("li.menu-item").hover(function(){
var pos = $(this).position().left;
$(".icon").animate({left : pos+'px'}, 1500 );
});
});
</script>
Check this beginner tutorial out for more info
A: Hum. With minimal modifications (stop()ping the animation on each new hover event, so stuff doesn't get chained), it seems to work in this fiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: why does this cause :show to get no layout at all: layout 'admin', :except => [:show] why does this cause :show to get no layout at all: layout 'admin', :except => [:show]
Is this the intended behavior? I'm forced to put a render :layout => 'application' in an otherwise empty def show end.
Shouldn't the show action default to the base layout?
A: This actually surprised me a bit and I had to go to the source to check. The answer is no, it does/should not default to the application layout. The conditions passed instead are used to determine if the action has a layout at all, hence the name of the mixed in method action_has_layout? (Rails 3).
I'd half expected it to behave like respond_to, which you can call multiple times to build up the conditions for different actions.
In any case you can easily handle this by sending a method to layout containing your logic (via a proc or a symbol referencing method), rather than defining an empty action simply to render a different layout.
For example:
layout :determine_layout
...
def determine_layout
# show gets application, the rest get admin
params[:action] == 'show' ? 'application' : 'admin'
# or, returning true would probably do it (and be more flexible in case
# the rest of your app swapped layouts to something other than application)
params[:action] == 'show' || 'admin'
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why my images are taking too much time to load? I've read about the LowProfileImageLoader. It will only load the image when the user can see it and will avoid blocking the UI thread.
I added it and tested on my application. All 25 images are from the exact same URL. With the default image it took a little to load but all other images were cached, and the scroll got super fast.
With the LowProfileImageLoader the images were not cached, it was loading 1 by 1 even though it was the exact same image. And when I scrolled down then up it would load the image all over again. And it takes a long time to load them.
Do I have to configure something to keep the images on cache? How do I configure this LowProfileImageLoader?
A: From what I understood by looking at a windows phone mango video presentation, images are automatically cached without you doing anything.
Video I'm talking about: http://www.wpcentral.com/multitasking-mango-demoed-detail
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Cannot generate a Pages controller in the Rails 3 tutorial I am working through the Michael Hartl Rails 3 tutorial, and I am currently on Chapter 3. The tutorial asks me to generate a Pages controller with actions for a Home page and a Contact page using the command line: "$ rails generate controller Pages home contact".
This is the output I get:
ruby 1.9.2p290 (2011-07-09) [i386-mingw32]
C:\Users\abcd\rails_projects2\sample_app>rails generate controller Pages home
contact
C:/Users/abcd/rails_projects2/sample_app/config/application.rb:8:in `require':
no such file to load -- sprockets/railtie (LoadError)
from C:/Users/abcd/rails_projects2/sample_app/config/application.rb:8:
in `<top (required)>'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/comman
ds.rb:15:in `require'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/comman
ds.rb:15:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
The contents of my config/application.rb file:
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module SampleApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
I have also discovered that when I try to run the command line "rails server", I get a similar error message. I don't know if this information is useful.
Thank you!
A: It looks like the tutorial is using Rails 3.0.9, but you've created your application using a later version of the Rails gem.
sprockets was added in version 3.1. Even though you've updated your Gemfile to specify Rails 3.0.9, the code that was generated when you ran rails new sample_app is expecting Rails 3.1 gems to be available (i.e. simply changing the Gemfile isn't enough to change the Rails version of the application).
You could try simply commenting out the reference to sprockets in your application.rb file, but even if that works for now it's likely there'll be other differences that'll cause errors later.
Your best bet is probably to start from scratch, but make sure you're using Rails 3.0.9. If you're using RVM, you could create a new gemset and install 3.0.9 into it, then use that gemset.
Alternatively, when you create the application specify the version of the gem you want in the command:
rails _3.0.9_ new sample_app
If you use this second method, then after you've created the application, simply using rails by itself to issue commands (like generate) should be okay, as Rails does some magic to determine the version of the app and use the right gem version, even if a later version is installed - you don't need to use rails _3.0.9_ all the time.
A: in your config/application.rb file, try to uncomment the "sprockets" line like this:
# require "sprockets/railtie"
Then check if it works afterwards... that should do the trick...
But if not, please check your Gemfile, it should look something like this:
# gem "rails", "~> 3.1.0" # or "3.0.9"
gem "rails" , "3.0.9"
gem 'sqlite3', '1.3.3' # or whatever DB you use
If that still doesn't help, check which version of sprockets you have installed:
in a shell, do a:
$ gem list | grep sprock
sprockets (2.0.0.beta.10)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to print a variable in Xcode I am new to Xcode.
I have variables x and y as random numbers from 1 to 100. I want the screen to print x and y when a button is pressed. How do I do that?
my code is:
- (IBAction)printtwonumbers:(id)sender;
{
x = arc4random() %100;
y = arc4random() %100;
label1 setText: [x];
label2 setText:[x];
}
A: XenElement is right if you want to print to the log. If you want to set the text of the labels though then your syntax is incorrect. In fact, if you are using that code you are probably getting a bunch of warnings and/or errors.
int x = arc4random() %10;
int y = arc4random() %100;
[label1 setText: [NSString stringWithFormat:@"%i", x];
[label2 setText: [NSString stringWithFormat:@"%i", y];
Take a look at the compiler warnings and you'll see why this code is what you need.
A: NSLog(@"Message Here: %d", x);
etc.
A: As noted by XenElement, NSLog is the basic method for printing to the console. printf also works as expected but there's little reason to use it.
I like to use Marcus Zarra's DLog macro. It gives a little more information than NSLog and it only prints to the console when you're running a debug build. The source is available on Marcus' blog.
To set the DEBUG flag, go to the build settings for the debug build and enter DEBUG under "Preprocessor Macros".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Continuously scrolling Gallery? I have a Gallery object that scrolls from left to right and back again. However, I would like to make this Gallery circle back on itself, that way when I get to my last View, the very first one is next and I can just keep scrolling. Any ideas? Thanks.
A: Galleries use an Adapter to back the data that they display. You can create a custom adapter where getCount() returns Integer.MAX_VALUE and getView() does a modulos the position with the number of images you have. This way it always returns the appropriate image for a given position.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I manage a website with Xcode? I'm starting a new web project, and I'm looking to learn more about Xcode at the same time, so I'm wondering if there's a good way to manage the project through Xcode?
In an ideal world, I would like the "Run" button to upload the final product files to the web server (or copy them to some local folder that is set to auto-sync using an FTP client) Then I would like it to launch safari (and a number of other test browsers) and have them open the home page.
Additional features that I think are possible:
Have local environment variables that are substituted by some kind of text find/replace action into HTML files as they are copied.
A: My advice is to stay away from XCode for Web development. While it can be done, it really isn't built for it and you will only make things much more difficult than it needs to be. If you really want to learn about XCode then use it for application development, not web development.
There are other IDEs out there specifically for web development that you might like. NetBeans, Coda, Expresso, etc. Personally, I enjoy using Expresso.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Securing the Identity of the Source Alice wants to know from Bob the location of a sensitive resource. Bob Kindly tells Alice the location, but how can Alice be sure of the identity of Bob?
Bob is a OpenBSD server, and the source of data is a Python/C++ App.
My Idea was:
Alice Knows Bob's public Key.
Alice encrypt a random string with Bob's Public Key, and send it to Bob.
Bob recover the random string, and hash it. Bob send back the sensitive resource, along with the hash.
The problem of this method is: Can I safely store a private key on Bob (the server)? How? Is there a better solution?
A: If Bob doesn't have a private key, then what else does Bob uniquely know that it can use to identify itself? And if you can't trust Bob to keep its private key safe, you're sunk no matter what you do.
If it's worthwhile spending the extra money, one thing you could do is have another machine (call it Cipherclerk) that is not online, can communicate only with Bob, and will only make certain kinds of communications. Cipherclerk holds the private key, and uses it to decrypt things for Bob. Then, even if Bob is compromised remotely, at least the private key isn't compromised with it.
An enhancement to your idea would be to have Bob use Alice's random string as a symmetric key to encrypt the resource.
A: This method is completely insecure if someone can mount a man in the middle attack. Mallory, the attack, can simply strip the the sensitive information out, substitute it with hers, and forward it on to Alice.
The solution is to use TLS or SSH. In either case, make sure Alice has bob's public key or key fingerprint. This is a widely used solution and is secure assuming no one can change the data Alice stores or read the data bob stores.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What alternative syntaxes are there for expressing XML? What human-readable and human-editable syntaxes exist that can be automatically converted to and from XML with no loss of expressivity. In other words, an updated version of this list. The three syntaxes mentioned there are:
*
*SOX
*PYX
*SLiP
Are there others? (This isn't about alternatives to XML, like JSON, but simply easier ways for humans to maintain XML files using a text editor).
A: Some more answers:
*
*CompactXML - one alternative general purpose XML syntax, looks fairly sensible
*SLAX - an alternative syntax for XSL. Looks like an odd hybrid of JavaScript, CSS, and...I'm not sure.
*RELAX NG - a schema language for XML (like XSL), with a compact alternative syntax.
And some useful links:
*
*XSugar - interesting paper about the problem
*XFlat - a general tool for converting between definable "flat" formats and XML. (So not a particular syntax)
*XSCS - a paper describing something very similar to CompactXML above. I think.
A: If you're looking for a good way to simply view and make small tweaks, I would highly recommend simply getting a beautifier and a text editor with code folding. Personally I use notepad++, but I'm sure there's dozens of others with those simple capabilities.
Ironically, I'm on SO right now as a break from an XML file I'm working on with broken indentation. The original developer had the indentation working well (it's in a non standard language for which the libraries are poor) but subsequent developers have given it... less care than it deserves.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Copy data from MS Access to MS Excel using Python I've been spending the better part of the weekend trying to figure out the best way to transfer data from an MS Access table into an Excel sheet using Python. I've found a few modules that may help (execsql, python-excel), but with my limited knowledge and the modules I have to use to create certain data (I'm a GIS professional, so I'm creating spatial data using the ArcGIS arcpy module into an access table)
I'm not sure what the best approach should be. All I need to do is copy 4 columns of data from access to excel and then format the excel. I have the formatting part solved.
Should I:
Iterate through the rows using a cursor and somehow load the rows into excel?
Copy the columns from access to excel?
Export the whole access table into a sheet in excel?
Thanks for any suggestions.
A: I eventually found a way to do this. I thought I'd post my code for anyone who may run into the same situation. I use some GIS files, but if you don't, you can set a variable to a directory path instead of using env.workspace and use a cursor search instead of the arcpy.SearchCursor function, then this is doable.
import arcpy, xlwt
from arcpy import env
from xlwt import Workbook
# Set the workspace. Location of feature class or dbf file. I used a dbf file.
env.workspace = "C:\data"
# Use row object to get and set field values
cur = arcpy.SearchCursor("SMU_Areas.dbf")
# Set up workbook and sheet
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
book.add_sheet('Sheet 2')
# Set counter
rowx = 0
# Loop through rows in dbf file.
for row in cur:
rowx += 1
# Write each row to the sheet from the workbook. Set column index in sheet for each column in .dbf
sheet1.write(rowx,0,row.ID)
sheet1.write(rowx,1,row.SHAPE_Area/10000)
book.save('C:\data\MyExcel.xls')
del cur, row
A: You can use ADO to read the data from Access(Here are the connection strings for Access 2007+(.accdb files) and Access 2003-(.mdb files)) and than use Excel's Range.CopyFromRecordset method(assuming you are using Excel via COM) to copy the entire recordset into Excel.
A: The best approach might be to not use Python for this task.
You could use the macro recorder in Excel to record the import of the External data into Excel.
After starting the macro recorder click Data -> Get External Data -> New Database Query and enter your criteria. Once the data import is complete you can look at the code that was generated and replace the hard coded search criteria with variables.
A: Another idea - how important is the formatting part? If you can ditch the formatting, you can output your data as CSV. Excel can open CSV files, and the CSV format is much simpler then the Excel format - it's so simple you can write it directly from Python like a text file, and that way you won't need to mess with Office COM objects.
A: I currently use the XLRD module to suck in data from an Excel spreadsheet and an insert cursor to create a feature class, which works very well.
You should be able to use a search cursor to iterate through the feature class records and then use the XLWT Python module (http://www.python-excel.org/) to write the records to Excel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add google chrome omnibox-search support for your site? When I enter some of URLs in Google Chrome omnibox, I see message in it "Press TAB to search in $URL". For example, there are some russian sites habrahabr.ru or yandex.ru. When you press TAB you'll be able to search in that site, not in your search engine.
How to make my site to be able for it? Maybe, I need to write some special code in my site pages?
A: Implementing omnibox support with search suggestions
The answer given by @element119 works perfect but here is a slightly tweaked code to support search suggestions as well as Mozilla Support.
Follow the steps below to implement omni box support for your site.
*
*Save the following code as search.xml
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<script/>
<ShortName>Site Name</ShortName>
<Description>Site Description (eg: Search sitename)</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16" type="image/x-icon">Favicon url</Image>
<Url type="application/x-suggestions+json" method="GET" template="http://suggestqueries.google.com/complete/search?output=firefox&q={searchTerms}" />
<Url type="text/html" method="GET" template="http://yoursite.com/?s={searchTerms}" />
<SearchForm>http://yoursite.com/</SearchForm>
</OpenSearchDescription>
*Upload search.xml to the root of your site.
*Add the following meta tag to your site's <head> tag
<link rel="search" href="http://www.yoursite.com/search.xml" type="application/opensearchdescription+xml" title="You site name"/>
Make sure to replace the domain urls with your domain.
A: Chrome usually handles this through user preferences. (via chrome://settings/searchEngines)
However, if you'd like to implement this specifically for your users, you need to add a OSD (Open Search Description) to your site.
Making usage of Google Chrome's OmniBox [TAB] Feature for/on personal website?
You then add this XML file to the root of your site, and link to it in your <head> tag:
<link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml" />
Now, visitors to your page will automatically have your site's search information placed into Chrome's internal settings at chrome://settings/searchEngines.
OpenSearchDescription XML Format Example
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>Your website name (shorter = better)</ShortName>
<Description>
Description about your website search here
</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16" type="image/x-icon">your site favicon</Image>
<Url type="text/html" method="get" template="http://www.yoursite.com/search/?query={searchTerms}"/>
</OpenSearchDescription>
The important part is the <url> item. {searchTerms} will be replaced with what the user searches for in the omnibar.
Here's a link to OpenSearch for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "172"
} |
Q: PDF Reader/editor in Ajax/ASP.Net I am working on project that allows to read document within the browser without the need to install software , It's a part of a management application for companies.
I tried out to work with iTextSharp ,PDFSharp , but these labrories don't allows you to do what I want to do.It's just for generating pdf from HTML.
I checked out for another solution , I found an interesting project developed by Mozilla Lab . Mozilla is working on technology that will allow PDF documents to be rendered within the browser, rather than utilizing a browser plug-in or an external app to open them.
https://github.com/Marak/pdf.js/
I wonder to know Can I integer this script and use it with ASP.Net ? , If yes , I will be pleased to be guided by you with code source or external links that you recommend in order to implement this solution.
A: I believe that link you have sighted is about creating PDF file in browser (and not about showing existing PDF in browser).
Said that, there is another interesting project pdf.js that is trying to render PDF using java-script and HTML 5. Its essentially a java-script library that takes PDF bytes and attempt to render them. As such, you should able to integrate it in any web site regardless of server side technology - include the script and make relevant calls. See this simple example to get started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dereferencing type-punned pointer will break strict-aliasing rules I have a unsigned char pointer which contains a structure.Now I want to do the following
unsigned char buffer[24];
//code to fill the buffer with the relevant information.
int len = ntohs((record_t*)buffer->len);
where record_t structure contains a field called len. I am not able to do so and am getting the error.
error: request for member ‘len’ in something not a structure or union.
Then I tried:
int len = ntohs(((record_t*)buffer)->len);
so as to get the operator precedence right. That gave me:
warning: dereferencing type-punned pointer will break strict-aliasing rules.
then I declared
record_t *rec = null;
rec = (record_t*)
what am I doing wrong here?
A: You're getting that warning because you're breaking strict-aliasing by having two pointers of different types pointing to the same location.
One way to get around that is to use unions:
union{
unsigned char buffer[24];
record_t record_part;
};
//code to fill the buffer with the relavent information.
int len = ntohs(record_part.len);
EDIT:
Strictly speaking, this isn't much safer than your original code, but it doesn't violate strict-aliasing.
A: You might try this:
unsigned char buffer[sizeof(record_t)];
record_t rec;
int len;
// code to fill in buffer goes here...
memcpy(&rec, buffer, sizeof(rec));
len = ntohs(rec.len);
A: According to the C and C++ standards, it is undefined behaviour to access a variable of a given type through a pointer to another type. Example:
int a;
float * p = (float*)&a; // #1
float b = *p; // #2
Here #2 causes undefined behaviour. The assignment at #1 is called "type punning". The term "aliasing" refers to the idea that several different pointer variables may be pointing at the same data -- in this case, p aliases the data a. Legal aliasing is a problem for optimization (which is one of the main reasons for Fortran's superior performance in certain situations), but what we have here is flat-out illegal aliasing.
Your situation is no different; you're accessing data at buffer through a pointer to a different type (i.e. a pointer that isn't unsigned char *). This is simply not allowed.
The upshot is: You should never have had data at buffer in the first place.
But how to solve it? Make sure you have a valid pointer! There is one exception to type punning, namely accessing data through a pointer to char, which is allowed. So we can write this:
record_t data;
record_t * p = &data; // good pointer
char * buffer = (char*)&data; // this is allowed!
return p->len; // access through correct pointer!
The crucial difference is that we store the real data in a variable of the correct type, and only after having allocated that variable do we treat the variable as an array of chars (which is allowed). The moral here is that the character array always comes second, and the real data type comes first.
A: You probably have a warning level set that includes strict aliasing warnings (it used to not be default, but at one point gcc flipped the default). try -Wno-strict-aliasing or -fno-strict-aliasing -- then gcc should not generate the warnings
A reasonably good explanation (based on cursory glance) is What is the strict aliasing rule?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Avoid regenerating files that won't change I have a Makefile with several rules of this form
protolist.c: $(PROTOCOLS) Makefile src/genmodtable.sh
$(SHELL) $(srcdir)/src/genmodtable.sh \
$@ $(filter-out %Makefile %genmodtable.sh, $^)
As the name implies, protolist.c winds up containing a list of all the "protocols" defined by the .c files in $(PROTOCOLS). The contents of this file do formally depend on everything in $(PROTOCOLS), the Makefile, and the generator script, but it's very rare for the file to actually change when one of those .c files is edited. Therefore, genmodtable.sh is coded to not change the timestamp of protolist.c if it's not going to make any change to its contents. This causes Make to skip rebuilding protolist.o and its dependencies when it's not really necessary.
That all works fine; the problem is that, because protolist.c now appears to be out of date with respect to its dependencies, Make thinks it has to try to regenerate protolist.c on every run. This isn't a performance issue -- the script is very fast -- but it is confusing behavior. I dimly recall an idiom, involving timestamp files, that could be used to stop Make from doing this, but I have not been able to reconstruct it or find it described anywhere. Does anyone know what it is?
(Also if anyone can suggest how to get rid of that silly $(filter-out ...) construct, that would be helpful, as that is the only GNUmakeism in this Makefile.)
A: This appears similar to an issue with Fortran programming and make, involving the files generated when compiling a module. (Not relevant, other than that is where I picked up how to do this.)
What you want is have make compare the timestamp of protolist.o to the timestamp of protolist.c, which remains 'old', and make the decision to run the recipe for protolist.c, depending on the timestamp of, well, a timestamp file, which gets updated each time the recipe is run.
In order to make this work, you have to link the two together with an empty rule.
protolist.o: protolist.c
[...]
protolist.c: protolist.c.time ;
protolist.c.time: $(PROTOCOLS) Makefile src/genmodtable.sh
$(SHELL) $(srcdir)/src/genmodtable.sh \
protolist.c $(filter-out %Makefile %genmodtable.sh, $^)
touch protolist.c.time
In my own makefiles, I have to declare the timestamp files as prerequisites of the special target .PRECIOUS, to prevent make from deleting them, but I'm using pattern rules; I'm not 100% sure, but I think this isn't necessary when using explicit rules, like here.
To avoid the $(filter-out ...) construct, can you not simply replace it with $(PROTOCOLS)?
(Although, personally, I would stick to Paul's First Rule of Makefiles: Don't hassle with writing portable makefiles, use a portable make instead.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I get tooltip to hover on top of texboxes? Hello again dearest Experts,
I am still having issues getting tooltips to work correctly.
The code below works correctly as far displaying the tooltips.
The big issue is that it expands the textbox, making other textboxes lose alignment.
What we would like to is to have the message in the tooltop hover on top of the textbox but not obscure it. This way, users can still type into it.
Can the code I have below be modified to help me accomplish this?
Many thanks.
THe css
<style type="text/css">
div.activeToolTip
{
display:block;
visibility:visible;
background-color:#A1D40A;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 0.75em;
line-height: 1.50em;
font-weight:bold;
color: #fff;
border:1px solid black;
filter: progid:DXImageTransform.Microsoft.Shadow(color=gray,direction=135);
width:200px;
height:70px;
}
div.idleToolTip
{
display:none;
visibility:hidden;
}
Then textbox and tooltip.
<asp:TableCell><asp:TextBox ID="instruct" onmouseover="document.getElementById('toolTipDiv').className='activeToolTip'" onmouseout="document.getElementById('toolTipDiv').className='idleToolTip'" runat="server" Width="75px"></asp:TextBox>
<div id="toolTipDiv" class="idleToolTip">My instructions go here.</div>
A: The key is to make your tooltip position: absolute. This way you'll have exact control over where it appears and it won't affect the layout of any other elements.
The other thing you should do it put it in an element with position: relative set:
<div class="relative">
<input type="text" />
<div id="toolTipDiv" class="idleToolTip">My instructions go here.</div>
</div>
This will create the coordinate system for it (i.e.: bottom: 20px will translate to 20px from the bottom of the relative parent):
.relative {
position: relative;
}
#toolTipDiv {
position: absolute;
bottom: 20px;
left: 0;
}
Here's a demo of it in action.
A: edit: sorry, that was a complete brain fart. I need more sleep. display:absolute won't do anything, it's position:absolute
Can you show the problem in the jsfiddle?
A: I recommend you use a jQuery plugin, there are tons of them:
30 Stylish jQuery Tooltip Plugins For Catchy Designs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Jsp tag confusions i am new to jsp, I am currently studying an example i got from online. some tags confused me.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<link href="<s:url value="/resources/main.css"/>" rel="stylesheet" type="text/css"/>
<title><s:text name="label.employees"/></title>
</head>
<body>
<div class="titleDiv"><s:text name="application.title"/></div>
<h1><s:text name="label.employees"/></h1>
*
*in line 6, what is label here mean? does label.employees here define a new variable?
*in line 9, what is titleDiv and application.title? define new variables?
Thank you very much for your help.
A: On lines 6 and 9, the "label.employees" and "application.title" strings are parameters being passed to the Struts text tag. This is not defining a new variable, rather it is telling the Struts tag which already-defined variable it should consult in order to find the text that it is supposed to show.
As for "titleDiv", that is just a standard CSS class name. It has nothing to do with JSP or JSP tags. It works the same in a JSP page as it does in any standard HTML page.
You may find the reference documentation helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need a Way to Disable IE9 Browser Caching I have a Flash application that sends a getURL request for an image file every 60 seconds.
This works fine in all browsers except IE9 with Internet Option set to automatically check for newer versions of stored pages.
I setup Charles proxy (http://xk72.com) to watch the requests being sent by my flash app and confirmed that the request is being surpressed by IE9 when the setting is set to Auto, but works fine if I change the setting to check everytime I visit the webpage. This, however, is not an option! I need this to work in all browsers regardless of how the options are set.
Even if I do a page refresh (F5), the ASP page does not reload. The only way to get it to reload is close the browser and restart it.
I have tried adding content headers to disable caching but it does not appear to work.
For Example, here is my request headers:
HTTP/1.1 200 OK
Date Sun, 02 Oct 2011 23:58:31 GMT
Server Microsoft-IIS/6.0
X-Powered-By ASP.NET
Expires Tue, 09 Nov 2010 14:59:39 GMT
Cache-control no-cache
max-age 0
Content-Length 9691
Content-Type text/html
Set-Cookie ASPSESSIONIDACQBSACA=ECJPCLHADMFBDLCBHLJFPBPH; path=/
Cache-control private
I have read the Microsoft blog (http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx) which states that if I add the content headers, the browser should respect my request, but it obviously does not.
I don't think this is a Flash issue since the html page that holds the Flash object will not even reload.
A: You can append a random number to the end of the url.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: error message for test_ifinteger I keep on getting this error message:
"Microsoft JScript runtime error: The value of the property 'test_ifinteger' is null or undefined, not a Function object"
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
NZ Currency Converter
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test_ifinteger(testcontrol, nameoffield) {
var x = 0;
var isok1 = true;
var isok = true;
var teststring = testcontrol.value;
if (teststring.length == 0)
return true;
if (isNaN(teststring)) {
isok1 = false;
alert(nameoffield + " must be a number!");
testcontrol.focus();
return isok1;
}
else if (teststring < 0) {
isok = false;
alert(nameoffield + " must be nonnegative!");
testcontrol.focus();
return isok;
}
else if
(teststring.CharAt(x) < 0)
isok = false;
alert(nameoffield + " must be nonnegative!");
testcontrol.focus();
return isok;
}
else if {
while (x < teststring.length) {
if (teststring.charAt(x) == '-')
isok = false;
x++;
}
}
if (!isok1) {
alert(nameoffield + " must be a number!");
testcontrol.focus();
} //end else if(ok)
return isok1;
else if (!isok) {
alert(nameoffield + " must be nonnegative!");
testcontrol.focus();
}
return isok;
}
</script>
<form name="Currency">
<tr>
<td>
<input type="radio" name="convert" value="fromnzd" checked <%if (String.Compare((String) ViewData["convert"],"Y",false)==0) Response.Write("checked"); %> />Convert From NZD<br />
<input type="radio" name="convert" value="tonzd" <%if (String.Compare((String) ViewData["convert"],"Y",false)==0) Response.Write("checked"); %> />Convert To NZD
</td>
</tr>
<br /><tr>
<td colspan="2" align="right"> The other currency is:</td>
<td>
<select name="exchrate:">
<% List<Currency.Models.exchrate> exchrate = (List <Currency.Models.exchrate>) ViewData["exchrate"];
foreach (Currency.Models.exchrate st in exchrate)
{
%>
<option value="<% Response.Write(st.othercurrency);%>"><% Response.Write(st.othercurrency);%></option>
<% } %>
<option value=""></option>
</select
</td>
</tr>
<br />
<tr><td colspan="2" align="right"> You Wish To Convert: <input type="text" name="calculate" value="<%=ViewData["calculate"]%>" onblur="test_ifinteger (Currency.calculate,'Value')" /><td><input type="submit" name="submitter" value="Calculate"/></td></td></tr>
<br /> <tr><td colspan="2" align="right"> That Will Produce: <input type="hidden" name="currency" value="<%=ViewData["currency"] %>"/></td></tr>
</form>
</asp:Content>
I can't find what the error might be. it worked before. Please help. new to asp.net
A: Try removing the space in the function call:
<input type="text" name="calculate" value="<%=ViewData["calculate"]%>"
onblur="test_ifinteger(Currency.calculate,'Value');" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to set the click event for 2 images in jQuery I have two images with the title "Show Options" it looks like this:
<a class="io-content-pane-header-button-right" style="right: 41px;"><img class="io-content-pane-header-button" src="/document/c947bf0e-0144-4fc8-8a33-ce0d0d698384/latest" title="Show Options"></a>
I have the following jQuery to display another div called "recordViewPopover" when this image is clicked.
$('img[title*=\"Show\"]').live('click', function(e) {
console.log('RECORD VIEW OPTION SELECTED!');
e.stopImmediatePropagation();
var position = $(this).parent().offset();
$('#recordViewPopover').css('top', (position.top + $(this).height()) - 50);
console.log(position);
$('#recordViewPopover').fadeToggle('fast');
if ($('img[title*=\"Show\"]').hasClass('active')) {
$(this).removeClass('active');
} else {
$('img[title*=\"Show\"]').addClass('active');
}
});
The problem is, I want to be able to show another DIV called "objectViewPopover" when the 2nd image is clicked. Right now, when I click on the 2nd image, only "recordViewPopover" is shown.
How can I solve this?
UPDATE:
here is a simpler scenario, I am just going through each of the images:
$('img[title*=\"Show\"]').each(function(index, value){
if(index === 0){
console.log('object');
$(this).live('click', function(e) {
console.log('OBJECT VIEW OPTION SELECTED!');
});
}
else
console.log('record');
});
Why doesn't the click bind to the first match?
A: In the images add data attribute, something like this
First Image: <img class="io-content-pane-header-button" data-divid="recordViewPopover"...>
Second Image: <img class="io-content-pane-header-button" data-divid="objectViewPopover"...>
and change
$('#recordViewPopover')
to
$('#' + $(this).data("divid"))
and change
$('img[title*=\"Show\"]')
to
$(this)
in your code.
Demo
A: If the positioning of the images in the DOM is consistent you could do something like
if($(this).is(':last-child'))...
Or you could give the images a unique class:
<a class="io-content-pane-header-button-right recordView" style="right: 41px;"><img class="io-content-pane-header-button" src="/some/src" title="Show Options"></a>
<a class="io-content-pane-header-button-right objectView" style="right: 41px;"><img class="io-content-pane-header-button" src="/some/other/src" title="Show Options"></a>
and do
if($(this).hasClass('objectView'))...
A: img1=$('img[title*=\"Show\"]')[0];
img2=$('img[title*=\"Show\"]')[1];
$(img1).live('click', function(e) {
console.log('RECORD VIEW OPTION SELECTED!');
e.stopImmediatePropagation();
var position = $(this).parent().offset();
$('#recordViewPopover').css('top', (position.top + $(this).height()) - 50);
console.log(position);
$('#recordViewPopover').fadeToggle('fast');
if ($(img1).hasClass('active')) {
$(this).removeClass('active');
} else {
$(img1).addClass('active');
}
});
$(img2).live('click', function(e) {
console.log('OBJECT VIEW OPTION SELECTED!');
e.stopImmediatePropagation();
var position = $(this).parent().offset();
$('objectViewPopover').css('top', (position.top + $(this).height()) - 50);
console.log(position);
$('objectViewPopover').fadeToggle('fast');
if ($(img2).hasClass('active')) {
$(this).removeClass('active');
} else {
$(img2).addClass('active');
}
});
I'm not great with jQuery, but try that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax loaded div with autopostback I have a page that runs a jquery onclick event. The event loads an an external .aspx file into a div. The page that's being loaded has a drop down list with an autopostback attribute that passes the selected item to a label.
Everything works fine except that the .aspx file that's being loaded will only post back once. After that no more autopostback. Here's my code
----- external.aspx ------
<script>
protected void ddlPrices_SelectedIndexChanged(object sender, EventArgs e)
{
lblPrice.Text = ddlPrices.SelectedValue.ToString();
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlPrices" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlPrices_SelectedIndexChanged">
<asp:ListItem>Basic</asp:ListItem>
<asp:ListItem>Pro</asp:ListItem>
<asp:ListItem>Platinum</asp:ListItem>
<asp:ListItem>Baller!</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lblPrice" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
---- default.aspx ------
<script>
$(document).ready(function () {
$("li#empNav1").click(function () {
$("div.subItem").load('external.aspx');
});
});
</script>
<ul class="nav-left">
<li id="empNav1" class="selected"><a href="#">Employer Overview</a></li>
<li id="empNav2"><a href="#">Why We're Better</a><span></span></li>
</ul>
<div class="subItem"></div>
As stated the div loads just fine, but external.aspx will only update lblPrice once. Then it no longer auto updates. Any help would be greatly appreciated specifics please....
UPDATE: I've tried putting an update panel in default.aspx around the div that being loaded that also didn't cut it.
A: Well $.load() actually copies the HTML from the requested URL and "pastes" it into the target container. It's possible that the ViewState of the parent page is conflicting with that of the page you are loading so the PostBack call to the ddlPrices_SelectedIndexChanged method is not being found.
I would suggest putting your dropdown code into a UserControl and just keep your ScriptManager and UpdatePanel on the parent page.
So you could make something like CTRLPriceList.ascx which would just have:
<asp:DropDownList ID="ddlPrices" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlPrices_SelectedIndexChanged">
<asp:ListItem>Basic</asp:ListItem>
<asp:ListItem>Pro</asp:ListItem>
<asp:ListItem>Platinum</asp:ListItem>
<asp:ListItem>Baller!</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lblPrice" runat="server"></asp:Label>
And its Code Behind would be:
protected void ddlPrices_SelectedIndexChanged(object sender, EventArgs e)
{
lblPrice.Text = ddlPrices.SelectedValue.ToString();
}
To really explore what's happening, you should use an HTML debugger like Firebug or Chrome's built-in one which let you see what's being rendered in the DOM in real-time (eg. after the $.load() is processed). I have a feeling loading a full ASPX page into another will look very messy and is probably not a good idea even if you do get it to work.
Also check for Javascript errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: -[UINavigationController pushViewController:animated:] crashes with no error in console Update
I swapped out completely different code for pushViewController, and it is still crashing... seems like pushViewController is not the culprit. Here is what I added instead:
NSString *videoURL = [[NSString alloc] initWithFormat:@"http://www.vimeo.com/m/#/%@", videoID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:videoURL]];
It opens up the URL in Safari, and then crashes.. wtf?
PushViewController crashes with no error in the console, but I do get an EXC_BAD_ACCESS error in Xcode. The crash doesn't happen until after the view controller has been pushed... but the view its pushing is empty... no code to mess up.
My code is below:
MainViewController.m
PlayVimeo *playTest = [[PlayVimeo alloc] initWithNibName:@"PlayVimeo" bundle:nil];
//playTest.videoID = videoID;
[self.navigationController pushViewController:playTest animated:YES];
[playTest release];
PlayVimeo.m
#import "PlayVimeo.h"
#import "SVProgressHUD.h"
@implementation PlayVimeo
@synthesize videoID, wView;
-(void)viewDidLoad {
[super viewDidLoad];
//Show loading alert
[SVProgressHUD showInView:self.view status:@"Loading Video..."];
}
-(void)viewWillAppear:(BOOL)animated {
NSLog(@"Play View Loaded!");
[self vimeoVideo];
}
-(void)vimeoVideo {
NSLog(@"Video ID: %@", videoID);
NSString *html = [NSString stringWithFormat:@"<html>"
@"<head>"
@"<meta name = \"viewport\" content =\"initial-scale = 1.0, user-scalable = no, width = 460\"/></head>"
@"<frameset border=\"0\">"
@"<frame src=\"http://player.vimeo.com/video/%@?title=0&byline=0&portrait=1&autoplay=1\" width=\"460\" height=\"320\" frameborder=\"0\"></frame>"
@"</frameset>"
@"</html>",
videoID];
NSLog(@"HTML String: %@", html);
[wView loadHTMLString:html baseURL:[NSURL URLWithString:@""]];
//Dismiss loading alert
[SVProgressHUD dismissWithSuccess:@"Playing..."];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)dealloc {
[super dealloc];
}
Navigation Controller Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
[Appirater appLaunched];
return YES;
}
Console on crash:
sharedlibrary apply-load-rules all
Current language: auto; currently objective-c
(gdb)
A: It's likely that the culprit is
[playTest release];
Without seeing the rest of your code, I would still say that you likely need to release this after you're done with the video.
A: The code can not be fixed, it seems. With the UIWebView class reference, there is an example program TransWeb. Take this as base, it has a window and a navigation controller with a webview in it (in the xib). In MyViewController it reads a html-file and displays it. What you need to do is to change the main view to landscape and replace the html-code with yours. Avoid the frame-stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Populate Data Table in any wpf control The reason why I am having a hard time populating this table is because the table get's created dynamically:
MySql.Data.MySqlClient.MySqlDataReader selection = mySql.QuerySelect(textBox1.Text); //textBox1.Text containts the text of the query to be executed
DataTable table = new DataTable(); // create table to hold results
// depending on the query construct the needed columns
for (int i = 0; i < selection.FieldCount; i++)
{
table.Columns.Add("Column " + i);
}
// while there are rows insert them
while (selection.Read())
{
object[] o = new object[selection.FieldCount];
for(int j=0; j<selection.FieldCount; j++)
{
o[j] = selection[j].ToString();
}
table.Rows.Add(o);
}
ok so far after this point my table is constructed.
now my problem is how can I display that table so that user can see the results.
here are the things I have tried:
with a datagrid:
<DataGrid AutoGenerateColumns="False" Margin="73,264,17,12" Name="dataGrid1" ItemsSource="{Binding}" />
code behind:
dataGrid1.DataContext = table.DefaultView;
that does not display the results. the rows get populated and rows two but with no content...
with ListView
<ListView Height="72" Margin="78,253,17,0" Name="listView1" VerticalAlignment="Top" ItemsSource="{Binding}" />
code behind:
listView1.DataContext = table.DataSet;
listView1.DataContext = table.DefaultView;
note the correct number of rows are displayed but with the wrong content.
with a ListBox
similar technique....
A: You want columns in your grid, so you probably don't want AutoGenerateColumns="False".
To use a <ListView>, you'll need to make columns yourself in a <GridView>.
To use a <ListBox>, set DisplayTemplate to a <DataTemplate> containing UI for the listboxes.
A: If you are using a ListBox you need to set the ItemTemplate for the listbox. The ItemTemplate tells the control how to render each data item (a DataRowView from the table's default view).
A simple DataTemplate would be a text block with its text property bound to one of the column's in your table
<ListBox ItemsSource="{Binding Path=MyTable.DefaultView}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding SomeColumn}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does NSNumberFormatter not accept plus number if(![myNumberFormatter numberFromString:[tempColumn objectAtIndex:j]])
{
numericalColumns[j] = NO;
if(j == 8)
{
NSLog(@" non numerical value in column 8 i = %d object = %@ ", i , [tempColumn objectAtIndex:j]);
}
}
What I find:
0 good
-19.49883745 good
+38.85928608 bad
+46.94000154 bad
-0.36042119 good
+38.30408636 bad
-44.29029741 good
+26.91823821 bad
-79.06183133 good
-16.69693020 good
A: Try doing this:
[myNumberFormatter setPositivePrefix:@"+"];
before calling numberForString
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NSDecimalNumberPlaceHolder Leak I have an iPad app that I am testing in Instruments before beta testing. I have gotten rid of all memory leaks except one, and I can't find any information on it. I am baffled as to what to do, since my code never mentions the leaking object which is an instance of NSDecimalNumberPlaceHolder.
For sure I am using NSDecimalNumber. I create 2 decimals per user operation and each I time I run a cycle of the app (which performs some math operation on the two NSDecimalNumbers) I generate four instances of this NSDecimalPlaceHolder thing. Since I do not know how it gets created, I do not know how to release or dealloc it so as to not generate these 16 btye leaks over and over again.
Is it possible that these are not really leaks?
I have run the XCode Analyzer and it reports no issues.
What I'm doing is this:
I send a decimal number from my controller over to my model (analyzer_) which performs the operations and sends back the result.
[[self analyzer_] setOperand:[NSDecimalNumber decimalNumberWithString:anotherStringValue]];
The setOperand method looks like this:
-(void)setOperand:(NSDecimalNumber*)theOperand
{
NSLog(@"setOperand called");
operand_ = theOperand;
//[operand_ retain];
}
Note that if I don't retain operand_ "somewhere" I get a BAD_ACCESS crash. I currently retain and release it later where the operand and the previously provided operand (queuedOperand_) are operated upon. For example:
{
[self performQueuedOperation];
queuedOperation_ = operation;
queuedOperand_ = operand_;
}
return operand_;
[operand_ release];
where performQueuedOperation is:
-(void)performQueuedOperation
{
[operand_ retain];
if ([@"+" isEqualToString:queuedOperation_])
{
@try
{
operand_ = [queuedOperand_ decimalNumberByAdding:operand_];
}
@catch (NSException *NSDecimalNumberOverFlowException)
{
//viewController will send decimal point error message
}
<etc for the other operations>
}
Let me know if this is not clear. Thanks.
A: Try Heapshot in Instruments, see: When is a Leak not a Leak?
If there is still a pointer to the memory that is no longer used it is not a leak but it is lost memory. I use Heapshot often, it really works great. Also turn on recording reference counting in the Allocations tool and drill down. Here is a screenshot:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 32bit MAPI-based app running under 64bit Outlook? I have an app using 32bit MAPI. Now I want to run it under a target system with 64bit Outlook installed. I know the app cannot work with the 64bit MAPI system. So I wonder if there is a way to install a 32bit MAPI subsystem, or some hotfix on the target system so that the app can work?
A: You can try to install the standalone verson of MAPI from http://www.microsoft.com/downloads/details.aspx?FamilyID=e17e7f31-079a-43a9-bff2-0a110307611e&DisplayLang=en, but it will refuse to instal if OUtlook is already present. It does not check the Outlook bitness.
In other words, there is nothing you can do short of recompiling your app in 64 bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does JavaScript hook WinRT events? Suppose I'm writing a WinRT app with both JavaScript and C# code, and I want my JavaScript code to hook an event on my C# object.
I know that's supposed to be possible, but what would that JavaScript code look like? How are events (however the concept of a CLR event is represented in WinRT) exposed in the JavaScript projection?
If a concrete example would help, let's say my C# object has this event:
public event EventHandler Initialized;
How do I hook that event from JavaScript?
(I'm sure the answer is buried in one of the //build/ videos, but they're not exactly searchable.)
A: Once you have your C# class hooked up and accessible from JavaScript (see C# //Build/ talk for details), it should be as simple as this:
var foo = new CSharpClass();
foo.addEventListener("Initialized", onInitialized);
Then when C# fires the event, your onInitialized function will be called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Represent QTabWidget's tab text in Qt StyleSheet file? How can i set the font size of the tab text for a QTabWidget , with Qt's StyleSheet file ?
I just don't know "what" widget is that
QTabWidget { font: 10pt; }
wasn't helping.
A: It's QTabBar.
Have a look at the Customizing QTabWidget and QTabBar docs for info.
This is how to set its font size:
QTabBar::tab { font: 10pt }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Defining XML Parent Style of Gradient / Shape / Corners How can I define an easily reusable base shape (or gradient, or corners) in XML?
I have a dozen or so drawable gradients that will be the same other than the start and end colors. I was hoping to define the identical stuff somewhere else and have an XML file for each different gradient that only defined the start and end colors. Is that possible?
This is the base:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient xmlns:android="http://schemas.android.com/apk/res/android"
android:type="linear"
android:angle="270"
android:startColor="#e1ffffff"
android:endColor="#e100ff00">
<stroke android:width="1dp"
android:color="#ff000000" />
<corners android:radius="4dp" />
</gradient>
</shape>
Then I wanted to overwrite the startColor and endColor (and maybe the corners radius too or any other property) in each drawable's XML file.
I tried using both parent and styles, but neither of them use any of the properties. For example:
<style name="base_gradient">
<item name="android:angle">270</item>
<item name="android:type">linear</item>
<item name="android:startColor">#e1ffffff</item>
<item name="android:endColor">#e100ff00</item>
</style>
And then the drawable looks like:
<gradient style="@style/base_gradient" />
That didn't work. I tried similarly putting the above in its own XML file and then doing this for each drawable:
<gradient parent="@drawable/base_gradient" />
That did not work either.
Is there a way to do this?
A: Unfortunately I don't think it is possible. I tried to do the same thing and could not find a solution.
What I would suggest is putting all your values in resource xml files. In my case I chose to put my dimensions in dimens.xml, & integers.xml and colours in colours.xml (though they could have been combined into one file)
While I ended up with a shape drawable file for each colour, at least if I want to tweak colours or padding etc I only need to edit the colours.xml file integers.xml or dimens.xml file.
One of my shape drawable then looked like this:
<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius = "@dimen/radius_corner" />
<!-- end colour at top, start colour at bottom -->
<gradient
android:angle="@integer/gradient_angle_default"
android:endColor="@color/white"
android:startColor="@color/pink_pale"/>
<padding
android:left = "@dimen/my_padding"
android:right = "@dimen/my_padding"
android:bottom = "@dimen/my_padding"
android:top = "@dimen/my_padding" />
</shape>
Resource file link: http://developer.android.com/guide/topics/resources/more-resources.html
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to use Selenium to store values between tests Selenium has the ability to temporarily store data items and then later retrieve them in subsequent tests, e.g.
storeText | @id='ctl00_ContentPlaceHolder1_FormView1' | someValue
This works well within a single test and also between tests in the same Test Suite when a value needs to be carried forward across test boundaries. Unfortunately it doesn't work between Test Suites (which is a requirement for our application that includes a number of workflows referring to the same object). How can Selenium be used to store values across Test Suite boundaries?
A: It's possible to store values from a Selenium Test into the browser's Local Storage using javascript, e.g. if previously a value had been stored to someValue:
getEval | this.browserbot.getUserWindow().localStorage.setItem("someValue",storedVars['someValue'])
assertEval | this.browserbot.getUserWindow().localStorage.getItem("someValue") | ${someValue}
storeEval | this.browserbot.getUserWindow().localStorage.getItem("assetLabel") | someValue
In this case, this.browserbot.getUserWindow() returns the window of the application. This will store someValue into Local Storage from where it can subsequently be retrieved back into the Selenium stored variables.
A: You could also implement the persistence in the code that's running your Selenium tests. If you're using RC, this would be fairly trivial. (ie, just straight database queries to insert/update and then retrieve).
If you're using Selenese and don't have access to an API for persistence, you could also whip up a quick and dirty little webpage to store the data in a database and then read it back for subsequent test runs. Obviously this isn't ideal, but it should work if you can't access a persistence store directly from your tests..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Create multiple arrays based on frequency of coordinates in an array Using JavaScript, I'd like to split one big array of coordinates into smaller arrays based on coinciding points. I am not 100% sure how to write the following in code but it describes what I'm attempting to achieve:
*
*Iterate through the array
var A = [(1,2)(1,3)(2,3)(9,10)(9,11)(10,11)];
*Combine the pairs that contain any matching/identical coordinate points:
var B = (1,2)(1,3)(2,3)
var C = (9,10)(9,11)(10,11)
*Combine the matching/identical points and create new, smaller arrays from the combinations in point #2
var D = [1,2,3]
var E = [9,10,11]
Can I get help please?
A: Working answer: http://jsfiddle.net/y3h9L/
OK, so if I understand the requirement A is a one-dimensional array that is assumed to have an even number of elements in x,y pairs.
A = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11]
// output should be
[ [1,2,3], [9,10,11] ]
// but if you add an extra pair that links the two halves, say add 2,11
A2 = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11, 2,11]
// then all are related so output should be
[ [1,2,3,9,10,11] ]
I've made no effort to pretty-up or optimise the following code, but it works:
// single dimensional array of x,y pairs
var A = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11];
// create a working copy of A so that we can remove elements
// and still keep the original A intact.
var workingCopy = A.slice(0, A.length),
matchedPairs = [],
currentMatches,
finalCombinations = [],
x, y, i, j,
tempArray;
while (workingCopy.length > 0) {
currentMatches = [];
currentMatches.push([workingCopy.shift(),workingCopy.shift()]);
workingCopyLoop:
for (x=0,y=1; x < workingCopy.length;) {
for (i=0; i < currentMatches.length; i++){
if (workingCopy[x] === currentMatches[i][0]
|| workingCopy[y] === currentMatches[i][1]) {
currentMatches.push([workingCopy.shift(),workingCopy.shift()]);
// go back to the beginning of workingCopyLoop
x=0;
y=1;
continue workingCopyLoop;
}
}
x += 2;
y += 2;
}
matchedPairs.push(currentMatches);
}
for (i=0; i<matchedPairs.length; i++){
tempArray = [];
for (j=0; j<matchedPairs[i].length; j++) {
// I assume you have a new enough version of JS that you have Array.indexOf()
if (-1 === tempArray.indexOf(matchedPairs[i][j][0]))
tempArray.push(matchedPairs[i][j][0]);
if (-1 === tempArray.indexOf(matchedPairs[i][j][1]))
tempArray.push(matchedPairs[i][j][1]);
}
finalCombinations.push(tempArray);
}
for (i=0; i<finalCombinations.length; i++)
console.log(finalCombinations[i]);
// console.log shows that finalCombinations = [ [1,2,3], [9,10,11] ]
If it's not obvious how this works, follow it through with a debugger and/or pencil and paper.
A: I must say your question is rather unclear, but i think i got it.
In other words what you're saying is:
I have an array containing a bunch of numbers, logically they represent coordinates, it's not that the coordinates are subarrays inside the master array, is just looking them 2 by 2, but it's a linear array.
What you want is something that detects coordinates that are adjacent and generate a new array containing them.
After that you want to go thru the new arrays and generate new arrays containing unique-elements.
Well that's the question, now the answer. First, the second point depends on how far you want to go, i'm thinking it's anormal grid of x,y coordinates, but how adjacent you want to go? The following just applies to the inmediate adjacent, up to 8 points can be adjacent to a single point.
[1,1][2,1][3,1]
[1,2][2,2][3,2]
[1,3][2,3][3,3]
May that be a representation of the grid, if your master array has the [2,2] coordinate, you want to build an array that begins with that one and all adjacents you find, lets say like master array has [3,2], then you want to add it to the subarray of [2,2].
I'm really not writing the code i'm just gonna explain sorts of algorithm you could use.
To build the second point arrays, lets call them Adjacents Arrays (AA) you could:
First coordinate will always build the first AA
To find adjacents you will cycle thru the master array and perform an "Adjacency Check" to every coordinate which would be: second x == ( first x-1, x or x+1) AND second y == ( first y-1, y or y+1), if it passes then pop/push, if not... next.
In case you finish cycling thru the master array means that AA is complete, and you have to start a new AA with the next coordinate.
Repeat until master array is empty.
Then to create the unique-element-array is quite a simple cycle, i wrote a similar function that does something like that but it creates an array with the element and how many times it appears in the array (instances):
function uniqueCnt( ori) { // agroups and counts unique elements of an array, scrubs '' elements
var res = []; // resulting array, ori parameter stands for original array
for( let cntA = 0; cntA < ori.length; cntA++) {
for( cntB = 0; cntB < res.length; cntB += 2) if( ori[cntA] == res[cntB]) { res[cntB + 1]++; break; } // if it matches means it's another instance then increase that element count
if( cntB == res.length && ori[cntA] != '') res.push( ori[cntA], 1); // New element found then push it and start count
}
return res; // returns the agrouped array 0:element 1:instances...
}
If you don't want a count of instances, then you would need an even simpler function, you could try modify this one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Windows Phone 7 Stock Pivot Control Slow? I have a stock unedited version of Mango's Pivot Application and when I goto run it the control it really slow, is there a way to speed this up?
By slow I mean, when I am running my finger across the screen multiple times fast - as I would do on the iPhone it's really slow I take my finger off and it's still going through the windows.
I am also testing this on a real device (HTC HD7) on other apps such as IM+, Kik Messenger, etc... it works fine.
Code for XAML:
<phone:PhoneApplicationPage
x:Class="PivotApp1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--Pivot Control-->
<controls:Pivot Title="MY APPLICATION">
<!--Pivot item one-->
<controls:PivotItem Header="first">
<!--Double line list with text wrapping-->
<ListBox x:Name="FirstListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Height="78">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PivotItem>
<!--Pivot item two-->
<controls:PivotItem Header="second">
<!--Triple line list no text wrapping-->
<ListBox x:Name="SecondListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock Text="{Binding LineOne}" TextWrapping="NoWrap" Margin="12,0,0,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding LineThree}" TextWrapping="NoWrap" Margin="12,-6,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PivotItem>
</controls:Pivot>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
C# MainPage.xaml.cs Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace PivotApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
}
}
C# App.xaml.cs Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace PivotApp1
{
public partial class App : Application
{
private static MainViewModel viewModel = null;
/// <summary>
/// A static ViewModel used by the views to bind against.
/// </summary>
/// <returns>The MainViewModel object.</returns>
public static MainViewModel ViewModel
{
get
{
// Delay creation of the view model until necessary
if (viewModel == null)
viewModel = new MainViewModel();
return viewModel;
}
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Disable the application idle detection by setting the UserIdleDetectionMode property of the
// application's PhoneApplicationService object to Disabled.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
// Ensure that application state is restored appropriately
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
// Ensure that required application state is persisted here.
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
C# MainViewModel.cs
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace PivotApp1
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
}
/// <summary>
/// A collection for ItemViewModel objects.
/// </summary>
public ObservableCollection<ItemViewModel> Items { get; private set; }
private string _sampleProperty = "Sample Runtime Property Value";
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its value using a Binding
/// </summary>
/// <returns></returns>
public string SampleProperty
{
get
{
return _sampleProperty;
}
set
{
if (value != _sampleProperty)
{
_sampleProperty = value;
NotifyPropertyChanged("SampleProperty");
}
}
}
public bool IsDataLoaded
{
get;
private set;
}
/// <summary>
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public void LoadData()
{
// Sample data; replace with real data
this.Items.Add(new ItemViewModel() { LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime two", LineTwo = "Dictumst eleifend facilisi faucibus", LineThree = "Suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime three", LineTwo = "Habitant inceptos interdum lobortis", LineThree = "Habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu suscipit torquent" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime four", LineTwo = "Nascetur pharetra placerat pulvinar", LineThree = "Ultrices vehicula volutpat maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime five", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos interdum lobortis nascetur" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime six", LineTwo = "Dictumst eleifend facilisi faucibus", LineThree = "Pharetra placerat pulvinar sagittis senectus sociosqu suscipit torquent ultrices vehicula volutpat maecenas praesent" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime seven", LineTwo = "Habitant inceptos interdum lobortis", LineThree = "Accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime eight", LineTwo = "Nascetur pharetra placerat pulvinar", LineThree = "Pulvinar sagittis senectus sociosqu suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime nine", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime ten", LineTwo = "Dictumst eleifend facilisi faucibus", LineThree = "Suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime eleven", LineTwo = "Habitant inceptos interdum lobortis", LineThree = "Habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu suscipit torquent" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime twelve", LineTwo = "Nascetur pharetra placerat pulvinar", LineThree = "Ultrices vehicula volutpat maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime thirteen", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos interdum lobortis nascetur" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime fourteen", LineTwo = "Dictumst eleifend facilisi faucibus", LineThree = "Pharetra placerat pulvinar sagittis senectus sociosqu suscipit torquent ultrices vehicula volutpat maecenas praesent" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime fifteen", LineTwo = "Habitant inceptos interdum lobortis", LineThree = "Accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat" });
this.Items.Add(new ItemViewModel() { LineOne = "runtime sixteen", LineTwo = "Nascetur pharetra placerat pulvinar", LineThree = "Pulvinar sagittis senectus sociosqu suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum" });
this.IsDataLoaded = true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
C# ItemViewModel.cs
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace PivotApp1
{
public class ItemViewModel : INotifyPropertyChanged
{
private string _lineOne;
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public string LineOne
{
get
{
return _lineOne;
}
set
{
if (value != _lineOne)
{
_lineOne = value;
NotifyPropertyChanged("LineOne");
}
}
}
private string _lineTwo;
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public string LineTwo
{
get
{
return _lineTwo;
}
set
{
if (value != _lineTwo)
{
_lineTwo = value;
NotifyPropertyChanged("LineTwo");
}
}
}
private string _lineThree;
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public string LineThree
{
get
{
return _lineThree;
}
set
{
if (value != _lineThree)
{
_lineThree = value;
NotifyPropertyChanged("LineThree");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
I'm running the version of WP 7.1 which was released a few days ago on Microsoft's website.
I can't figure out how to get the application to speed up as it lags in comparison to iOS when bringing my finger across and it's not smooth, I take it off for a few seconds and it's still trying to catch up to where I was.
A: Your problem isn't related to your XAML. It's related to the C# code running in the background.
The problem is you're adding a heavy load to the UI thread, and as such the navigation between pivots, which is also running on the UI thread, lags heavily.
We'll need to see the related C# code (code-behind / viewmodel, etc.) to give more detailed advice.
As for your XAML, a good advice would be to use a Grid instead of StackPanel in your DataTemplate if possible, since it improves virtualization of the list elements.
A: I take it you are using the stock Pivot application template as part of the windows phone SDK 7.1 (Mango RTM release), in which case there should be no issues.
I've just fired up the template locally and ran it with no issues, so you might want to try a fresh copy if you can.
In the template there is no C# to speak of, it just loads up two lists for displaying to the two list boxes in the view, nothing special there. Granted it is not the most efficient way of doing this as the display will not render until BOTH the lists are populated, better to use some level of virtualisation and load the two lists separately for each view.
I take on board Claus's comment about using a grid over a stackpanel but in most cases unless you are using stack panels within stack panels there is no real issue and the benefit of how a stack panel handles layout can be a huge benefit.
let me know if you have done anything else to the default template and I'll expand where I can
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extracting with Regex in Yahoo pipes I am trying to use Yahoo pipes and remove everything from "Article" till the end of the page.
If I use Regex exp Article.+ I can extract everything till the end of line which is till "2011" . But I need to extract till the end of the page which is till "url.replace"
What am I doing wrong. I am using http://gskinner.com/RegExr/ which is awesome
Here is what the section of the page looks like
This Article was reviewed by Brown Last updated on: Oct 2, 2011
'; _url = _url.replace
Thanks
Hil
A: I think I got it:
query string is:
Article.+
this will extract till end of line
If one wants to extract till end of page use the S checkbox in Yahoo Pipes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django OneToOne Field Now I'm working one url mapping. Let's say I have three classes, company, user, and store, and my goal is that their urls will be in the same hierarchy. Since they are the same hierarchy in urls, I have to create a class url_mapping to ensure there is no duplicate name. Let's me give a more concrete problem I have.
Class Company(models.Model):
company_name = models.CharField(max_length=30)
url_mapping = models.OneToOneField(URL_mapping)
Class User(models.Model):
user_name = models.CharField(max_length=30)
url_mapping = models.OneToOneField(URL_mapping)
Class store(models.Model):
store_name = models.CharField(max_length=30)
url_mapping = models.OneToOneField(URL_mapping)
Class URL_mapping(models.Model):
url = models.CharField(max_length=30)
Now, when a visitor access to my site with certain url, I'll match the url in URL_mapping class, and then do the reverse lookup and see which type of url between company, user, and store it is.
Since User, Store, and Company have different view function, is it possible that we can quickly re-directly to the corresponding view function quickly using reverse lookup? Or should I add another field in URL_mapping saying that which url type it is?
The example is
http://www.example.com/levis -> will handle by brand_views
http://www.example.com/david -> will handle by user_views
http://www.example.com/mancy -> will handle by store_views
In database, we will have
url_mapping
id:1, name:levis
id:2, name:david
id:3, name:mancy
user
id:1, name:david, url_mapping:2
brand
id:1, name:levis, url_mapping:1
store
id:1, name: mancy, url_mapping:3
Where url_mapping is oneToOneField.
Don't know how to quickly look up from url_mapping class now.
Thank you.
A: I understand your question as "I have a URL, and I want to go to the corresponding Store, company or the User".
You can do that using
URL_mapping.objects.get(url).user
URL_mapping.objects.get(url).store
URL_mapping.objects.get(url).company
Clearly 2 of these will give you an error and you wouldn't know which it maps to.
Seems to me like, for what you are really looking for here, you should really use Generic Foreign Keys
So, then you will be able to do:
URL_mapping.objects.get(url)
which will have the corresponding User, Company or the Store model.
A: *
*I would use a SlugField in each model (Company, User, Store) as their identifier.
*theoretically, you do not need any URL mapping tables at all, in the view that handles the requests, extract the last part of the url, which is a slug identifying a Company, or a User, or a Store, and search Company, then User, and then Store models for the given slug. Stop when you find the object.
*to improve speed, you can create an auxiliary model like you did and use GenericForeignKey relation as Lakshman Prasad suggested. In this auxiliary model, again, I would use a SlugField for an identifier. And if you use that, you do not need slugs in your main models.
*I personally think this is a bad design. First, I doubt that these URLs are REST-ful. Second, for this to work, the slugs in your main models have to be unique across these three models, which can be ensured by only an external mechanism, you cannot use a UNIQUE constraint here. Your URL_mapping model is simply one such mechanism. It basically stores your slugs for the three models outside the models and, if you add the UNIQUE constraint to the SlugField in URL_mapping, makes sure the slugs are unique across your main models.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: multiprocessing and BaseHTTPServer I am trying to develop a HTTPServer using Python's BaseHTTPServer and multiprocessing.
I am multiprocessing in order to execute multiple Python scripts simultaneously.
Please note that the Script1 is just a simple script having a while loop printing time.asctime() for 5 seconds
The full code is here:
""" HTTP Server to run multiple python scripts via multiprocessing?
"""
from threading import Thread
from subprocess import PIPE, Popen
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import time
import multiprocessing
def simple_script(request_handler):
print 'simple_script started', time.asctime()
print 'request_handler', request_handler
s = Popen('C:/Python27/python C:/Script1.py 5', shell=True,
stdout=PIPE, stderr=PIPE)
out, err = s.communicate()
print out, err
request_handler.wfile.write(out)
request_handler.wfile.write(err)
request_handler.wfile.write('\n')
print 'simple_script ended', time.asctime()
class Handler(BaseHTTPRequestHandler):
def handle(self):
""" Overriding this method of SocketServer.BaseRequestHandler
in order to implement my own service
"""
print 'Reading', self.rfile.readline()
print 'Handling request started', time.asctime()
t = multiprocessing.Process(target=simple_script, args=(self,))
t.start()
time.sleep(2)
print 'Handling request ended', time.asctime()
def finish(self):
pass
class MyHTTPServer(HTTPServer):
def process_request(self, request, client_address):
"""Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
"""
self.finish_request(request, client_address)
#self.shutdown_request(request)
if __name__ == '__main__':
server = MyHTTPServer(('', 8080), Handler)
print 'Starting server, use <Ctrl-C> to stop'
server.serve_forever()
I am getting this error:
<code>
Starting server, use <Ctrl-C> to stop
Reading GET / HTTP/1.1
Handling request started Mon Oct 10 14:44:24 2011
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 65046)
Traceback (most recent call last):
File "C:\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Barik\UCS automation\eclipse_workspace\UCS\Python_HTTP\src\threading_with_http\problem_multiprocessing.py", line 46, in process_request
----------------------------------------
self.finish_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\lib\SocketServer.py", line 639, in __init__
self.handle()
File "C:\Barik\UCS automation\eclipse_workspace\UCS\Python_HTTP\src\threading_with_http\problem_multiprocessing.py", line 32, in handle
t.start()
File "C:\Python27\lib\multiprocessing\process.py", line 104, in start
self._popen = Popen(self)
File "C:\Python27\lib\multiprocessing\forking.py", line 244, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python27\lib\multiprocessing\forking.py", line 167, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 548, in save_tuple
save(element)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 725, in save_inst
save(stuff)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 548, in save_tuple
save(element)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 396, in save_reduce
save(cls)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 748, in save_global
(obj, module, name))
PicklingError: Can't pickle <type 'cStringIO.StringO'>: it's not found as cStringIO.StringO
ReadingTraceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python27\lib\multiprocessing\forking.py", line 347, in main
self = load(from_parent)
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python27\lib\pickle.py", line 880, in load_eof
raise EOFError
EOFError
Handling request started Mon Oct 10 14:44:41 2011
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 65047)
Traceback (most recent call last):
File "C:\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Barik\UCS automation\eclipse_workspace\UCS\Python_HTTP\src\threading_with_http\problem_multiprocessing.py", line 46, in process_request
self.finish_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\lib\SocketServer.py", line 639, in __init__
self.handle()
File "C:\Barik\UCS automation\eclipse_workspace\UCS\Python_HTTP\src\threading_with_http\problem_multiprocessing.py", line 32, in handle
t.start()
File "C:\Python27\lib\multiprocessing\process.py", line 104, in start
self._popen = Popen(self)
File "C:\Python27\lib\multiprocessing\forking.py", line 244, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python27\lib\multiprocessing\forking.py", line 167, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 548, in save_tuple
save(element)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 725, in save_inst
save(stuff)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 548, in save_tuple
save(element)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 396, in save_reduce
save(cls)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 748, in save_global
(obj, module, name))
PicklingError: Can't pickle <type 'cStringIO.StringO'>: it's not found as cStringIO.StringO
----------------------------------------
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python27\lib\multiprocessing\forking.py", line 347, in main
self = load(from_parent)
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python27\lib\pickle.py", line 880, in load_eof
raise EOFError
EOFError
Any help or alternative?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Printing out values of a dictionary line by line in Python I have the following code here:
tel = {2: [[0, 0, 1, 1], [0, 1, 0, 1]], 3: [[1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [1, 0, 1, 1]]}
for i in tel.values():
a = ''.join(map(str,i))
print a
The dictionary tel consists of keys which are the number of 1s in the keys value(here, they are lists of binary). The key's value/s can have more than one (in this case they are)
What this does is print the values that belong to each key line by line.
My goal:
I want to print the string version of each value.
In the example above, I want the output to be:
0011
0101
1011
1011
1000
1011
1011
How would I accomplish this?
A: >>> for x in tel.values():
... for y in x:
... print ''.join(str(z) for z in y)
...
0011
0101
1011
1011
1000
1011
1011
A: You could do:
for key in tel:
for num in tel[key]:
print ''.join(str(n) for n in num)
For your example this prints:
0011
0101
1011
1011
1000
1011
1011
A: Create a generator expression to traverse the data structure, and then just print its content.
val_gen = (''.join(map(str,v)) for vs in tel.values() for v in vs)
for v in val_gen: # Or sorted(val_gen) if order matters.
print v
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Appending Bytes puts spaces I'm trying to loop through an array of byte and copy the contents to a new list of bytes, and display them back. please see the code below.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myByte() As Byte = New Byte() {65, 66, 67}
Dim newByte() As Byte = New Byte() {}
Dim tempByteList As New List(Of Byte)
For i As Integer = 0 To 2
ReDim newByte(1)
Array.Copy(myByte, i, newByte, 0, 1)
tempByteList.AddRange(newByte)
Next
Dim str1 As String = System.Text.UnicodeEncoding.UTF8.GetString(tempByteList.ToArray())
End Sub
I want to see str1 as "ABC" but the out put i get is "A B C" (ie with spaces between letters)
Please note: I have to copy(chunks) within a loop and get the result at the end, this is just a sample to reproduce my real issue.
any help will be appreciated
A: The problem is in your ReDim statement. Microsoft's definition of ReDim states that the array bounds specified always go from 0 to the bound specified (in your case 1), so you are essentially ReDim-ing a 2 item array, which is why you're seeing "spaces" in between the A, B, and C elements. Change your ReDim statement to
ReDim newByte(0)
and all should be well as you will then be declaring the newByte array to go from 0 to 0 (a single item array), which is what you want.
A: You could also use the Array.CreateInstance method in VB.Net and not need to do the redim as createInstance makes it exactly the size that you specify. (Only other thing is do you need to build your TempByteList or do you know at the start of the loop the size you require, because you could just create your Final bytearray initially and Array.Copy them into the correct offset rather than append to a list then .ToArray()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim myByte() As Byte = New Byte() {65, 66, 67}
Dim newByte() As Byte = CType(Array.CreateInstance(GetType(Byte), 1), Byte())
Dim tempByteList As New List(Of Byte)
For i As Integer = 0 To 2
Array.Copy(myByte, i, newByte, 0, 1)
tempByteList.AddRange(newByte)
Next
Dim str1 As String = System.Text.UnicodeEncoding.UTF8.GetString(tempByteList.ToArray())
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does DataOutputStream.writeUTF() add additional 2 bytes at the beginning? When I was trying to parse xml using sax over sockets I came across a strange occurence.
Upon analysing I noticed that DataOutputStream adds 2 bytes in front of my data.
Message send by DataOutputStream:
0020 50 18 00 20 0f df 00 00 00 9d 3c 3f 78 6d 6c 20 P.. .... ..<?xml
0030 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 3f 3e 3c version= "1.0"?><
0040 63 6f 6d 70 61 6e 79 3e 3c 73 74 61 66 66 3e 3c company> <staff><
0050 66 69 72 73 74 6e 61 6d 65 3e 79 6f 6e 67 3c 2f firstnam e>yong</
0060 66 69 72 73 74 6e 61 6d 65 3e 3c 6c 61 73 74 6e firstnam e><lastn
0070 61 6d 65 3e 6d 6f 6f 6b 20 6b 69 6d 3c 2f 6c 61 ame>mook kim</la
0080 73 74 6e 61 6d 65 3e 3c 6e 69 63 6b 6e 61 6d 65 stname>< nickname
0090 3e c2 a7 3c 2f 6e 69 63 6b 6e 61 6d 65 3e 3c 73 >..</nic kname><s
00a0 61 6c 61 72 79 3e 31 30 30 30 30 30 3c 2f 73 61 alary>10 0000</sa
00b0 6c 61 72 79 3e 3c 2f 73 74 61 66 66 3e 3c 2f 63 lary></s taff></c
00c0 6f 6d 70 61 6e 79 3e ompany>
Message send using Transformer:
0020 50 18 00 20 b6 b1 00 00 3c 3f 78 6d 6c 20 76 65 P.. .... <?xml ve
0030 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f rsion="1 .0" enco
0040 64 69 6e 67 3d 22 75 74 66 2d 38 22 3f 3e 3c 63 ding="ut f-8"?><c
0050 6f 6d 70 61 6e 79 3e 3c 73 74 61 66 66 3e 3c 66 ompany>< staff><f
0060 69 72 73 74 6e 61 6d 65 3e 79 6f 6e 67 3c 2f 66 irstname >yong</f
0070 69 72 73 74 6e 61 6d 65 3e 3c 6c 61 73 74 6e 61 irstname ><lastna
0080 6d 65 3e 6d 6f 6f 6b 20 6b 69 6d 3c 2f 6c 61 73 me>mook kim</las
0090 74 6e 61 6d 65 3e 3c 6e 69 63 6b 6e 61 6d 65 3e tname><n ickname>
00a0 c2 a7 3c 2f 6e 69 63 6b 6e 61 6d 65 3e 3c 73 61 ..</nick name><sa
00b0 6c 61 72 79 3e 31 30 30 30 30 30 3c 2f 73 61 6c lary>100 000</sal
00c0 61 72 79 3e 3c 2f 73 74 61 66 66 3e 3c 2f 63 6f ary></st aff></co
00d0 6d 70 61 6e 79 3e mpany>
As one might notice DataOutputStream adds two bytes in front of the message. Thus the sax parser throws the exception "org.xml.sax.SAXParseException: Content is not allowed in prolog.". However when I skip over these 2 bytes the sax parser works just fine.
Additional I noticed that DataInputStream is unable to read the Transformer message.
My question is: Why does DataOutputStream adds these bytes and why doesn't the Transformer?
For those who are interested in replicating the problem here is some code:
Server using DataInputStream:
String data = "<?xml version=\"1.0\"?><company><staff><firstname>yong</firstname><lastname>mook kim</lastname><nickname>§</nickname><salary>100000</salary></staff></company>";
ServerSocket server = new ServerSocket(60000);
Socket socket = server.accept();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
os.writeUTF(data);
os.close();
socket.close();
Server using Transformer:
ServerSocket server = new ServerSocket(60000);
Socket socket = server.accept();
Document doc = createDocument();
printXML(doc, os);
os.close();
socket.close();
public synchronized static void printXML(Document document, OutputStream stream) throws TransformerException
{
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(stream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "no");
serializer.transform(domSource, streamResult);
}
private static Document createDocument() throws ParserConfigurationException
{
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element company = document.createElement("company");
Element staff = document.createElement("staff");
Element firstname = document.createElement("firstname");
Element lastname = document.createElement("lastname");
Element nickname = document.createElement("nickname");
Element salary = document.createElement("salary");
Text firstnameText = document.createTextNode("yong");
Text lastnameText = document.createTextNode("mook kim");
Text nicknameText = document.createTextNode("§");
Text salaryText = document.createTextNode("100000");
document.appendChild(company);
company.appendChild(staff);
staff.appendChild(firstname);
staff.appendChild(lastname);
staff.appendChild(nickname);
staff.appendChild(salary);
firstname.appendChild(firstnameText);
lastname.appendChild(lastnameText);
nickname.appendChild(nicknameText);
salary.appendChild(salaryText);
return document;
}
Client using SAX Parser:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new MyHandler();
Socket socket = new Socket("localhost", 60000);
InputSource is = new InputSource(new InputStreamReader(socket.getInputStream()));
is.setEncoding("UTF-8");
//socket.getInputStream().skip(2); // skip over the 2 bytes from the DataInputStream
saxParser.parse(is, handler);
Client using DataInputStream:
Socket socket = new Socket("localhost", 60000);
DataInputStream os = new DataInputStream(socket.getInputStream());
while(true) {
String data = os.readUTF();
System.out.println("Data: " + data);
}
A: The output of DataOutputStream.writeUTF() is a custom format, intended to be read by DataInputStream.readUTF().
The javadocs of the writeUTF method you are calling say:
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
A: Always use the same type of stream when reading and writing data. If you are feeding the stream directly into a sax parser, then you should not use a DataOutputStream.
Just use
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(os.getBytes("UTF-8"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: CSS webkit radial + iPad (Safari Mobile) not working I'm puzzled at the moment. I got this gradient
background-image: -webkit-radial-gradient(50% 65%, ellipse cover, #f2f2f4, #201935 55%);
It works on Safari, works on Safari changing the User Agent to
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5
which is the exact same webkit and browser as the one in the iPad
But when I load it on the ipad itself is not working, their forums say the webkit got support for it... can someone help me make it work?
or, can someone help me obtain the same result with webkit-gradient (I can't achieve something that adjust to resizing as well as the radial-gradient, nor the ellipsoid form), because apparently there is support for both?
A: You can specify the gradient using the older WebKit syntax, like this:
background-image: -webkit-gradient(radial, 50% 65%, 0, 50% 65%, 200, color-stop(0, #f2f2f4), color-stop(55%, #201935));
Unfortunately you can't specify percent for the point radius.
A: I believe that it's an issue with the version of webkit currently used in iOS.
Desktop Safari also had issues with radial gradients up to version 5.1.
Changing the user agent of desktop Safari to 5.0 as I understand it only changes the user agent string reported to browsers not the actual rendering engine used.
Sadly, running against the iOS simulator confirms that radial gradients aren't currently available on iOS and this is also a problem on tablets I've tested using running Android 3.2.
The good news is that we're imminently due OS updates for both iOS and Android so hopefully this problem will just go away.
If you really need radial gradients between now and iOS 5 and Android 4 you'll have to resort to either background images or SVG. :(
(If anyone knows a CSS trick to get round this then I'd really like to hear it too.)
A: Per https://developer.apple.com/library/archive/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Gradients/Gradient.html#//apple_ref/doc/uid/TP40008032-CH10-SW1
The -webkit-linear-gradient and webkit-radial-gradient properties require iOS 5.0 or later, or Safari 5.1 or later on the desktop. If you need to support earlier releases of iOS or Safari, see “Prior Syntax (-webkit-gradient).”
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Explaination of while(false !== ($f=readdir($d))){ I have just started practicing OOP in php through the book Concepts, Techniques and Codes. Unluckily I have never worked with directories and files in PHP and feeling difficulty to understand this condition here is the full code
function DirectoryItems($directory){
$d = "";
if(is_dir($directory)){
$d = opendir($directory) or die("Couldn't open directory.");
while(false !== ($f=readdir($d))){
if(is_file("$directory/$f")){
$this->filearray[] = $f;
}
}
closedir($d);
}else{
//error
die("Must pass in a directory.");
}
}
All I can understand is first we check the parameter that is it directory after that we open that directory and than we read the directory and putt all the files in the directory into an array but the condition is confusing me what the heck is !== I know only about !=
This book is written in PHP4 and 5 btw
A: The !== is like != but in addition to checking the equality it also checks the type.
This is an important distinction because sometimes something is "falsey" or "truthy" but not really a Boolean type with a value of false or true. The number 0 for example is generally treated as false.
The second slightly confusing part here is that the code is checking false !== (assignment) in the while loop. This is basically checking if the assignment was for a valid value.
So to out it all together code:
while(false !== ($f=readdir($d))
...translates to something like:
While $f is assigned an object from readdir($d) do ...
A: === means "equal value and equal type"
!== means "not equal value or not equal type"
Using ==, and empty string is equal to false. Using === though, they are not equal because the type is different.
!= and !== work the same way. The extra = sign means that type should be checked too, not just equivalent values.
A: The == will coerce values to the same type to compare them. If the readdir returns 0, then False==0 will probably evaluate to be true. However, False===0 will not be true.
There are a lot of people who know a lot more about comparison operators, type coercion, value types, etc. I'll delete this when they answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Escape regex in .NET? Essentially what i am doing is finding a piece of text in a textfile. The text is user specified so before i stick it into my regex expression i need to escape it all so . are \. and that something like {0, 3} is the string literal instead of part of the regex expression. Is there a function i can use to escape it? if not what chatacters should i stick \ in front of to ensure a valid regex statement?
A: Use Regex.Escape method -
Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,.,
#, and white space) by replacing them with their escape codes. This
instructs the regular expression engine to interpret these characters
literally rather than as metacharacters.
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Play audio and video with gnonlin I've been messing around with Gstreamer and Gnonlin lately, I've been concatenating segments of video files but when I dynamically connect the src pad on the composition, I can choose either the audio or video portion of the files, producing silent playback or videoless audio. How can I attach my composition to an audioconverter and a video sink at the same time. Do I have to make two compositions and add the files to both them?
A: Yes, gnonlin compositions work on one media type at a time. Audio and Video are treated separately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting up OGRE with Eclipse on Ubuntu I've just begun to wade in the waters of OGRE to introduce myself to game programming with C++ (I had done some Unity prior).
I'm having a bit of difficulty setting up the tutorial application as specified here:
http://ogre3d.org/tikiwiki/Setting+Up+An+Application+-+Eclipse+-+Linux
I have downloaded OGRE 1.7.3 as a debian/Ubuntu package (from the PPA/OGRE team) so it lives on my hard drive somewhere. I am presuming I don't need to do anything with CMake since it's already been compiled.
In the tutorial instructions it says under the heading Project Configuration it asks me to provide the path to OGRE but I cannot find it. I have looked in the most usual place I know /usr/bin (under /usr/bin/OGRE) and it's not there. Where is it located?
I would greatly appreciate if someone could enlighten the final steps to getting the tutorial application visible onscreen. Thanks.
A: Yes, I might be answering my own question and it might be lame, but I did enough research to figure out what the heck is going on.
http://www.ogre3d.org/forums/viewtopic.php?f=2&t=47695
showed me what I had to do with libraries and what to do with them when using the SDK while
Problem with installing Ogre sdk?
gave me the code needed for the ogre model to appear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Lazy Expiration in Memcached I read this - How does the lazy expiration mechanism in memcached operate?
So I have a question. Is it possible/recommended to make a program myself that periodically checks for all items in memcached, sending GET requests for each item so that expired items are removed?
The reason I want this is because I want to have a proper control of the used percentage in Memcached. If that percentage is near 100%, I will never be sure if I should add more memory, or if I should not worry because there are many expired items.
I use PHP, and unfortunately this doesn't return all the items in memcached (no clue why):
$allSlabs = $memcache->getExtendedStats('slabs');
foreach ($allSlabs as $server => $slabs) {
foreach ($slabs as $slabId => $slabMeta) {
$cdump = $memcache->getExtendedStats('cachedump', (int)$slabId);
foreach ($cdump as $keys => $arrVal) {
foreach ($arrVal as $key => $v) {
echo $key, "\n";
}
}
}
}
A: You should just use the eviction rate to see if you need to add more memory. The eviction stats will increase if memcached had to throw out an object in order to make room for storing the next one. (and you can look at the "reclaimed" stat to see the number of times we could reclaim the memory for an item to store a new item.
The code you suggest would jam down the server by dumping its content every now and then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: xslt sort output xml I'm trying to find a solution to the following problem.
I'm developing XSLT transformation (which is now about 40KB big) that is transforming quite complex XMLs into a quite simple structure which would like this:
<Records>
<Record key="XX">
</Record>
<Record key="XX1">
</Record>
<Record key="XX2">
</Record>
<Record key="XX3">
</Record>
</Records>
I would like to have this output XML sorted according to Records/Record/@key values.
The problem is that my XSLT produces this output unsorted and due to its complexity I am unable to sort it there.
Is it possible to apply xsl:sort on the output XML? I know that I can prepare another XSLT transform, but in my case that's not the solution, as I'm limited to only one XSLT.. Please, help!...
A:
Is it possible to apply xsl:sort on the output XML?
Yes, multipass processing is possible, and especially in XSLT 2.0 you don't even need to apply an xxx:node-set() extension on the result, because the infamous RTF type does no longer exist:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="vPass1">
<!--
Put/Invoke your cirrent code here
to generate the following
-->
<Records>
<Record key="XX3">
</Record>
<Record key="XX2">
</Record>
<Record key="XX4">
</Record>
<Record key="XX1">
</Record>
</Records>
</xsl:variable>
<xsl:apply-templates select="$vPass1/*"/>
</xsl:template>
<xsl:template match="Records">
<Records>
<xsl:perform-sort select="*">
<xsl:sort select="@key"/>
</xsl:perform-sort>
</Records>
</xsl:template>
</xsl:stylesheet>
When this transformation is performed on any XML document (not used/ignored), the wanted, correct, sorted result is produced:
<Records>
<Record key="XX1"/>
<Record key="XX2"/>
<Record key="XX3"/>
<Record key="XX4"/>
</Records>
In XSLT 1.0 it is almost the same with the additional conversion of the result from RTF type to a normal tree:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common"
exclude-result-prefixes="ext">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="vrtfPass1">
<!--
Put/Invoke your cirrent code here
to generate the following
-->
<Records>
<Record key="XX3">
</Record>
<Record key="XX2">
</Record>
<Record key="XX4">
</Record>
<Record key="XX1">
</Record>
</Records>
</xsl:variable>
<xsl:variable name="vPass1"
select="ext:node-set($vrtfPass1)"/>
<xsl:apply-templates select="$vPass1/*"/>
</xsl:template>
<xsl:template match="Records">
<Records>
<xsl:for-each select="*">
<xsl:sort select="@key"/>
<xsl:copy-of select="."/>
</xsl:for-each>
</Records>
</xsl:template>
</xsl:stylesheet>
A: 40Kb is a lot of code for one stylesheet. When things get to this kind of scale, it's usually best to split a transformation into a pipeline of smaller transformations. If you have such a pipeline architecture, then adding a sort step at the end is trivial. There are plenty of technologies for managing a pipeline of transformations (XProc, Orbeon, xmlsh, ant, Coccoon) depending on your requirements. The benefit of pipelining is that it keeps your code modular and reusable.
A: As an addendum to Dimitre's excellent solution above, if you're using an XSLT 1.0 processor (for example, .NET), the following can give you a pointer as to how to use node-set:
http://www.xml.com/pub/a/2003/07/16/nodeset.html#tab.namespaces
In my case, I was in .NET 1.1 (i.e. MSXML) and the solution looked something like:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:template match="/">
<xsl:variable name="vrtfPass1">
<Records xmlns="">
<xsl:apply-templates />
</Records >
</xsl:variable>
<xsl:variable name="vPass1" select="msxsl:node-set($vrtfPass1)"/>
<xsl:apply-templates select="$vPass1/*" mode="sorting"/>
</xsl:template>
<xsl:template match="Records" mode="sorting">
<Records>
<xsl:for-each select="Record">
<xsl:sort select="@key"/>
<xsl:copy-of select="."/>
</xsl:for-each>
</Records>
</xsl:template>
</xsl:stylesheet>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: java.lang.NoSuchMethodError for method on the build path I have a basic Android project created in Eclipse Indigo. I have a third-party library on my build path, and it is called is used when I instantiate a class from that library in my initial activity.
Although the app build just fine, I encounter the following error:
10-02 19:51:17.311: ERROR/AndroidRuntime(314): java.lang.NoSuchMethodError: org.apache.http.conn.scheme.Scheme.<init>
Earlier in logcat, I do observe the following error message:
10-02 19:50:48.670: DEBUG/dalvikvm(295): DexOpt: not verifying 'Lorg/apache/http/conn/scheme/Scheme;': multiple definitions
This class is included in the third-party JAR; is it used by Android somehow/somewhere to suggest a conflict or other source of "multiple definitions?"
Thanks!
A:
How does one reconcile the conflict - do I have crack open the third-party JAR and exclude the conflicting files?
My guess is that this would not help, though you can certainly try it. Somebody would appear to be trying to call a method on Scheme that perhaps exists in the JAR's own private copy of that class but is not in the Android SDK.
If the third-party JAR in question is Apache HttpClient, simply don't put that JAR in your build path, as HttpClient is already part of Android, and stick to methods that are in the SDK. If the third-party JAR is not Apache HttpClient, I suspect that once you remove their duplicate org.apache.http classes, that something else will break that depended on their own private version of those classes. If that is the case, you should probably take it up with the third-party developer directly, to work with them on Android support for their JAR. You might be able to use tools like jarjar to get past this, but I would not count on it.
A: You can try something like jarjar, it can break open the jars and rename the packages to a different path at build time. This avoids conflicts like the ones you're having. I'm just not sure it will work with Android.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error Uncaught out off memory when I use persisten object to save data on Blackberry? I use Persisten Object to save data but when I run my application on Simulator, have an error dialog
Uncaught out off memory
and run on real device, it take very long time to load and run.
What did I do wrong? Please help me
A: The BlackBerry® Persistent Store APIs are designed to provide a flexible and robust data storage interface. With the BlackBerry Persistent Store APIs, you can save entire Java® objects to memory without having to serialize the data first. When you start the application, you can retrieve the Java object from memory and process the information. No size limit exists on a persistent store; however, the limit for an individual object within the store is 64 KB.
The BlackBerry Persistent Store APIs do not provide a relational database model. You must create an effective object model and manage the relationships between objects, as necessary, using indices and hash tables.
sample example of storing persistent data
best practice for persistent storage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple instances of JQueryUI Autocomplete on same Pyramid page I have a working JQueryUI Autocomplete input widget working nicely with my Pyramid backend. The autocomplete posts its request.params['term'] to the same URL as the page its on, and Pyramid uses request_param='term' as a route predicate to send the term value to my database query view-callable.
The problem I have now though, is that I need to add more autocomplete widgets to the same page. However, I can't use the same route predicate term because both widgets post term and so Pyramid doesn't know where to send the post.
I know you can make custom predicates in Pyramid, but as far as I can see, there is nothing unique about the 2 autocomplete widgets with which I can make a custom predicate.
To give some context, below is the route/view definition. The definition is actually illegal because Pyramid rightly refused to identical predicates, but it serves to demonstrate my dilemma:
config.add_route('search_programs','/search/programs')
config.add_view(
'haystack.search.search_programs',
route_name='search_programs',
renderer='templates/search_programs.jinja2')
config.add_view(
'haystack.search.programtype_autocomplete',
route_name='search_programs',
request_param='term', renderer='json')
config.add_view(
'haystack.search.majorgenre_autocomplete',
route_name='search_programs',
request_param='term', renderer='json')
What would be awesome is if the autocomplete widget had an option to specify an arbitrary key for posting, instead of just 'term' every time. Any help would be awesome.
A: You need to set your autocomplete for each widget explicitly and indicate a specific url and/or a custom piece of data in the post.
This is a clip from the Remote JSONP datasource example on the JQueryUI documentation:
$( "#a-particular-auto-complete-widget" ).autocomplete({
source: function( request, response ) {
$.ajax({
/* specifiy your specific url here - could be a different
* route for each different source....
*/
url: "http://someurl.com/search/programs/majorgenre",
dataType: "jsonp",
data: { featureClass: "P",
style: "full",
maxRows: 12,
/* ...or add a custom piece of data to
* indicate how it should be handled by
* your Pyramid view(s).
*/
customParam: "majorgenre",
name_startsWith: request.term
}
/* see docs for rest of code... */
....
Then you can handle it in Pyramid however you want. I would probably just map one view to this route (and not bother with an ajax customParam):
config.add_route('search_programs','/search/programs/{autocomplete}')
And then in the view:
def autocomplete_handler_view(request):
autocomplete_type = request.matchdict.get('autocomplete', None)
if autocomplete == 'majorgenre':
return handle_majorgenre(request.params['term'])
elif autocomplete == 'programtype':
return handle_programtype(request.params['term'])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting XML feed and outputting Hello I would like to get the XML feed for my site:
http://buildworx-mc.com/forum/syndication.php?fid=4&limit=5
And display them in this format:
<ul>
<li><a href="linktothread"> Topic 1 </a> </li>
<li><a href="linktothread"> Topic 2 </a> </li>
<li><a href="linktothread"> Topic 3 </a> </li>
</ul>
I guess the best/easiest method to do this is using PHP, so how can I get the XML and display them in list items? It'll be displayed on http://example.com while the feed is http://example.com/forum
I tried the other answers from other questions asked, but nothing seems to work for me.
A: You may try SimpleXML once you are using PHP:
http://php.net/manual/en/book.simplexml.php
Just load that URL, so that it will convert the XML file into an object:
http://www.php.net/manual/en/function.simplexml-load-file.php
Then you may iterate the objects with a simple "foreach", to generate that HTML list you want.
For testing purposes, and to understand how the object is created, you may use "print_r()".
A: You may need to use the command "file_get_contents" to get a copy of the remote file in order to parse it using PHP. I'm surprised this step is necessary since you say you want to display items from your forum on your site so you might be able to set the 'feed' variable to the direct link, assuming everything is under the same domain. If not, this ought to work.
$feed = file_get_contents('http://buildworx-mc.com/forum/syndication.php?fid=4&limit=5');
$xml = simplexml_load_string($feed);
$items = $xml->channel->item;
foreach($items as $item) {
$title = $item->title;
$link = $item->link;
$pubDate = $item->pubDate;
$description = $item->description;
echo $title . "<br>";
// continue to format as an unordered list
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Advancing slideshow in jQuery I use this piece of code from tutorialzine:
$(window).load(function(){
// The window.load event guarantees that all the images are loaded before the auto-advance begins.
var timeOut = null;
$('#slider_navigator .arrow, #slider_navigator .dot').click(function(e,simulated){
// The simulated parameter is set by the trigger method.
if(!simulated){
// A real click occured. Cancel the auto advance animation.
clearTimeout(timeOut);
}
});
// A self executing named function expression:
(function autoAdvance(){
// Simulating a click on the next arrow.
timeOut = setTimeout(autoAdvance,2000);
$('.slider_rightlink').trigger('click',[true]);
})();
});
This works like expected except one thing, the first slide is immediately advanced when I load the page. After loading it rotates nicely with the rest of the slides.
How can I change this so that it shows the first slide 2 seconds like the rest?
A: $(window).load(function(){setTimeout(function(){
// The window.load event guarantees that all the images are loaded before the auto-advance begins.
var timeOut = null;
$('#slider_navigator .arrow, #slider_navigator .dot').click(function(e,simulated){
// The simulated parameter is set by the trigger method.
if(!simulated){
// A real click occured. Cancel the auto advance animation.
clearTimeout(timeOut);
}
});
// A self executing named function expression:
(function autoAdvance(){
// Simulating a click on the next arrow.
timeOut = setTimeout(autoAdvance,2000);
$('.slider_rightlink').trigger('click',[true]);
})();
},2000);}
);
There's probably a setTimeout jQuery function, but this will work.
A: do not make it self executing function:
function autoAdvance(){
// Simulating a click on the next arrow.
timeOut = setTimeout(autoAdvance,2000);
$('.slider_rightlink').trigger('click',[true]);
};
timeOut = setTimeout(autoAdvance,2000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3 template not loading in jQuery UI Tabs I have a Profile in my Rails 3 app. When the Profile is viewed, the Profile's about information shows in a div container by default. What I want to do is replace the "about" information in the div with messages from the User when a "messages" link is clicked. (The messages should load according to the profile_messages template.) To do this, I turned to jQuery UI Tabs.
So the "about" information exists in Tab-1. The "Messages" is in a template called profile_messages that I've tried loading from both the ProfilesController and the MessagesController.
I've gotten a lot of help here on SO to get to where I'm at. However, for some reason I can't get the actual messages to show up. What happens when I click "messages is I see the error message in my jQuery. If I inspect the element, I see this:
Failed to load resource: the server responded with a status of 404 (Not Found) `profile_messages`
Here is my code. If anyone can help me figure out what's going on I'd appreciate it greatly.
ProfilesShow show.html.erb:
<div id="tabs">
<ul id="infoContainer">
<li><a href="#tabs-1">About</a></li>
<li><%= link_to "Messages", "/profiles/profile_messages", :remote => true %></li>
</ul>
<div id="tabs-1">
</div><!-- end profile-about -->
profile_messages.html.erb:
<div id="tabs-2">
<% for 'message' in @user.messages %>
<div class="message-1">
</div>
</div><!-- end messages -->
<% end %>
ProfilesController:
def show
@profile = Profile.find(params[:id])
@user = User.find(@profile.user_id)
end
Routes.rb:
resources :messages do
resources :responses
end
resource :messages do
collection do
get :profile_messages
end
end
profile_messages.js.erb:
$( "#tabs" ).html( "<%= escape_javascript( render(@profile.messages) ) %>" );
From rake routes:
message GET /messages/:id(.:format) {:action=>"show", :controller=>"messages"}
profile GET /profiles/:id(.:format) {:action=>"show", :controller=>"profiles"}
profile_messages_messages GET /messages/profile_messages(.:format {:action=>"profile_messages", :controller=>"messages"}
jQuery UI Tabs:
$(function() {
$( "#tabs" ).tabs({
spinner: '<img src="">' },{
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"There was an error loading this tab. Please try again." );
}
}
});
});
As I said, I'm really close so if anyone can help me figure out what I'm doing wrong I'd appreciate it.
UPDATE: If I switch the route from profiles/profile_messages to messages/profile_messages here is the HTML output of the jQuery UI Tabs:
<div id="tabs">
<ul id="infoContainer">
<li><a href="#tabs-1">About</a></li>
<li><a href="messages/profile_messages" data-remote="true">Messages</a></li>
</ul>
<div id="tabs-1">
Here is what I see in Firebug:
<div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
<ul id="infoContainer" class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">About</a></li>
<li class="ui-state-default ui-corner-top"><a href="#ui-tabs-1" data-remote="true">Messages</a></li>
</ul>
<div id="tabs-1" class="ui-tabs-panel ui-widget-content ui-corner-bottom">
</div>
</div>
The fact that Firebug shows the second link as #ui-tabs-1 seems odd to me.
A: The routes output says it all: profile_messages_messages, but you also need to append _path--if you were using the generated path variable and not using a string path.
A: Does this route exist?
/profiles/profile_messages
This is what you are calling from your link_to. From your routes output, it seems this should be:
/messages/profile_messages
A: Thanks to the combined efforts of folks here on SO I was able to get this to work. Check out these questions for more code:
Exclude application layout in Rails 3 div
Rails 3 jQuery UI Tabs issue loading with Ajax
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Global Java Servlet Filter, is it possible? I'm writing a project for academic purposes which among other irrelevant stuff, includes writing a filter which monitors servlet/jsp response times.
The thing is that the filter should work on every deployed web application in the server and not only over a specific one, I just couldn't find any information regarding applying "global" filters.
Is it even possible?
NOTE:
It's important to mention that i'm using Apache Tomcat 7 as the server of choice.
Thanks!
Mikey
A: You could provide the filter in Tomcat's common classpath and edit Tomcat's own /conf/web.xml to add the filter, but this does not run on non-existing webapp contexts (i.e. it does not cover all possible requests) and it is overrideable in all deployed webapps. The more robust solution depends on the servlet container used. In case of Tomcat, you need the Valve component.
Kickoff example:
import org.apache.catalina.valves.ValveBase;
public class MyValve extends ValveBase {
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
// ...
getNext().invoke(request, response);
}
}
register it as follows in server.xml:
<Valve className="com.example.MyValve" />
A: Filters are configured per-web app, but Tomcat itself may have a mechanism for timing request/response processing times.
A: You can config the url-pattern of your filter to process any request/response that you want. Please check http://www.caucho.com/resin-3.0/config/webapp.xtp#filter-mapping
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Add Change Item order ribbon in Sharepoint 2010 I want to add Change item order ribbon into ribbon panel. I have created feature and activated, however i still cant see the item order ribbon. Can anyone help me with this?
below is my code
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!--Change Item order Ribbon-->
<CustomAction
Id="SPChangeItemOrder"
Location="CommandUI.Ribbon.ListItem"
RegistrationId="101"
RegistrationType="List"
Title="List View Ribbon Customization"
>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.ListItem.Actions.Controls._children">
<!--Get Details from CMDUI.XML-->
<Button
Id="Ribbon.ListItem.Actions.ChangeItemOrder"
Alt="Change the order of the items in this list."
Sequence="20"
Command="ChangeLinkOrder"
LabelText="$Resources:core,cui_ButChangeItemOrder;"
ToolTipTitle="$Resources:core,cui_ButChangeItemOrder;"
ToolTipDescription="$Resources:core,cui_STT_ButChangeItemOrder;"
TemplateAlias="o2"
Image16by16="/_layouts/$Resources:core,Language;/images/formatmap16x16.png" Image16by16Top="-192" Image16by16Left="-144"
Image32by32="/_layouts/$Resources:core,Language;/images/formatmap32x32.png" Image32by32Top="-192" Image32by32Left="-288"
/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler Command="ChangeLinkOrder" CommandAction="javascript:alert('Please check Change Item Order');"></CommandUIHandler>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
A: Try something like this where RegistrationID is the Type value of a list definition. You don't need the CommandUIHandler if you want to use SharePoint's OOB Change Item Order command.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!--Change Item order Ribbon-->
<CustomAction
Id="XYZ.Webpart.Links.XYZLinksListDefinition.RibbonSortOrderButton"
Location="CommandUI.Ribbon"
RegistrationId="30099"
RegistrationType="List"
Title="List View Ribbon Customization" >
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.ListItem.Actions.Controls._children">
<Button
Id="Ribbon.ListItem.Actions.RibbonSortOrderButton"
Sequence="25"
Command="ChangeLinkOrder"
Image16by16="/_layouts/$Resources:core,Language;/images/formatmap16x16.png" Image16by16Top="-192" Image16by16Left="-144"
Image32by32="/_layouts/$Resources:core,Language;/images/formatmap32x32.png" Image32by32Top="-192" Image32by32Left="-288"
LabelText="$Resources:core,cui_ButChangeItemOrder;"
ToolTipTitle="$Resources:core,cui_ButChangeItemOrder;"
ToolTipDescription="$Resources:core,cui_STT_ButChangeItemOrder;"
TemplateAlias="o1" />
</CommandUIDefinition>
</CommandUIDefinitions>
</CommandUIExtension>
</CustomAction>
</Elements>
A: Invalid value for attribute location in customaction element, choose right location value from here http://msdn.microsoft.com/en-us/library/bb802730.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert Multiline into list I have extracted a set of data from HTML page and copied to a variable. The variable looks like
names='''
Apple
Ball
Cat'''
Now I like to join each line into a list so that I can access any line I want. Is there any way to do that in Python
A: Using splitlines() to split by newline character and strip() to remove unnecessary white spaces.
>>> names='''
... Apple
... Ball
... Cat'''
>>> names
'\n Apple\n Ball\n Cat'
>>> names_list = [y for y in (x.strip() for x in names.splitlines()) if y]
>>> # if x.strip() is used to remove empty lines
>>> names_list
['Apple', 'Ball', 'Cat']
A: names.splitlines() should give you just that.
A: names.split('\n') should give you a list split by '\n'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Including in c++ program in Ubuntu OS I have a small program that uses "trying to use" #include <queue>. I use Ubuntu OS but it says:
fatal error: queue: No such file or directory
Any ideas why, or what I need to do to make it work?
#include <queue>
using namespace std;
int main()
{
queue<int> Q;
Q.push( 1 );
Q.push( 2 );
Q.push( 3 );
cout << Q.front();
Q.pop();
cout << Q.front();
Q.pop();
cout << Q.front();
Q.pop();
return 0;
}
A: You are compiling your C++ program (which you saved with a .c extension) with a C compiler.
This won't work, since you're using the C++ STL (and namespace std).
Compile using g++ instead:
g++ queuetest.cpp -o queuetest
See the docs for compiling C++. Consider changing your extension to .cpp as well.
You'll also want to #include <iostream> for cout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having problems linking with v8 on windows I'm using Visual Studio 2010 on a 64-bit Windows 7 machine. I've pulled v8 source from SVN, built it with no problems (wich arch=x64), but I still can't compile my project that tries to use v8.
Here is a sample code that produces that same error :
#include <v8.h>
int main(int argc, char *argv[])
{
v8::Handle<v8::Context> context = v8::Context::New();
return 0;
}
The linker error I get is :
v8test.obj : error LNK2019: unresolved external symbol "public: static class v8::Persistent<class v8::Context> __cdecl v8::Context::New(class v8::ExtensionConfiguration *,class v8::Handle<class v8::ObjectTemplate>,class v8::Handle<class v8::Value>)" (?New@Context@v8@@SA?AV?$Persistent@VContext@v8@@@2@PAVExtensionConfiguration@2@V?$Handle@VObjectTemplate@v8@@@2@V?$Handle@VValue@v8@@@2@@Z) referenced in function _main
I built v8 as a static lib, tried both debug and release build, I get the same error.
A: In addition to v8_base.lib you need to also include v8_snapshot.lib, ws2_32.lib, and winmm.lib.
The sample on the V8 Getting Started Page can be compiled in a Console Application with following dependencies listed under Project Properties->Configuration Properties->Linker->Input->Additional Dependencies:
v8_base.lib;v8_snapshot.lib;ws2_32.lib;winmm.lib;(AdditionalDependencies)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AFNetworking Post Request with json feedback I am using AFNetworking and creating a post request for which I require json feedback. The code below works however I have two main questions; where do I release the ActivityIndicator Manager? The second question is this code correct, being new I get confused with blocks so I really want to know if I am doing it right thing for optimum performance, even though it works.
NSURL *url = [NSURL URLWithString:@"mysite/user/signup"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
AFNetworkActivityIndicatorManager * newactivity = [[AFNetworkActivityIndicatorManager alloc] init];
newactivity.enabled = YES;
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
usernamestring, @"login[username]",
emailstring, @"login[email]",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"mysite/user/signup"parameters:params];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id json) {
NSString *status = [json valueForKey:@"status"];
if ([status isEqualToString:@"success"]) {
[username resignFirstResponder];
[email resignFirstResponder];
[self.navigationController dismissModalViewControllerAnimated:NO];
}
else {
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Login Unsuccessful"
message:@"Please try again"
delegate:NULL
cancelButtonTitle:@"OK"
otherButtonTitles:NULL];
[alert show];
[alert release];
}
}
failure:^(NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", error);
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Login Unsuccessful"
message:@"There was a problem connecting to the network!"
delegate:NULL
cancelButtonTitle:@"OK"
otherButtonTitles:NULL];
[alert show];
[alert release];
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
NSLog(@"check");
}
Thank you very much for your help in advance :)
A: I know this question is a bit old, but I still wanted to contribute.
As steveOhh said, you should use [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES] to turn on the activity network indicator. It is a singleton, and hence it doesn't require you to manually alloc-init and release. As to the other question, I noticed you are missing some parameters in your block calls, also, you can do this, which is much cleaner code:
NSURL *url = [NSURL URLWithString:@"mysite/user/signup"];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:[NSURLRequest requestWithURL:url] success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// your success code here
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// your failure code here
}];
[operation start]; // start your operation directly, unless you really need to use a queue
A: Why not use this instead?
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
Hence there's no need to alloc and init
Can't say much on the other codes, just started out learning objective-C and AFNetworking.. :)
Regards,
Steve0hh
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: shouldStartLoadwithRequest not getting called in subclass I have a view controlled app. On my xib I have no webviews but I do have buttons that bring up classes that have webviews. So hit button one and a uiwebview pops up so on and so forth.
Now in one of my classes I pull up a remote webpage that has a link on it. I want to over-ride that button link with shouldStartLoadwithrequest. How ever this never seems to get called.
Right now my class is called Tenth.m and I have this code in my view controller
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@" Test spot 1");
NSString* scheme = [[request URL] scheme];
if ([@"didTap" isEqual:scheme]) {
// Call your method
NSLog(@" Test spot 2");
[self didTapButton1];
return NO;
} else {
NSLog(@" Test spot 3");
return YES;
}}
But I get nothing (none of my NSLogs). I have tried putting this into my Tenth.m class and still nothing. I have looked at other examples and even downloaded one but it only uses the viewcontroller and delegates classes. No third class.
I'm lost as to why its not getting called.
Here is my third class
#import "Tenth.h"
@implementation Tenth
- (void)awakeFromNib
{
[category10 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mywebsite.com/api/didtap.php"]]];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
@end
remote page code
<a href="didTap://button1">hello</a>
Tenth.h file
#import <UIKit/UIKit.h>
@interface Tenth : UIViewController <UIWebViewDelegate> {
IBOutlet UIWebView *category10;
}
-(IBAction)back;
@end
A: My first guess is that the Web view does not have its delegate set. In order for it to call
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
The class containing this method needs to be set as the webview's delegate. So somewhere in the code there should be a line similar to webView.delegate = <variable>, where the variable is the instance of the class which has implemented the shouldStartLoadWithRequest: method.
This is often "self" when the webView is a subview of a viewController's view. But the way you have described your application, I am not sure if it will be self or not, but it sounds like it will not be self, but the name of the instance of a different class.
A: Maybe try this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Remember to set web view delegate to self.
category10.delegate = self;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP class method called by jQuery I'm fairly new to jQuery and OOP in PHP,
but what I have is a PHP Object that has an array
$array[0] = "a"
$array[1] = "b"
$array[2] = "c"
$array[3] = "d"
and a select box in my HTML
<select class="box">
<option value="1">First Letter</option>
<option value="2">Second Letter</option>
<option value="3">Third Letter</option>
<option value="4">Fourth Letter</option>
</select>
<div></div>
How do I dynamically change whatever is in the div tags as someone changes the value of the select box using jQuery?
Is there a way to do something like
$('.box').change(){ var value = $object->array[index-1]}?
Assuming I had already have the value for index.
EDIT
I know I'll have to use Ajax, but I'm not sure how to call a method in an instance of an object already made.
A: You can't access PHP through javascript. There are several possible solutions:
*
*Load all of the possible data combinations at once onto the page stored somewhere in the DOM. As the user cycles through the options, change them appropriately.
*Load only the initial elements onto the page without javascript, then use Ajax to load all other possible combinations.
*Load each combination with ajax on the fly.
You can either have javascript make an Ajax request to the same page and filter the request, or you can create a proxy that will serve only the requests you need when hit with ajax.
A: Remember that you are trying to combine PHP with Javascript.
Your code will primarily be written in javascript, but you'll
only inject bits of PHP code into the javascript code.
As in this instance, use the standard jquery onchange event method 'change()'
for the selectbox, set the javascript variable value to $object->array[0]
from PHP.
$('select').change(function() {
var value = <?php echo $object->array[$index] ?>
$('div').html(value)
});
A: You can use the php function json_encode to turn your php data into a javascript object. e.g
<script type="text/javascript">
var mydata = <?= json_encode($myarray) ?>;
console.log(mydata);
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: E4X Parsing with HTTP Request Response XML I put together a simple XML schema for a directory (address-book) markup system. The basic structure is as follows:
<?xml version="1.0" encoding="UTF-8">
<directory
xmlns="http://example.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example.com directory.xsd">
<title>An Example Directory Document</title>
<creator>Lorem Ipsum Dolor</creator>
<date>September 29, 2011</date>
<person>
<firstName>Lorem</firstName>
<middleName>Ipsum</middleName>
<lastName>Dolor</lastName>
<email type="personal">[email protected]</email>
<email type="other">[email protected]</email>
<phone type="mobile">(123) 456-7890</phone>
</person>
</directory>
This is the JavaScript (and E4X; this is actually only being used if a PHP $_GET[] or $_REQUEST[] variable is true, due to the fact that only Firefox has decent E4X support):
<script type="text/javascript;e4x=1">
var directory;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://example.com/directoryExample.xml', true);
xmlhttp.onreadystatechange = (function() {
if(xmlhttp.readyState === 4) {
if(xmlhttp.status === 200) {
directory = xmlhttp.responseXML;
HandleDirectoryData();
}
}
});
function HandleDirectoryData() {
var container = document.getElementById('output');
var directoryTitle = directory.title;
var directoryCreator = directory.creator;
var directoryDate = directory.date;
var title = document.createElement('p');
var creator = document.createElement('p');
var titleLabel = document.createElement('label');
var creatorLabel = document.createElement('label');
title.id = "xmlDirectoryTitle";
creator.id = "creator";
titleLabel.for = title.id;
creatorLabel.for = creator.id;
titleLabel.textContent = "Title:";
creatorLabel.textContent = "Creator:";
titleLabel.appendChild(title);
creatorLabel.appendChild(creator);
container.appendChild(titleLabel);
container.appendChild(creatorLabel);
for each(var person in XMLData) {
console.log("Displaying of the person data happens here...");
}
}
I believe the XMLHttpRequest is fine, and that it is simply the parsing that has something wrong with it.
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP: Send $_POST data to my Class? I'm trying to send my $_POST data to a class of mine for processing... but it doesn't seem to matter how I send it, PHP is telling me:
Trying to get property of non-object
Class method:
public function test_me_out($postdata) {
if(isset($postdata->price)) {
return "the price was: " . $postdata->price . " …and this was added.";
} else {
return "it's apparently not set...";
}
}
A: $_POST is not an object. You should access its information using it as an array like $_POST['my_data'].
A: You can still do
$postData = new ArrayObject($_POST,ArrayObject::ARRAY_AS_PROPS);
Then $postData->price will work as expected to be.
A: How are you calling test_me_out? Like this?
test_me_out($_POST)
$_POST is an array, not an object. Therefore you can access the variables in your function like so:
$postdata['price']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are some good methods for hashing passwords in an Android app? I am creating an app that requires the user to register with a remote server, but I want to hash their password before sending it off to be stored in my database.
I tried using the jBCrypt library, but it created a long hang time while hashing. Are there any other alternatives? What would be the best (and safest) way to hash the passwords without creating a noticeable hang?
A: Your approach seems to be wrong. Unless you have some special requirements, the usual way to do this is the following (not Android-specific, for any web application):
*
*When the users register, take their password, hash it (using a random salt is also recommended), and save it in the DB. That is done so you don't save the actual password in your DB.
*When the user needs to login, you send the actual password to your webapp (use SSL to avoid sending it in the clear), not the hash. On the server, you apply the same hashing algorithm as in step 1, and compare the result to what is in your DB. If they are the same, the user has provided the correct password.
In short, you should do your hashing on the server, not on the Android device.
A: Avoid saving 3rd party passwords at all cost. Saving them is considered a form of phishing. Try to save an authentication token instead of a raw password that you can get using a method like OAuth.
If you do need to send a password to a database on a webserver, just use HTTPS. This will ensure safe encryption over the wire. Then you can encrypt the password as necessary in the database. This method also ensures that your encryption mechanism is not on the device itself which can be more easily compromised.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MySQL & PHP leaderboard query I have a set of players and I want to select the top 5 scores from the tables and print out the username and scores in descending order, what's the SQL statement for that?
and How to output the result?
A: SELECT * FROM yourtable ORDER BY score DESC LIMIT 5
Explanations:
SELECT * FROM yourtable: we select yourtable.
ORDER BY score DESC: We order the results based on the column score and in descending order.
LIMIT 5: we limit the number of results by 5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cross-Compile of Boost for GCC ARM (Linux) from Windows building .o but not .a I'm cross-compiling Boost for a Linux distro on an ARM board. I'm using windows with Boost 1.47.
My project-config.jam contains the following:
import option ;
using gcc : arm : "C:/Program Files (x86)/CodeSourcery/Sourcery
G++ Lite/bin/arm-none-linux-gnueabi-g++" ;
option.set keep-going : false ;
And I'm building with the command:
bjam toolset=gcc-arm target-os=linux
Whilst .o objects are building just fine, .a builds are failing usually with something like:
"C:\Program Files (x86)\CodeSourcery\Sourcery G++ Lite\bin"
"bin.v2\libs\wav
e\build\gcc-arm\release\link-static\target-os-linux\threading-multi\libboost_wav
e-gcc-mt-1_47.a"
...failed gcc.archive
bin.v2\libs\wave\build\gcc-arm\release\link-static\target-
os-linux\threading-multi\libboost_wave-gcc-mt-1_47.a... ...skipped
libboost_wave-gcc-mt-1_47.a for lack of libboost_wav
e-gcc-mt-1_47.a... ...failed updating 23 targets... ...skipped 28
targets... ...updated 641 targets...
I am also getting quote a few of the following error messages:
'"C:\Program Files (x86)\CodeSourcery\Sourcery G++ Lite\bin"' is not
recognized as an internal or external command, operable program or
batch file.
Any ideas guys?
Many thanks
A: I just have:
import option ;
using gcc : arm : arm-none-linux-gnueabi-g++.exe ;
option.set keep-going : false ;
And the compiler in the path. Works for me. Perhaps '\' vs '/' in your case.
http://www.boost.org/boost-build2/doc/html/bbv2/tasks/crosscompile.html
EDIT: To add the
C:\Program Files (x86)\CodeSourcery\Sourcery G++ Lite\bin
directory to your path follow the instructions here:
http://geekswithblogs.net/renso/archive/2009/10/21/how-to-set-the-windows-path-in-windows-7.aspx
A: Faced the same problem, it was caused by the spaces within the path which aren't properly handled by boost.build. Either switch to boost 1.48.0, or move CS into a path without spaces.
A: The error for C:\Program Files (x86)\CodeSourcery\Sourcery G++ Lite\bin sounds like a variable for the name of the compiler is missing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I load a external QML file in Qt Quick? Ok like if I'm trying to make something like a menu for a simple game. How can I make it so that when the start button is clicked it loads a different QML file?
A: You can use Qt.createComponent() or Loader. For example:
import QtQuick 1.0
Item {
MyButton {
onClicked: loader.source = "MyGameFile.qml"
}
Loader {
id: loader
anchors.fill: parent
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Genexus: Sort a Top10 list (grid) using a variable I have the following issue: I'm generating a Top10 list of items, based on how many times each item has been sold. I can calculate that number and store it in a variable correctly, but when I try to sort the grid by that variable programatically, Genexus won't let me (ofcourse I can click on that row and it'll get sorted correctly, but that's not what I want).
As far as I've read, grids can't be sorted using variables for some reason, is there a workaround for this?
A: You should use a Data Provider to load a SDT with the Top10 list of items, sorted by solded items. Then show the output SDT in a grid.
A: You should try to find a way to load them in the proper order.
If that is not posible, create an SDT Collection with the items and use the method sort.
After that, change the grid to a non-base table grid and use the load event to load the content of the collection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSDateformatter (seems to) throwing an exception. But process does not exit with an error message and call stack Unfortunately, the Mac I'm working on does not allow us to attach a debugger, so I have no idea what the cause it.
Talk about a baptism by fire.
The tutorial program finds four placeholders and replaces them with text from four text fields.
NSString *stringTemplate = [[NSString alloc] initWithString:txtTemplate.text];
// My pseudo debugger
NSLog(@"%@", stringTemplate);
//Start Weird Exit
NSDateFormatter *dateShortFormat = [[[NSDateFormatter alloc]init]autorelease];
[dateShortFormat setDateFormat:NSDateFormatterShortStyle];
//End Weird Exit
//Pseudo debugger
NSLog(@"%@", txtPlace.text);
[stringTemplate stringByReplaceingOccurancesOfString:@"<place>" withString:txtPlace.text];
//txtDate is a TextField
NSLog(@"%@", txtDate.text);
[stringTemplate stringByReplaceingOccurancesOfString:@"<date>" withString:[NSString stringFromDate:[dateShortFormat dateFromString:txtDate.text]]];
//There has to be a shorter way to type that. . .
NSLog(@"%@", txtVerb.text);
[stringTemplate stringByReplaceingOccurancesOfString:@"<verb>" withString:txtVerb.text];
NSLog(@"%@", txtNumber.text);
[stringTemplate stringByReplaceingOccurancesOfString:@"<number>" withString:txtNumber.text];
txvStory.text =stringTemplate;
So I don't ever see the bottom four console messages. But I see the very first message though.
Like always, any improvements would be greatly appreciated. Anything from memory management to design principle advice. Strangely, it is difficult to get a lot of advice in real life. But on the Internet, it seems to come left and right.
A: It looks like you've either got typos in your post, or your actually sending invalid messages to your date formatter. You have:
[stringTemplate stringByReplaceingOccurancesOfString ...
Where you should have
[stringTemplate stringByReplacingOccurancesOfString ...
In other words, there is no "e" in "Replacing"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using QBuffer for binary data I am writing a Qt (4.6) application that is responsible for reading from a usb acm modem device. A mix of raw binary and (ascii) character data is read in from the device. I have a thread that is responsible for constantly reading data from the device into shared memory as it becomes available and second thread that handles processing of this data.
I was thinking of using the QBuffer class as a means to store the data and share it between threads but as I read about QByteArray (which QBuffer uses as a data store). I became worried that the QBuffer will always be appending a '\0' Null character to the end of the data that is being passed between threads since QByteArray exhibits this behavior? Is this the case or will QBuffer allow me to store and retrieve data without enforcing any terminating '\0' character on all of my data?
A: The terminating 0 is transparent to your application.
For instance, if you append "ABC" to an array, "ABC\0" will be appended, but size() will still return 3 and if you subsequently append "DEF" the array will contain "ABCDEF\0" (and size() will still return 6, not 7).
The terminating 0 may be useful in case you request the pointer to the raw data for further processing using functions from the C library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I inject custom audio buffers into a DirectX filter graph using DSPACK? I am using Delphi 6 with DSPACK to do several operations involving audio and DirectX. I have the "input" side figured out where I assign one of the enumerated audio input devices to a TFilter object and connect that filter to a TSampleGrabber object and that gives me the audio buffers I need to send audio to Skype. It is the logical inverse of that graph that I need to figure out. I receive audio buffers from Skype via a socket. I need to create a graph that has a filter that would be the complement to TSampleGrabber. In other words, a TFilter that instead of delivering audio buffers during an event that fires when new audio is available like TSampleGrabber does, would have a similar event that fires when new audio is necessary to feed the graph. At the tail end of this "output" graph would be a TFilter assigned to one of the enumerated audio output devices whose input pins would connect to the output pins of this TSampleGrabber inverse doppelganger.
Does anyone know how to do this? I of course would prefer to avoid writing a custom filter COM object of my own to get this done. I'm hoping that there is an existing TFilter that accepts custom audio buffers to be mixed into a DirectX filter graph.
A: A common starting point for a data injection filter is Push Source Filters Sample. This creates a filter with output only pin, which injects data into DirectShow pipeline, data can be of any type and typically it is video or audio.
As you mentioned Delphi and DSPack, the latter has this sample ported (see \Demos\D6-D7\Filters\PushSource).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Multiple toString() Methods with Generics I have an object which will be stored in two different data structures.
I am using generics, and each structure has to print out the object in a different way. Is there a way to have multiple toString() methods that will invoke accordingly?
I can't create two different methods that return a string, as custom methods are not defined in the generic type, so you can't call them unless you cast it, which breaks the point behind generics.
Should I just create two different objects with different toString() methods for each data structure? Or is there an alternative?
Thanks
A: I think you need to use the toString() of the different objects, but you should still be able to do this with generics in place.
I imagine your generic class has at least one instance of the generic type. If that is the case, override your generic classes toString() to delegate to the generic type object instance.
If your generic class only has a single instance, you can do something like this:
class Holder<T> {
private T instance;
public Holder(T _instance) {
instance = _instance;
}
public String toString() {
return instance.toString();
}
}
And if your class has multiple instances of the generic type (as with many Collection's), you can delegate to each instance of the type.
class CollectionHolder<T> {
private Collection<T> collection;
public CollectionHolder(Collection<T> _collection) {
collection= _collection;
}
public String toString() {
StringBuilder builder = new StringBuilder();
for(T t : collection) {
builder.append(t); //same as builder.append(t.toString())
}
return builder.toString();
}
}
A: If you need to call it on both you need to add it to your interface. It's entirely possible you don't want to use toString() for it, since toString() is supposed to be a human readable representation.
class Nay1 {
String someCrazyMethod() { return "ugh"; }
}
class Nay2 {
String someRandomMethod() { return "ook"; }
}
Well this sucks. You wouldn't want a Nay1 to ook, or a Nay2 to ugh. But you need something uniform!
interface NayInterface {
String nayRepresentation();
}
And your new classes:
class Nay1 implements NayInterface {
String someCrazyMethod() { return "ugh"; }
public String nayRepresentation() { return someCrazyMethod(); }
}
class Nay2 implements NayInterface {
String someRandomMethod() { return "ook"; }
public String nayRepresentation() { return someRandomMethod(); }
}
Now no matter what, you can call myNayInterface.nayRepresentation(); to get your string representation that matches the appropriate class without doing any casting.
class ActuallyDoesSomething<T extends NayInterface> {
String foo;
public ActuallyDoesSomething(T t) {
this.foo = t.nayRepresentation();
}
public String foo() { return foo; }
}
Obviously if you want to use toString() instead of nayRepresentation, you can do that. But this will allow you to not have to consume toString and keep that instead for debugging purposes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set up a Thread and Handler for a SAX parser? I've been trying to set up a UI Thread and Handler for a SAX parser. This is my parser without a UI Thread and Handler implemented:
public class AndroidXMLReader extends ListActivity {
private XMLFeed myXMLFeed = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL xmlUrl = new URL("http://feeds.bbci.co.uk/news/uk/rss.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
XMLHandler myXMLHandler = new XMLHandler();
myXMLReader.setContentHandler(myXMLHandler);
InputSource myInputSource = new InputSource(xmlUrl.openStream());
myXMLReader.parse(myInputSource);
myXMLFeed = myXMLHandler.getFeed();
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myXMLFeed!=null)
{
ArrayAdapter<XMLItem> adapter =
new ArrayAdapter<XMLItem>(this,
android.R.layout.simple_list_item_1,myXMLFeed.getList());
setListAdapter(adapter);
}
}
}
Then here I went and tried to add the UI Thread & Handler. Edit 1 - this is the amended code as per HellBoy's reply:
public class AndroidXMLReader extends ListActivity {
private static final int THREAD_FINISHED = 0;
private XMLFeed myXMLFeed = null;
private ProgressDialog progressDialog;
private Button refreshFeed;
Handler handler = new Handler();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
public void initControls(){
refreshFeed = (Button) findViewById(R.id.refresh);
refreshFeed.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v){
progressDialog = ProgressDialog.show(AndroidXMLReader.this, "",
"Please wait for few seconds...", true);
processThread();
}
});
}
protected void processThread() {
Thread t = new Thread()
{
public void run(){
getNews();
//UI();
// Sends message to the handler so it updates the UI
handler.sendMessage(Message.obtain(mHandler, THREAD_FINISHED));
; }
};
t.start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case THREAD_FINISHED:
progressDialog.dismiss();
break;
};
};
};
private void getNews(){
try {
URL xmlUrl = new URL("http://feeds.bbci.co.uk/news/uk/rss.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
XMLHandler myXMLHandler = new XMLHandler();
myXMLReader.setContentHandler(myXMLHandler);
InputSource myInputSource = new InputSource(xmlUrl.openStream());
myXMLReader.parse(myInputSource);
myXMLFeed = myXMLHandler.getFeed();
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myXMLFeed!=null){
ArrayAdapter<XMLItem> adapter =
new ArrayAdapter<XMLItem>(this,
android.R.layout.simple_list_item_1,myXMLFeed.getList());
setListAdapter(adapter);
}
}
}
At the moment it hangs at the progress dialog and I can't figure out why ... Any help would be appreciated.
Edit 1 - The error message that I get now is:
Only the original thread that created a view hierarchy can touch its
views.
10-04 21:39:27.570: ERROR/AndroidRuntime(17454): at com.android.testfeed3.AndroidXMLReader.getNews(AndroidXMLReader.java:121)
10-04 21:39:27.570: ERROR/AndroidRuntime(17454): at com.android.testfeed3.AndroidXMLReader.access$2(AndroidXMLReader.java:85)
10-04 21:39:27.570: ERROR/AndroidRuntime(17454): at com.android.testfeed3.AndroidXMLReader$3.run(AndroidXMLReader.java:60)
10-04 21:39:27.645: WARN/ActivityManager(2703): Force finishing activity com.android.testfeed3/.AndroidXMLReader
10-04 21:39:33.495: ERROR/WindowManager(17454): Activity com.android.testfeed3.AndroidXMLReader has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40527a20 that was originally added here
10-04 21:39:33.495: ERROR/WindowManager(17454): android.view.WindowLeaked: Activity com.android.testfeed3.AndroidXMLReader has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40527a20 that was originally added here
10-04 21:39:33.495: ERROR/WindowManager(17454): at com.android.testfeed3.AndroidXMLReader$2.onClick(AndroidXMLReader.java:50)
Any help would be appreciated.
A: Try to put your processThread() method like this
protected void processThread() {
Thread t = new Thread()
{
public void run() {
theThread();}
};
t.start();
}
A: In order to make changes to the UI the commands must come from thread that created it, i.e. the main (or UI) thread.
At a quick glance, this line:
if (myXMLFeed!=null)
{
ArrayAdapter<XMLItem> adapter =
new ArrayAdapter<XMLItem>(this,
android.R.layout.simple_list_item_1,myXMLFeed.getList());
setListAdapter(adapter);
}
needs to be put in a separate Handler and that Handler called from your new thread.
A: Just scan your code, but I don't see any problem with it. You may put some debug logs to see which line got stuck. But If I were you , I would have used AsynTask.
Thread and handler come in handy when you want to update the UI from background thread.
AsynTask is used when you fire something that would block the UI.
In your case, I think AsynTask is better.
1) Android Doc of AsynTask
2) Use onPreExecute()(UI Thread) to fire up the pregress dialog you want
3) do the actually URL and SAX parse in doInBackground() (worker thread). This will run the code for you in a background thread so you don't have to init it.
4) onPostExecute() (UI Thread), close the dialog or do whatever you want to update the UI.
A: wait!! What could this be?
protected void processThread() {
Thread t = new Thread();{ <--- a semi-colon
You might wanna check your logic again inside the thread 't'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: using javascript to find position of DOM elements I want to inspect spatial organization of elements on a web page.
Could I get sample code and pointers to resources.
Thanks.
A: Here you go:
function position( elem ) {
var left = 0,
top = 0;
do {
left += elem.offsetLeft;
top += elem.offsetTop;
} while ( elem = elem.offsetParent );
return [ left, top ];
}
Live demo: http://jsfiddle.net/dDyZF/2/
A: You didn't ask for jQuery, but you might want to check out the jQuery dimensions plugin.
A: If you want good, modular code that you can read and easily extract just the bits you want, try David Mark's MyLibrary (which you use to build your library).
I find libraries like jQuery are so intricately bound up in themselves and dependant on their own functionality that trying to track down all the functions and re-mapping of properties is an exercise in frustration. On the other hand, MyLibrary is written to be very modular from the start and provides better cross-browser features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: About add Customized View I want add customized View to ScrollView. In customized View, Only two methods are described, constructor and onDraw(). But the image that drew in onDraw(), isn't show on ScrollView. What's wrong in my program?
A: You might need to override onMeasure() so the view can be sized appropriately. Otherwise it might help if you post some code with your question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery size() and find if class is applied I'm trying to count the li's of a ul. I am using jQuery size() method.
Here is a sample of my HTML:
<ul id="show-items" class="ui-sortable">
<li id="todo-2">
<label class="editable done">fasdfasdf</label>
</li>
<li id="todo-3">
<label class="editable">fasdfasdf</label>
</li>
<li id="todo-4">
<label class="editable">fasdfasdf</label>
</li>
<li id="todo-5">
<label class="editable done">fasdfasdf</label>
</li>
<li id="todo-6">
<label class="editable">fasdfasdf</label>
</li>
</ul>
I use the following code to find all the lists from #show-items but I want to specify only the lists which have label and class done and the lists which haven't got class done.
var n = $("#show-items li").size();
$(".numb").text("There are " + n + " divs. Click to add more.");
This show's me the lists which have the class done:
var n = $("#show-items li").find(".done").size();
$(".numb").text("Clear " + n + " completed task.");
How can I find the lists with no class done? I tried :not(done) but it show's my everything else apart from the lists.
So basically from the above HTML I want to get this:
You have 5 lists. 2 Lists have class done and 3 don't.
Thanks alot
A: You were close. You can use the :not() selector like so:
// <li> without .done class on <label>
$("#show-items li").find("label:not(.done)").size();
// <li> with .done class on <label>
$("#show-items li").find("label.done").size();
Here's an example.
A: Even easier and faster:
alert($("#show-items li label:not(.done)").size());
alert($("#show-items li label.done").size());
you don't have to use find() after a selector.
Fiddle: http://jsfiddle.net/zsbT8/2/
A: You might also want to use the length property instead of size(). As the jQuery docs say:
The .size() method is functionally equivalent to the .length property; however, the .length >property is preferred because it does not have the overhead of a function call.
http://api.jquery.com/size/
http://api.jquery.com/length/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sorting Silverstripe SiteTree by depth I want to get all of the SiteTree pages of a Silverstripe website and then sort them by depth descending. By depth I mean the number of parents they have.
This is already done to some extent by the Google Sitemaps Module. Except it doesn't go past a depth of 10 and doesn't calculate for pages hidden from search: https://github.com/silverstripe-labs/silverstripe-googlesitemaps
Looking at the Google Sitemaps Module module it appears easy enough to count the number of parents of a page: ( /code/GoogleSitemapDecorator.php - line 78)
$parentStack = $this->owner->parentStack();
$numParents = is_array($parentStack) ? count($parentStack) - 1: 0;
But what is the best way to sort the SiteTree using this calculation?
I'm hoping there's an easier way than getting all of the SiteTree, appending the depth, and then resorting.
A: The function below will get all published pages from the database, checks they are viewable and not an error page, finds out how many ancestors they have and then returns a DataObjectSet of the pages ordered by depth (number of ancestors).
public function CustomPages() {
$filter = '';
$pages = Versioned::get_by_stage('SiteTree', 'Live', $filter);
$custom_pages = new DataObjectSet();
if($pages) {
foreach($pages as $page) {
if( $page->canView() && !($page instanceof ErrorPage) ) {
$parentStack = $page->parentStack();
$numParents = is_array($parentStack) ? count($parentStack) - 1 : 0;
$page->Depth = $numParents;
$custom_pages->push($page);
}
}
}
$custom_pages->sort('Depth', 'DESC');
return $custom_pages;
}
A: If you're using PostgreSQL you can also use a single database query. In our effort to speed up SilverStripe (2.4), we've replaced the getSiteTreeFor() with a single database query, see:
http://fvue.nl/wiki/SilverStripe:_Replace_getSiteTreeFor_with_single_query
The breadcrumb field contains an array of ID's on which you can sort.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use a YUI DataSource to populate a HighCharts line chart I want to convert my YUI2 Flash-based charts to a pure javascript implementation. I already have a data source defined using YUI DataSource, but I have been unable to extract the data I need from it to populate my chart.
My code looks like this:
function setupChart(e) {
var dataSource = new YAHOO.util.DataSource(document.location.href + '/index/charts');
dataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
dataSource.responseSchema = {
fields: ['date', 'cust_view', 'cust_upd', 'notes', 'mydata_comp', 'mydata_not_completable'] };
var mychart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: { text: null },
xAxis: {
type: 'datetime',
tickInterval: 7 * 24 * 3600 * 1000 // one week
},
yAxis: {
title: { text: null }
},
series: [
{ name: 'Viewed', data: 'cust_view' }
{ name: 'Updated', data: 'cust_upd' }
{ name: 'Notes Created', data: 'notes' },
{ name: 'myData Completions', data: 'mydata_comp' },
{ name: 'myData marked as Incompletable', data: 'mydata_not_completable' } ]
});
}
So, I know that dataSource holds the values I want, but I don't know how to format the syntax in HighCharts to get it out of there.
First question on SO, sorry if not clear.
A: You're missing the step of retrieving the data from your server.
That is done with an Ajax call. The data will be available in the callback function that you provide. You will create the chart in the callback function Not in the mainline. Eg
dataSource.sendRequest("get_data.php",
{
success: function (req,res) {
// res.results holds the results. Use
// firebug to see its format
// The format is an array of JS objects.
// Each element of the array is an object with
// properties from your fields configuration.
//
// Eg
[
{ date: "xxx", cust_view: "red", notes: "apples", ... },
{ date: "xxx", cust_view: "green", notes: "vegetable", ... },
{ date: "xxx", cust_view: "cherries", notes: "fruit", ... },
...
]
// create the Highcharts.chart and add the data to it
// here
}
failure: function () {
alert("Couldn't contact server");
}
});
See examples from YUI docs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Improving performance by having a global array or file for all visitors? In my application I have two pages. Index and engine. Index has mostly jQuery scripts and the basic two of them is an autoload function for the engine.php file that happens every 3 mins, and the other one is a "show more" button that shows 10 more posts when it is clicked.
$feeds = array('','');
$entries = array();
foreach ($feeds as $feed) {
$xml = simplexml_load_file($feed);
$entries = array_merge($entries, $xml->xpath('/rss/channel//item'));
}
What I am looking for is a way to separate the $feeds = array('',''); part that is loaded with the engine.php on every 3 mins or click.
What is your suggestions about that ?
A: I'm not sure I understand your question, but global variables are defined in php if they're defined outside all functions. To use them inside, you have to reference it like this before using it:
$variable = ""; //this variable is global
function test(){
global $variable;
//now you can use your variable
}
If what you meant, is that the value for your variable need to be persisted between requests, then I would suggest you use the $_SESSION array (link).
If this does not answer your question let me know.
Edit for updated answer
You'll have to persist the $feeds array in some way. I think the easiest way would be to use the session, but that won't make the array available to all users like you mentioned. So I'd suggest you persist the list of feed on a file, that way you can access the same information every time for all users.
Doing that you can create a new script that will updated the file whenever you want (i.e every 10 minutes), and the engine.php will only have to work directly with the file.
Do you need some specific help with code for this proposed solution? Does it help you solve your problem?
Edit2
To save your $feeds array to a file, simply do the following (I guess this part you already know):
$fp = fopen("feeds.txt", "a");
if($fp) {
foreach($feeds as $line) {
fwrite($fp, $line."\n");
}
fclose($fp);
}
And to load that same file, you can do this:
$feeds = file("feeds.txt"); //This will load each line into a different position of the array $feeds.
If you want to serialize the $entries array, I would suggest taking a look at serialize & unserialize functions
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Writer vs WriterT in Haskell What is the difference between Writer and WriterT in Haskell? Is one preferred over the other?
A: To add to the excellent explanations above, I'd like to also point to this paper. Has helped me quite a bit:
Monad Transformers Step By Step
A: The difference is that Writer is a monad, whereas WriterT is a monad transformer, i.e. you give it some underlying monad, and it gives you back a new monad with "writer" features on top. If you only need the writer-specific features, use Writer. If you need to combine its effects with some other monad, such as IO, use WriterT.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Single login, multiple application authentication Is there a Codeigniter authentication server that's available for use? Trying to get a multi-application service going similar to Basecamp and I don't want to reinvent the wheel. Alternatively, are there any respectable resources that deal with this kind of authentication?
Thanks!
A: Or, you can implement an OpenID service and have all of your CI applications connect via openid. This is the way StackOverflow does it. I'd google "codeigniter openid" to see what's available. here's a sampling:
http://thinkmoult.com/2009/02/22/use-codeigniter-openid-library-to-integrate-openid/
http://codeigniter.com/wiki/OpenID
A: You should be able to create a user db, and authentication library to do the job.
TankAuth maybe?
You can have 2 applications either seperately installed, or sharing a CI installation using the same library and authentication database. I'd keep everything else application specific, just share profile and login information.
A: Facebook connect offers good authentication possibilities. Also Google, Yahoo! and many other big sites offers similar posibilities.
If you mean that you want some form of 'register at one site get them all'-service, all you need to do is point the authentication to the same database on all sites.
Another posibility is making an authentication page then using cURL or AJAX to check authentication.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Silverlight Binding to commands Sometimes when I bind to commands to a ViewModel, my CanExecute code does not always get called and hence my buttons are not disabled when they should be.
Any ideas?
Thanks
A: When canExecute is not called the first time, that's a binding problem.
If it's not 'automatically' called second,[n]th time, that's the normal behavior.
Imagine, how the UI should know that it should requery your predicate? When you have a command parameter it will call your predicate every time the parameter changes. Generally, some UI 'events' also requery it (focus, updatelayout etc), but not always (that's good, it would be pointless to reevaluate every command binding all time). So you cannot rely on it. You make the business logic, so you know when it needs an update, not the UI. The UI 'cannot see inside your predicate delegate' and watch what happens. You have to notify the UI about it, same as you notify when a property changed.
ICommand has an event, so you must implement it, it's the CanExecuteChanged.
You should implement a public method to fire it (or it is already implemented if you use a framework, like MVVMLight or Prism).
A simple implementation.
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
So you can call it on your command whenever your canExecute state changes in your business logic and it is going to notify all the subscribers, which is your button in this case.
A: You mention the state of the button not being disabled. This seems more like a binding issue than binding to commands. Is the state of the property you are binding to changing? When is it changing, etc.?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google TV emulator in bridge network mode I want to connect to my app running in the emulator from another machine on my local network. The ip assigned to emulator is 10.0.2.15 while my host machine has ip 192.168.1.* . Is there any way to run the emulator in bridge mode such that it gets an ip in the range 192.168.1.* ?
A: The Android Emulator has a virtual router connecting it to the network. You can use the redir command to setup network connections. See this article:
http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: var's I keep declaring the same things over again Not sure if there is away to do what I want, I basically need to store the following information in a global var, and if they are being requested, then be able to fetch them from any public function without having to re-send it to the function that needs the information at current I am doing the following
public function savenewbusinesslead($tradingname, $companyname)
{
$this->tradingname = $tradingname;
$this->companyname = $companyname;
}
public function sendemail($email,$tradingname){
$this->email = $email;
$this->tradingname = $tradingname
}
What I want to do is the following
private function global($tradingname, $companyname){
$this->tradingname = $tradingname;
$this->companyname = $companyname;
}
public function savenewbusinesslead(){
print $this->global->tradingname;
}
A: To reference a global variable from within your methods, you need to use the global keyword, like this:
//assuming $tradingname is defined ouside your method
public function savenewbusinesslead(){
global $tradingname;
print $tradingname;
}
Does this help?
A: You can always use a static variable in your class to handle this.
More over there: http://www.php.net/manual/en/language.oop5.static.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Join only for specific rows where value matches a variable I have multiple MySQL tables containing varying numbers of columns. After joining three of the tables, I have a resulting table that's structured as follows:
+------------+------------+-----------+-------+------+
| student_id | first_name | last_name | class | rank |
+------------+------------+-----------+-------+------+
| 1 | John | Doe | 2012 | 1 |
+------------+------------+-----------+-------+------+
| 2 | Suzy | Public | 2013 | 12 |
+------------+------------+-----------+-------+------+
| 3 | Mike | Smith | 2014 | 50 |
+------------+------------+-----------+-------+------+
I also have two additional tables that aren't involved in the initial join:
interest
+-------------+------------+-----------------------+----------------+
| interest_id | student_id | employer_interest | interest_level |
+-------------+------------+-----------------------+----------------+
| 1 | 1 | Wayne Enterprises | High |
+-------------+------------+-----------------------+----------------+
| 2 | 1 | Gotham National Bank | Medium |
+-------------+------------+-----------------------+----------------+
| 3 | 2 | Wayne Enterprises | Low |
+-------------+------------+-----------------------+----------------+
| 4 | 3 | Gotham National Bank | High |
+-------------+------------+-----------------------+----------------+
offers
+----------+------------+-----------------------+
| offer_id | student_id | employer_offer |
+----------+------------+-----------------------+
| 1 | 1 | Wayne Enterprises |
+----------+------------+-----------------------+
| 2 | 1 | Gotham National Bank |
+----------+------------+-----------------------+
| 3 | 2 | Wayne Enterprises |
+----------+------------+-----------------------+
The interest and offers table won't necessarily contain a record for every student_id but at the same time contain multiple records that reference a single student_id.
For each of the latter two tables, I'd like to:
*
*Select all rows where the employer_interest or employer_offer value is equal to $var (a variable I've set in PHP)
*Join these rows to the original table
For example, if $var is set to Wayne Enterprises, I'd like the resulting table to be:
+------------+------------+-----------+-------+------+-------------------+----------------+-------------------+
| student_id | first_name | last_name | class | rank | employer_interest | interest_level | employer_offer |
+------------+------------+-----------+-------+------+-------------------+----------------+-------------------+
| 1 | John | Doe | 2012 | 1 | Wayne Enterprises | High | Wayne Enterprises |
+------------+------------+-----------+-------+------+-------------------+----------------+-------------------+
| 2 | Suzy | Public | 2013 | 12 | Wayne Enterprises | Low | Wayne Enterprises |
+------------+------------+-----------+-------+------+-------------------+----------------+-------------------+
| 3 | Mike | Smith | 2014 | 50 | NULL | NULL | NULL |
+------------+------------+-----------+-------+------+-------------------+----------------+-------------------+
Is what I'm trying to do possible using just a MySQL query? If so, how do I do it?
A: it sounds like you just need a LEFT JOIN to the other tables since it appears you want to see all students from the first set regardless of any job offer/interest.
If so... ensure both the "Interest" and "Offers" tables have an index where the student ID is either a single element index, or first in that of a compound index.
select STRAIGHT_JOIN
ORS.Student_ID,
ORS.First_Name,
ORS.Last_Name,
ORS.Class,
ORS.Rank,
JI.Employer_Interest,
JI.Interest,
OFR.Employer_Offer
from
OriginalResultSet ORS
LEFT JOIN Interest JI
ON ORS.Student_ID = JI.Student_ID
AND JI.Employer_Interest = YourPHPVariable
LEFT JOIN Offers OFR
on JI.Student_ID = OFR.Student_ID
AND JI.Employer_Interest = OFR.Employer_Offer
To prevent "NULL" results in the employer interest, interest and offer, you can wrap them in a Coalesce() call such as (for all three columns on left join)
COALESCE( JI.Employer_Interest, " " ) Employer_Interest
A: Your query should be something like this:
select
s.student_id, s.first_name, s.last_name, s.class, s.rank,
i.employer_interest, i.interest_level,
o.employer_offer
from students s
left join interest i
on i.student_id = s.student_id
and i.employer_interest = 'Wayne Enterprises'
left join offers o
on o.student_id = s.student_id
and o.employer_offer = 'Wayne Enterprises'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending Data to Website From iPhone I'm creating an iPhone Game where I want the user to get a unique numeric code when they first launch the app, that way when a friend of that user opens it, he/she can input that code and both users can get rewarded. I haven't encountered any issues regarding that, however what I want to do is make it to where the app registers the code given to every user and saves it to a website of some sort. That way when the other user enters the code, it will load the data from that website and check if it's registered. How would I manage to save the data onto a website? and also What free website could I use for this without having a character limit on the body page?
-Thanks in advance
A: You can send data using NSURLConnection. Just create an NSMutableURLRequest and call its -setHTTPMethod: method with “POST” as the HTTP method. Then, set its body and header fields appropriately, and you can use NSURLConnection to send the data.
A: Your thinking is correct, in that you need to save your data somewhere online, but you don't really "save data onto a website" in the way that you're describing. "Free Website" services usually serve a different purpose entirely - that of serving up public html pages. Sure, they can take the form of a CMS (like wordpress.com or tumblr accounts), but using that as an interface for storing your application's data is not something they're typically designed to do.
For something like this, where you have a public iPhone app that requires secure access to custom strings, you really want to have control over your own web server (different than a domain name, btw), and interface with a database on that server. This will come at a cost, and will involve more code than you're likely to find someone to write for you on here. Sorry to say it, but hey if someone wants to prove me wrong I'd love to see it.
Because all you need to store & retrieve are random strings (basically referral codes... if I'm understanding correctly), your database needs are pretty simple. If you're not familiar with things like PHP / MySQL, and you don't want to learn, it might be worth reaching out to some server-side developers for help. Unless there's more to it than you describe, you can probably find someone to help you for relatively cheap.
Good luck - and I'm sorry there isn't a simpler answer for ya.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Converting an unsigned char* to readable string & whats this function doing I have googled alot to learn how to convert my unsigned char* to a printable hex string. So far I am slightly understanding how it all works & the difference between signed & unsigned chars.
Can you tell me what this function I found does? And help me devlop a function that converts a unsigned char*(which is a hashed string) to a printable string?
Does the following function do this:
- it iterates over every second character of the char array string
- on each loop it reads the char at the position string[x], converts it to an unsigned number(with a precision of 2 decimal places) then copies that converted char(number?) to the variables uChar.
- finally it stores the unsigned char uChar in hexstring
void AppManager :: stringToHex( unsigned char* hexString, char* string, int stringLength )
{
// Post:
unsigned char uChar = 0;
for ( int x = 0; x<stringLength; x+=2 )
{
sscanf_s(&string[x], "%02x", &uChar);
hexString[x] = uChar;
}
}
So I guess that means that it converts the character in string to unsigned(& 2dcp) to ensure that it can be correctly stored the hexstring. Why to 2 decimal places, & wont a simple conversion from signed(if that character is signed) to unsigned result in a completely different string?
If I have a unsigned char* how can I go about converting it to something that will let me print it out on screen?
A: Those aren't decimal places, they're digits. You're saying "don't give me a string shorter than 2; if it's shorter than 2 digits, then pad it with a zero."
This is so that if you have a hex sequence 0x0A it'll actually print 0A and not just A.
Also, there is no signed/unsigned conversion here. Hex strings are hex strings - they don't have a sign. They're a binary representation of the data, and depending on how they're interpreted may be read as two's complement signed integers, unsigned integers, strings, or anything else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Yii: Piggybacking on Session GC For Cart Cleanup? I am building a shopping cart using the Yii framework. I have created a cart model to store the items the user adds to the cart, and I'm keeping track of the products that guest shoppers are adding to the cart by using a session_id field that stores the current session.
However, if the shopper abandons the cart or the session simply times out before they proceed to the checkout I find that I have a bunch of records in the cart table that need to be cleaned up.
I was thinking that the best way to do this would be to piggy back on the garbage collection process that Yii uses to clean up the session table, but I'm not sure how to do this, or even if this is the best way.
Am I on the right track here?
If so, how do I go about piggybacking on Yii's garbage collection?
A: I don't know much about PHP's session garbage collection, so I don't know if this is a better way to go than a cron job. The little I do know I just learned from Professor Google, and it makes me think relying on the session garbage collection may not be as reliable as you want:
How do I expire a PHP session after 30 minutes?
But it could work, I suppose. Kind of clever, actually, if it does. And in this case, you would need to override the gcSession() method in the CDbHttpSession class in the Yii core (assuming, as you say, you are using the database session storage). You can override this method very easily, actually, in your config.php file.
First, create your new MyCustomHttpSession class which extends CDbHttpSession (drop it in your /components folder probably). Be sure to add your new custom Cart garbage collection to the gcSession() function!
class MyCustomHttpSession extends CDbHttpSession
{
public function gcSession($maxLifetime) {
/**** ADD YOUR CUSTOM LOGIC HERE ****/
$sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
$this->getDbConnection()->createCommand($sql)->execute();
return true;
}
}
Then, tell Yii to use your new MyCustomHttpSession class in the components configuration array:
'components'=>array(
'session'=>array(
'class' => 'application.components.MyCustomHttpSession',
'connectionID' => 'db',
'timeout'=>14400, // 4 hour session time
),
),
I did not test this, but it should work just fine. Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting Controller / View to recognize different table I am using Devise in Rails to help authenticate users. I am trying to create users within the system. I created a scaffold (just for the auto-generated code) Employee, and I changed the table in the employees_controller.rb to User. When I list the employees, it correctly lists the users. But when I attempt to add a new user, it gives me the error:
undefined method `users_path' for #<#<Class:0x7fb289704bd8>:0x7fb289702540>
It gives me the error for the line:
<%= form_for(@employee) do |f| %>
What can I do to allow this to work correctly?
A: I wouldn't use scaffolding for your user model when implementing devise. However, if you use scaffolding, I would create that first and then follow this tutorial for adding devise to that model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: generic linked list pointer access I am writing a generic linked list in C++ using templates, and am experiencing Segmentation Faults when accessing Node values.
To make the test case simpler, I have implemented a fixed size, two node, linked list.
I have two questions:
1a) Why isn't aList.headNodePtr->prevNodePtr set to NULL?
1b) Why isn't aList.tailNodePtr->nextNodePtr set to NULL?
I set both of these values to NULL in the LinkedList constructor, but the output in main shows that:
head prevAddress: 0x89485ed18949ed31
tail nextAddress: 0x7fffe8849679
2) Why does the following line in main() cause a Seg Fault?
aList.headNodePtr->nodeValue = 1;
The full code is below:
#include <iostream>
using namespace std;
template <class T>
class Node {
public:
Node<T>* prevNodePtr;
Node<T>* nextNodePtr;
T nodeValue;
};
template <typename T>
class LinkedList {
public:
Node<T>* headNodePtr;
Node<T>* tailNodePtr;
LinkedList() {
Node<T>* headNodePtr = new Node<T>;
Node<T>* tailNodePtr = new Node<T>;
headNodePtr->prevNodePtr = NULL;
headNodePtr->nextNodePtr = tailNodePtr;
tailNodePtr->prevNodePtr = headNodePtr;
tailNodePtr->nextNodePtr = NULL;
}
~LinkedList() {
headNodePtr = NULL;
tailNodePtr = NULL;
delete headNodePtr;
delete tailNodePtr;
}
};
int main()
{
LinkedList<int> aList;
cout << "head Value: " << aList.headNodePtr->nodeValue << endl;
cout << "head prevAddress: " << aList.headNodePtr->prevNodePtr << endl;
cout << "head nextAddress: " << aList.headNodePtr->nextNodePtr << endl;
cout << "tail Value: " << aList.tailNodePtr->nodeValue << endl;
cout << "tail prevAddress: " << aList.tailNodePtr->prevNodePtr << endl;
cout << "tail nextAddress: " << aList.tailNodePtr->nextNodePtr << endl;
aList.headNodePtr->nodeValue = 1;
}
A: You're not actually setting the members, you're setting the locals you declared in the ctor:
Node<T>* headNodePtr; // <-- MEMBERS
Node<T>* tailNodePtr;
LinkedList() {
Node<T>* headNodePtr = new Node<T>; // <-- LOCALS
Node<T>* tailNodePtr = new Node<T>;
Try this instead:
Node<T>* headNodePtr; // <-- MEMBERS
Node<T>* tailNodePtr;
LinkedList() {
headNodePtr = new Node<T>; // <-- MEMBER ACCESS
tailNodePtr = new Node<T>;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Queues as global and working on its contents from main I am getting errors about the template arguments not being valid and it is not seeing that I declared my queue variables as global.., i tried putting them inside the function (but thats not what I want because i want to deque from main) and does not work either.. Here are my errors and code
program.cpp: In function ‘int main(int, char**)’:
program.cpp:62:24: error: argument of type ‘bool (std::queue<std::basic_string<char> >::)()const’ does not match ‘bool’
program.cpp:62:24: error: in argument to unary !
program.cpp:68:23: error: argument of type ‘bool (std::queue<std::basic_string<char> >::)()const’ does not match ‘bool’
program.cpp:68:23: error: in argument to unary !
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <string>
#include <queue>
#include <iostream>
#define SIZE 100
using namespace std;
queue<string> bfFilesQueue;
queue<string> bfDirsQueue;
static int display_info(const char *fpath, const struct stat *sb,
int tflag, struct FTW *ftwbuf)
{
//Check the type of Flag (i.e File or Directory)
switch(tflag)
{
case FTW_D:
case FTW_F:
bfFilesQueue.push(fpath);
break;
case FTW_DP:
bfDirsQueue.push(fpath);
break;
}
return 0; /* Continue */
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
return 1;
}
int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS;
if (nftw(argv[1], display_info, 20, 1) == -1)
{
perror("nftw");
return 255;
}
printf("***************************\n");
while(!bfFilesQueue.empty)
{
cout << bfFilesQueue.front() << " ";
bfFilesQueue.pop();
}
while(!bfDirsQueue.empty)
{
cout << bfDirsQueue.front() << " ";
bfDirsQueue.pop();
}
return 0;
}
A: Your while statements are attempting to check the function std::queue::empty() itself, and not the result of a call to the function. The type that appears in your error message is the type of the function.
As overcoder's comment says, adding parentheses will fix the code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I install the Python library 'gevent' on Mac OS X Lion Python library gevent, version 0.13.6 (the current version on PyPI) will not pip install on OS X Lion, Python 2.7 (and probably others.) It works fine on Snow Leopard.
How can I get this library installed?
Bonus points if it can be done using pip install, rather than a manual or custom process, because then it will play nicely with automated builds.
Here is my pip install output:
pip install gevent
Downloading/unpacking gevent
Running setup.py egg_info for package gevent
Requirement already satisfied (use --upgrade to upgrade): greenlet in ./tl_env/lib/python2.7/site-packages (from gevent)
Installing collected packages: gevent
Running setup.py install for gevent
building 'gevent.core' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c gevent/core.c -o build/temp.macosx-10.6-intel-2.7/gevent/core.o
In file included from gevent/core.c:225:
gevent/libevent.h:9:19: error: event.h: No such file or directory
gevent/libevent.h:38:20: error: evhttp.h: No such file or directory
gevent/libevent.h:39:19: error: evdns.h: No such file or directory
gevent/core.c:361: error: field ‘ev’ has incomplete type
gevent/core.c:741: warning: parameter names (without types) in function declaration
gevent/core.c: In function ‘__pyx_f_6gevent_4core___event_handler’:
gevent/core.c:1619: error: ‘EV_READ’ undeclared (first use in this function)
gevent/core.c:1619: error: (Each undeclared identifier is reported only once
gevent/core.c:15376: warning: assignment makes pointer from integer without a cast
[... about 1000 more lines of compiler errors...]
gevent/core.c:15385: error: dereferencing pointer to incomplete type
gevent/core.c: In function ‘__pyx_pf_6gevent_4core_4http___init__’:
gevent/core.c:15559: warning: assignment makes pointer from integer without a cast
gevent/core.c: At top level:
gevent/core.c:21272: error: expected ‘)’ before ‘val’
lipo: can't figure out the architecture type of: /var/folders/s5/t94kn0p10hdgxzx9_9sprpg40000gq/T//cczk54q7.out
error: command 'gcc-4.2' failed with exit status 1
Complete output from command /Users/jacob/code/toplevel/tl_env/bin/python -c "import setuptools;__file__='/Users/jacob/code/toplevel/tl_env/build/gevent/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/s5/t94kn0p10hdgxzx9_9sprpg40000gq/T/pip-s2hPd3-record/install-record.txt --install-headers /Users/jacob/code/toplevel/tl_env/bin/../include/site/python2.7:
running install
running build
running build_py
running build_ext
building 'gevent.core' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386 -arch x86_64 -g -O2 -DNDEBUG -g -O3 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c gevent/core.c -o build/temp.macosx-10.6-intel-2.7/gevent/core.o
A: This is the way I found the easiest:
install libevent using homebrew
$ brew install libevent
install gevent
$ pip install gevent
This was the only way I could get it to work.
A: Found this answer when looking for help installing on Snow Leopard, posting this in case someone else comes this way with the same problem.
I had libevent installed via macports.
export CFLAGS=-I/opt/local/include
export LDFLAGS=-L/opt/local/lib
sudo pip install gevent
A: CFLAGS='-std=c99' pip install gevent
See in: Can't install gevent OSX 10.11
on OS X 10.11, clang uses c11 as the default, so just turn it back to c99.
A: I had libevent installed via brew and it failed too, what worked was similar to what Stephen done, but pointing to brew default install:
CFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib pip install gevent
A: After a while, I realized that the paths for the CFLAGS variable mentioned above works when installing libevent from port, but not from brew. The following worked for me (on OSX Mavericks):
$ brew install libevent
$ export CFLAGS="-I /usr/local/Cellar/libevent/2.0.21/include -L /usr/local/Cellar/libevent/2.0.21/lib"
$ pip install gevent
A: Don't post the entire thing! That's too much! 90% of the time, the first error is enough...
gevent/libevent.h:9:19: error: event.h: No such file or directory
This means that the library which provides the event.h header is not installed. The library is called libevent (website).
In general, compilation errors like these are a flaw in the build scripts. The build script should give an error message that libevent is not installed, and it is a bug that it did not do so.
To get libevent from MacPorts and then manually tell compiler with CFLAGS environment variable where to find event.h and libevent while running pip.
sudo port install libevent
CFLAGS="-I /opt/local/include -L /opt/local/lib" pip install gevent
You can also use homebrew for installing libevent : brew install libevent
(from David Wolever's comment)
A: In case you install all from sources and use csh the following works on mac os 10.9
*
*download latest stable http://libevent.org/ libevent-2.0.21-stable
*
*./configure
*make
*sudo make install
*virtualenv env
*source env/bin/activate.csh
*setenv CFLAGS "-I /usr/local/include -L /usr/local/lib"
*pip install gevent
A: I use virtualenv and virtualenv wrapper, and so I wanted this to be self contained. I got gevent working like so:
Assuming you have virtual env setup, then:
workon {my_virtual_env}
Then download libevent and install it against the virtualenv.
curl -L -O https://github.com/downloads/libevent/libevent/libevent-2.0.21-stable.tar.gz
tar -xzf libevent-2.0.21-stable.tar.gz
cd libevent-2.0.21-stable
./configure --prefix="$VIRTUAL_ENV"
make && make install
I'm assuming you've got gcc 5+ installed (I use brew)
Hope this helps.
A: sudo pip install cython git+git://github.com/gevent/gevent.git#egg=gevent
A: I am using MacOs High Sierra (10.13.3)
First I did :
brew install libevent
I upgraded my pip version to pip-18.0.
then tried installing again with following :-
pip install gevent
it worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
} |
Q: How to capitalize first letters in each word of RichTextBox.Text? How can I switch the first letter of each word of RichTextBox.Text to upper case?
For example, I need to switch this text:
"This is a big and beautiful dog."
To this text:
"This is a Big And Beautiful Dog".
That means I need to capitalize the first letter in the words which include three letters or more. It is difficult for me. Also, there are many lines in RichTextBox.Text.
A: Try this :
System.Globalization.CultureInfo cultureInfo =
System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
richTextBox1.Text = textInfo.ToTitleCase(RichTextBox.Text);
A: Try this.
string[] str = richTextBox1.Text.Split(' ');
string a="";
string b="";
for (int i = 0; i < str.Length; i++)
{
if (str.GetValue(i).ToString().Length > 2)
{
b = str.GetValue(i).ToString().Replace(str.GetValue(i).ToString().Substring(0, 1), str.GetValue(i).ToString().Substring(0, 1).ToUpper());
}
else
{
b = str.GetValue(i).ToString();
}
a = a + " " + b;
}
richTextBox1.Text = a;
A: You can capitalize the first letter of each word according to CultureInfo by simply using this:
Note: "test" is a sample property as Name, Surname, Address, etc.
text = string.IsNullOrEmpty(text) ?
string.Empty :
CultureInfo
.CurrentCulture
.TextInfo
.ToTitleCase(text.ToLower(new CultureInfo("tr-TR", false)));
Please note that, in here there is an extra control for null values.
A: I have this extension. Note - it makes everything Capitalized, so that eMail will become Email. Good about it - it works on arrays with no concatenations.
public static string Capitalize(this string value)
{
char[] chars = value.ToLower().ToCharArray();
bool isNewWord = true;
for (int i = 0; i < chars.Length; i++)
{
if (char.IsWhiteSpace(chars[i]))
{
isNewWord = true;
continue;
}
if (isNewWord)
{
chars[i] = char.Parse(chars[i].ToString().ToUpper());
isNewWord = false;
}
}
return new string(chars);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can LINQ ToArray return a strongly-typed array in this example? I've contrived this example because it's an easily digested version of the actual problem I'm trying to solve. Here are the classes and their relationships.
First we have a Country class that contains a Dictionary of State objects indexed by a string (their name or abbreviation for example). The contents of the State class are irrelevant:
class Country
{
Dictionary<string, State> states;
}
class State { ... }
We also have a Company class which contains a Dictionary of zero or more BranchOffice objects also indexed by state names or abbreviations.
class Company
{
Dictionary<string, BranchOffice> branches;
}
class BranchOffice { ... }
The instances we're working with are one Country object and an array of Company objects:
Country usa;
Company companies[];
What I want is an array of the State objects which contain a branch. The LINQ I wrote is below. First it grabs all the companies which actually contain a branch, then joins to the list of states by comparing the keys of both lists.
The problem is that ToArray returns an anonymous type. I understand why anonymous types can't be cast to strong types. I'm trying to figure out whether I could change something to get back a strongly typed array. (And I'm open to suggestions about better ways to write the LINQ overall.)
I've tried casting to BranchOffice all over the place (up front, at list2, at the final select, and other less-likely candidates).
BranchOffice[] offices =
(from cm in companies
where cm.branches.Count > 0
select new {
list2 =
(from br in cm.branches
join st in usa.states on br.Key equals st.Key
select st.Value
)
}
).ToArray();
A: You can do:
select new MyClassOfSomeType {
..
)
For selection, you can give it a custom class type. You can also then use ToList. With ArrayList, if you need to keep it loosely typed, you can then make it strongly typed later using Cast<>, though only for any select result that doesn't generate an anonymous class.
HTH.
A: If i understand the problem correctly, the you want just the states that have office brances in them, not the branches too. If so, one posible linq is the following:
State[] offices =
(from cm in companies
where cm.branches.Count > 0
from br in cm.branches
join st in usa.states on br.Key equals st.Key
select st.Value
).Distinct().ToArray();
If you want both the states and the branches, then you will have to do a group by, and the result will be an IEnumerable>, which you can process after.
var statesAndBranches =
from cm in companies
where cm.branches.Count > 0
from br in cm.branches
join st in usa.states on br.Key equals st.Key
group br.Value by st.Value into g
select g;
Just one more thing, even though you have countries and branches declared as dictionaries, they are used as IEnumerable (from keyValuePair in dictionary) so you will not get any perf benefit form them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XPath select descendent of parents sibling with in limits My xpath:
(//tr[td[contains(., 'Refine by Vehicle Types')]])[1] /following-sibling::tr /td/div/table /tr/td/font /ul/li/a
My source:
<tr><td><font color="White">Refine by Vehicle Types</font></td> </tr>
<tr><td><div>
<table> <tr> <td><font<ul><li><a> Automobile/Light Trucks</a></li></ul></font></td> </tr> </table>
</div></td> </tr>
<tr> <td></td> </tr>
<tr> <td><font>Refine by Category</font></td> </tr>
<tr> <td><div>
<table> <tr> <td><font><ul><li><a>Agricultural</a></li></ul></font></td></tr>
I'm trying to scrape this source and collect the <li> nodes after "Refine by Vehicle Types" but not after "Refine by Category".
Any help is appriciated.
A: You are almost there.
Change:
(//tr
[td[contains(., 'Refine by Vehicle Types')]]
)
[1]
/following-sibling::tr
/td/div/table
/tr/td/font
/ul/li/a
to:
(//tr
[td[contains(., 'Refine by Vehicle Types')]]
)
[1]
/following-sibling::tr[1]
/td/div/table
/tr/td/font
/ul/li/a
When the second XPath expression is evaluated against the following XML document (your severely malformed text corrected to become a well-formed XML document):
<table>
<tr>
<td>
<font color="White">Refine by Vehicle Types</font>
</td>
</tr>
<tr>
<td>
<div>
<table>
<tr>
<td>
<font>
<ul>
<li>
<a> Automobile/Light Trucks</a>
</li>
</ul>
</font>
</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<font>Refine by Category</font>
</td>
</tr>
<tr>
<td>
<div>
<table>
<tr>
<td>
<font>
<ul>
<li><a>Agricultural</a></li>
</ul>
</font>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
Only one -- the wanted -- a element is selected:
<a> Automobile/Light Trucks</a>
Note: Did I mention that an XPath Visualizer will help you a lot?
A: For a robust XPath, which will work no matter how many tr/li elements are between the two text labels, try:
(//tr
[td[contains(., 'Refine by Vehicle Types')]]
)[1]
/following-sibling::tr[not(preceding-sibling::tr
[contains(., 'Refine by Category')])]
/td/div/table
/tr/td/font
/ul/li/a
(Borrowing from @Dimitre's formatting.)
The above is inefficient (could be O(n^2)), so if you have a long page, it could get slow.
But for moderate pages it should be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pausing in game to display score I'm new to Android and I'm not sure how to tackle this one.
I'm making a Pong like game, and after a score is made, I want to display the score for a few seconds while pausing the game.
I'm using the onDraw() method like this:
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(_bitmapStore.get(R.drawable.batblue),bluebat.getX() - (_bitmapStore.get(R.drawable.batblue).getWidth() /2),bluebat.getY(),null);
canvas.drawBitmap(_bitmapStore.get(R.drawable.ball),ball.getX() - (_bitmapStore.get(R.drawable.ball).getWidth() /2),ball.getY()-(_bitmapStore.get(R.drawable.ball).getHeight() /2), null);
canvas.drawBitmap(_bitmapStore.get(R.drawable.batred),redbat.getX() - (_bitmapStore.get(R.drawable.batred).getWidth() /2),redbat.getY(),null);
if(drawScore){
canvas.drawBitmap(_bitmapStore.get(R.drawable.user),200,200, null);
canvas.drawBitmap(_bitmapStore.get(R.drawable.cpu),400,200, null);
}
}
I want it to draw the score for a few seconds, but don't know how to pause.
I tried the thread.sleep() method, even though I know it's not recommended. But it didn't do nothing except for slowing the game down.
The images are displayed only once a score is made, but the game keeps on running behind it.
A: I would separate out your drawing from your engine. If your engine worked something like this
for(Drawable d : engine.getComponentsToDraw()) d.draw(canvas);
you would get this for free essentially. Obviously this is abstract: you may or may not have a Drawable interface. But this will give you a lot of power over your game. Instead of having a variable to draw a score or not, you'd have an object in a list (probably a map, actually) that would get added and removed after a particular amount of time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP how to remove the last part of a filename after underscore A filename looks like whatever_test_123234545.gif.
What is the easiest way to remove the last underscore followed by all characters and numbers after it but not the the dot extension.
In other words i want whatever_test_123234545.gif to look like whatever_test.gif. A filename can have a random number of underscores. I just want to remove the last part before .ext.
A: This will remove everything between the last underscore and the .. If the filename does't have a . or doesn't have an _ it will not change the filename:
$filename = 'whatever_test_123234545.gif';
$new_filename = preg_replace('/_[^_.]*\./', '.', $filename);
And to actually rename the file:
rename($filename, $new_filename);
A: The below code will replace the last _XXXXXX before the . where XXX is any number.It will replace only if XXX is a number.
$filename = 'whatever_test_56623736373738333.gif';
$new_filename = preg_replace('/_[0-9]+(\.)/', '.', $filename, 1);
A: $x = 'whatever_test_123234545.gif';
$newstring = substr($x, 0, strrpos($x, '_')).substr($x, strrpos($x, '.'));
A: This one will replace the last _XXXXXX before the . where XXX is any string.
<?php
echo preg_replace('/_[a-zA-Z0-9]+(\.)/', '.', 'whatever_test_123234545.gif', 1);
?>
// Prints: whatever_test.gif
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: node.js rename and AWS
Possible Duplicate:
Move file to a different partition using node.js
I'm using fs.renameSync to rename a /tmp file to a file in a directory on a mounted EBS file-system on an AWS micro-instance. I get the error :
Error: EXDEV, Invalid cross-device link '/tmp/55fb21262ba306f70e2d7ccaac5a59e0'
at Object.renameSync (fs.js:320:18)
The rename works fine on my local server. I'm running node with sudo on AWS and have write access to both directories.
Also, the mv command works fine, which with spawn, could be my workaround.
Is there something special about /tmp on the AWS micro-instance?
A: This is a duplicate of: How do I move file a to a different partition or device in Node.js?
You can't create cross-device hard links, which apparently fs.renameSync does. An EBS volume is a different device than where /tmp is mounted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits